/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2007 Dave Chapman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "plugin.h" PLUGIN_HEADER /* All swcodec targets have BUTTON_SELECT apart from the H10 and M3 */ #if CONFIG_KEYPAD == IRIVER_H10_PAD #define TESTCODEC_EXITBUTTON BUTTON_RIGHT #elif CONFIG_KEYPAD == IAUDIO_M3_PAD #define TESTCODEC_EXITBUTTON BUTTON_RC_PLAY #elif CONFIG_KEYPAD == COWOND2_PAD #define TESTCODEC_EXITBUTTON BUTTON_POWER #else #define TESTCODEC_EXITBUTTON BUTTON_SELECT #endif static const struct plugin_api* rb; CACHE_FUNCTION_WRAPPERS(rb) /* Log functions copied from test_disk.c */ static int line = 0; static int max_line = 0; static int log_fd = -1; static char logfilename[MAX_PATH]; static bool log_init(bool use_logfile) { int h; rb->lcd_getstringsize("A", NULL, &h); max_line = LCD_HEIGHT / h; line = 0; rb->lcd_clear_display(); rb->lcd_update(); if (use_logfile) { rb->create_numbered_filename(logfilename, "/", "test_codec_log_", ".txt", 2 IF_CNFN_NUM_(, NULL)); log_fd = rb->open(logfilename, O_RDWR|O_CREAT|O_TRUNC); return log_fd >= 0; } return true; } static void log_text(char *text, bool advance) { rb->lcd_puts(0, line, text); rb->lcd_update(); if (advance) { if (++line >= max_line) line = 0; if (log_fd >= 0) rb->fdprintf(log_fd, "%s\n", text); } } static void log_close(void) { if (log_fd >= 0) rb->close(log_fd); } struct wavinfo_t { int fd; int samplerate; int channels; int sampledepth; int stereomode; int totalsamples; }; static void* audiobuf; static void* codec_mallocbuf; static size_t audiosize; static char str[MAX_PATH]; /* Our local implementation of the codec API */ static struct codec_api ci; struct test_track_info { struct mp3entry id3; /* TAG metadata */ size_t filesize; /* File total length */ }; static struct test_track_info track; static bool taginfo_ready = true; static volatile unsigned int elapsed; static volatile bool codec_playing; static volatile long endtick; struct wavinfo_t wavinfo; static unsigned char wav_header[44] = { 'R','I','F','F', // 0 - ChunkID 0,0,0,0, // 4 - ChunkSize (filesize-8) 'W','A','V','E', // 8 - Format 'f','m','t',' ', // 12 - SubChunkID 16,0,0,0, // 16 - SubChunk1ID // 16 for PCM 1,0, // 20 - AudioFormat (1=16-bit) 0,0, // 22 - NumChannels 0,0,0,0, // 24 - SampleRate in Hz 0,0,0,0, // 28 - Byte Rate (SampleRate*NumChannels*(BitsPerSample/8) 0,0, // 32 - BlockAlign (== NumChannels * BitsPerSample/8) 16,0, // 34 - BitsPerSample 'd','a','t','a', // 36 - Subchunk2ID 0,0,0,0 // 40 - Subchunk2Size }; static inline void int2le32(unsigned char* buf, int32_t x) { buf[0] = (x & 0xff); buf[1] = (x & 0xff00) >> 8; buf[2] = (x & 0xff0000) >> 16; buf[3] = (x & 0xff000000) >>24; } static inline void int2le24(unsigned char* buf, int32_t x) { buf[0] = (x & 0xff); buf[1] = (x & 0xff00) >> 8; buf[2] = (x & 0xff0000) >> 16; } static inline void int2le16(unsigned char* buf, int16_t x) { buf[0] = (x & 0xff); buf[1] = (x & 0xff00) >> 8; } void init_wav(char* filename) { wavinfo.totalsamples = 0; wavinfo.fd = rb->creat(filename); if (wavinfo.fd >= 0) { /* Write WAV header - we go back and fill in the details at the end */ rb->write(wavinfo.fd, wav_header, sizeof(wav_header)); } } void close_wav(void) { int filesize = rb->filesize(wavinfo.fd); int channels = (wavinfo.stereomode == STEREO_MONO) ? 1 : 2; int bps = 16; /* TODO */ /* We assume 16-bit, Stereo */ rb->lseek(wavinfo.fd,0,SEEK_SET); int2le32(wav_header+4, filesize-8); /* ChunkSize */ int2le16(wav_header+22, channels); int2le32(wav_header+24, wavinfo.samplerate); int2le32(wav_header+28, wavinfo.samplerate * channels * (bps / 8)); /* ByteRate */ int2le16(wav_header+32, channels * (bps / 8)); int2le32(wav_header+40, filesize - 44); /* Subchunk2Size */ rb->write(wavinfo.fd, wav_header, sizeof(wav_header)); rb->close(wavinfo.fd); } /* Returns buffer to malloc array. Only codeclib should need this. */ static void* codec_get_buffer(size_t *size) { DEBUGF("codec_get_buffer(%d)\n",(int)size); *size = CODEC_SIZE; return codec_mallocbuf; } /* Null output */ static bool pcmbuf_insert_null(const void *ch1, const void *ch2, int count) { /* Always successful - just discard data */ (void)ch1; (void)ch2; (void)count; /* Prevent idle poweroff */ rb->reset_poweroff_timer(); return true; } /* 64KB should be enough */ static unsigned char wavbuffer[64*1024]; static inline int32_t clip_sample(int32_t sample) { if ((int16_t)sample != sample) sample = 0x7fff ^ (sample >> 31); return sample; } /* WAV output */ static bool pcmbuf_insert_wav(const void *ch1, const void *ch2, int count) { const int16_t* data1_16; const int16_t* data2_16; const int32_t* data1_32; const int32_t* data2_32; unsigned char* p = wavbuffer; const int scale = wavinfo.sampledepth - 15; const int dc_bias = 1 << (scale - 1); /* Prevent idle poweroff */ rb->reset_poweroff_timer(); if (wavinfo.sampledepth <= 16) { data1_16 = ch1; data2_16 = ch2; switch(wavinfo.stereomode) { case STEREO_INTERLEAVED: while (count--) { int2le16(p,*data1_16++); p += 2; int2le16(p,*data1_16++); p += 2; } break; case STEREO_NONINTERLEAVED: while (count--) { int2le16(p,*data1_16++); p += 2; int2le16(p,*data2_16++); p += 2; } break; case STEREO_MONO: while (count--) { int2le16(p,*data1_16++); p += 2; } break; } } else { data1_32 = ch1; data2_32 = ch2; switch(wavinfo.stereomode) { case STEREO_INTERLEAVED: while (count--) { int2le16(p, clip_sample((*data1_32++ + dc_bias) >> scale)); p += 2; int2le16(p, clip_sample((*data1_32++ + dc_bias) >> scale)); p += 2; } break; case STEREO_NONINTERLEAVED: while (count--) { int2le16(p, clip_sample((*data1_32++ + dc_bias) >> scale)); p += 2; int2le16(p, clip_sample((*data2_32++ + dc_bias) >> scale)); p += 2; } break; case STEREO_MONO: while (count--) { int2le16(p, clip_sample((*data1_32++ + dc_bias) >> scale)); p += 2; } break; } } wavinfo.totalsamples += count; rb->write(wavinfo.fd, wavbuffer, p - wavbuffer); return true; } /* Set song position in WPS (value in ms). */ static void set_elapsed(unsigned int value) { elapsed = value; } /* Read next amount bytes from file buffer to . Will return number of bytes read or 0 if end of file. */ static size_t read_filebuf(void *ptr, size_t size) { if (ci.curpos > (off_t)track.filesize) { return 0; } else { /* TODO: Don't read beyond end of buffer */ rb->memcpy(ptr, audiobuf + ci.curpos, size); ci.curpos += size; return size; } } /* Request pointer to file buffer which can be used to read amount of data. tells the buffer system how much data it should try to allocate. If is 0, end of file is reached. */ static void* request_buffer(size_t *realsize, size_t reqsize) { *realsize = MIN(track.filesize-ci.curpos,reqsize); return (audiobuf + ci.curpos); } /* Advance file buffer position by amount of bytes. */ static void advance_buffer(size_t amount) { ci.curpos += amount; } /* Advance file buffer to a pointer location inside file buffer. */ static void advance_buffer_loc(void *ptr) { ci.curpos = ptr - audiobuf; } /* Seek file buffer to position beginning of file. */ static bool seek_buffer(size_t newpos) { ci.curpos = newpos; return true; } /* Codec should call this function when it has done the seeking. */ static void seek_complete(void) { /* Do nothing */ } /* Request file change from file buffer. Returns true is next track is available and changed. If return value is false, codec should exit immediately with PLUGIN_OK status. */ static bool request_next_track(void) { /* We are only decoding a single track */ return false; } /* Free the buffer area of the current codec after its loaded */ static void discard_codec(void) { /* ??? */ } static void set_offset(size_t value) { /* ??? */ (void)value; } /* Configure different codec buffer parameters. */ static void configure(int setting, intptr_t value) { switch(setting) { case DSP_SWITCH_FREQUENCY: case DSP_SET_FREQUENCY: DEBUGF("samplerate=%d\n",(int)value); wavinfo.samplerate = (int)value; break; case DSP_SET_SAMPLE_DEPTH: DEBUGF("sampledepth = %d\n",(int)value); wavinfo.sampledepth=(int)value; break; case DSP_SET_STEREO_MODE: DEBUGF("Stereo mode = %d\n",(int)value); wavinfo.stereomode=(int)value; break; } } static void init_ci(void) { /* --- Our "fake" implementations of the codec API functions. --- */ ci.codec_get_buffer = codec_get_buffer; if (wavinfo.fd >= 0) { ci.pcmbuf_insert = pcmbuf_insert_wav; } else { ci.pcmbuf_insert = pcmbuf_insert_null; } ci.set_elapsed = set_elapsed; ci.read_filebuf = read_filebuf; ci.request_buffer = request_buffer; ci.advance_buffer = advance_buffer; ci.advance_buffer_loc = advance_buffer_loc; ci.seek_buffer = seek_buffer; ci.seek_complete = seek_complete; ci.request_next_track = request_next_track; ci.discard_codec = discard_codec; ci.set_offset = set_offset; ci.configure = configure; /* --- "Core" functions --- */ /* kernel/ system */ ci.PREFIX(sleep) = rb->PREFIX(sleep); ci.yield = rb->yield; /* strings and memory */ ci.strcpy = rb->strcpy; ci.strncpy = rb->strncpy; ci.strlen = rb->strlen; ci.strcmp = rb->strcmp; ci.strcat = rb->strcat; ci.memset = rb->memset; ci.memcpy = rb->memcpy; ci.memmove = rb->memmove; ci.memcmp = rb->memcmp; ci.memchr = rb->memchr; ci.strcasestr = rb->strcasestr; #if defined(DEBUG) || defined(SIMULATOR) ci.debugf = rb->debugf; #endif #ifdef ROCKBOX_HAS_LOGF ci.logf = rb->logf; #endif ci.qsort = rb->qsort; ci.global_settings = rb->global_settings; #ifdef RB_PROFILE ci.profile_thread = rb->profile_thread; ci.profstop = rb->profstop; ci.profile_func_enter = rb->profile_func_enter; ci.profile_func_exit = rb->profile_func_exit; #endif #ifdef CACHE_FUNCTIONS_AS_CALL ci.invalidate_icache = invalidate_icache; ci.flush_icache = flush_icache; #endif #if NUM_CORES > 1 ci.create_thread = rb->create_thread; ci.thread_thaw = rb->thread_thaw; ci.thread_wait = rb->thread_wait; ci.semaphore_init = rb->semaphore_init; ci.semaphore_wait = rb->semaphore_wait; ci.semaphore_release = rb->semaphore_release; #endif } static void codec_thread(void) { const char* codecname; int res; codecname = rb->get_codec_filename(track.id3.codectype); /* Load the codec and start decoding. */ res = rb->codec_load_file(codecname,&ci); /* Signal to the main thread that we are done */ endtick = *rb->current_tick; codec_playing = false; } static enum plugin_status test_track(const char* filename) { size_t n; int fd; enum plugin_status res = PLUGIN_ERROR; long starttick; long ticks; unsigned long speed; unsigned long duration; const char* ch; /* Display filename (excluding any path)*/ ch = rb->strrchr(filename, '/'); if (ch==NULL) ch = filename; else ch++; rb->snprintf(str,sizeof(str),"%s",ch); log_text(str,true); log_text("Loading...",false); fd = rb->open(filename,O_RDONLY); if (fd < 0) { log_text("Cannot open file",true); goto exit; } track.filesize = rb->filesize(fd); /* Clear the id3 struct */ rb->memset(&track.id3, 0, sizeof(struct mp3entry)); if (!rb->get_metadata(&(track.id3), fd, filename)) { log_text("Cannot read metadata",true); goto exit; } if (track.filesize > audiosize) { log_text("File too large",true); goto exit; } n = rb->read(fd, audiobuf, track.filesize); if (n != track.filesize) { log_text("Read failed.",true); goto exit; } /* Initialise the function pointers in the codec API */ init_ci(); /* Prepare the codec struct for playing the whole file */ ci.filesize = track.filesize; ci.id3 = &track.id3; ci.taginfo_ready = &taginfo_ready; ci.curpos = 0; ci.stop_codec = false; ci.new_track = 0; ci.seek_time = 0; starttick = *rb->current_tick; codec_playing = true; rb->codec_thread_do_callback(codec_thread, NULL); /* Wait for codec thread to die */ while (codec_playing) { rb->sleep(HZ); rb->snprintf(str,sizeof(str),"%d of %d",elapsed,(int)track.id3.length); log_text(str,false); } ticks = endtick - starttick; /* Be sure it is done */ rb->codec_thread_do_callback(NULL, NULL); log_text(str,true); if (wavinfo.fd < 0) { /* Display benchmark information */ rb->snprintf(str,sizeof(str),"Decode time - %d.%02ds",(int)ticks/100,(int)ticks%100); log_text(str,true); duration = track.id3.length / 10; rb->snprintf(str,sizeof(str),"File duration - %d.%02ds",(int)duration/100,(int)duration%100); log_text(str,true); if (ticks > 0) speed = duration * 10000 / ticks; else speed = 0; rb->snprintf(str,sizeof(str),"%d.%02d%% realtime",(int)speed/100,(int)speed%100); log_text(str,true); #ifndef SIMULATOR /* show effective clockrate in MHz needed for realtime decoding */ if (speed > 0) { speed = CPUFREQ_MAX / speed; rb->snprintf(str,sizeof(str),"%d.%02dMHz needed for realtime", (int)speed/100,(int)speed%100); log_text(str,true); } #endif } res = PLUGIN_OK; exit: rb->backlight_on(); if (fd >= 0) { rb->close(fd); } return res; } /* plugin entry point */ enum plugin_status plugin_start(const struct plugin_api* api, const void* parameter) { int result, selection = 0; enum plugin_status res = PLUGIN_OK; int scandir; struct dirent *entry; DIR* dir; char* ch; char dirpath[MAX_PATH]; char filename[MAX_PATH]; rb = api; if (parameter == NULL) { rb->splash(HZ*2, "No File"); return PLUGIN_ERROR; } codec_mallocbuf = rb->plugin_get_audio_buffer(&audiosize); audiobuf = SKIPBYTES(codec_mallocbuf, CODEC_SIZE); audiosize -= CODEC_SIZE; #ifdef HAVE_ADJUSTABLE_CPU_FREQ rb->cpu_boost(true); #endif rb->lcd_clear_display(); rb->lcd_update(); MENUITEM_STRINGLIST( menu, "test_codec", NULL, "Speed test", "Speed test folder", "Write WAV", ); rb->lcd_clear_display(); result=rb->do_menu(&menu,&selection, NULL, false); scandir = 0; if (result==0) { wavinfo.fd = -1; log_init(false); } else if (result==1) { wavinfo.fd = -1; scandir = 1; /* Only create a log file when we are testing a folder */ if (!log_init(true)) { rb->splash(HZ*2, "Cannot create logfile"); res = PLUGIN_ERROR; goto exit; } } else if (result==2) { log_init(false); init_wav("/test.wav"); if (wavinfo.fd < 0) { rb->splash(HZ*2, "Cannot create /test.wav"); res = PLUGIN_ERROR; goto exit; } } else if (result == MENU_ATTACHED_USB) { res = PLUGIN_USB_CONNECTED; goto exit; } else if (result < 0) { res = PLUGIN_OK; goto exit; } if (scandir) { /* Test all files in the same directory as the file selected by the user */ rb->strncpy(dirpath,parameter,sizeof(dirpath)); ch = rb->strrchr(dirpath,'/'); ch[1]=0; DEBUGF("Scanning directory \"%s\"\n",dirpath); dir = rb->opendir(dirpath); if (dir) { entry = rb->readdir(dir); while (entry) { if (!(entry->attribute & ATTR_DIRECTORY)) { rb->snprintf(filename,sizeof(filename),"%s%s",dirpath,entry->d_name); test_track(filename); log_text("", true); } /* Read next entry */ entry = rb->readdir(dir); } rb->closedir(dir); } } else { /* Just test the file */ res = test_track(parameter); /* Close WAV file (if there was one) */ if (wavinfo.fd >= 0) { close_wav(); log_text("Wrote /test.wav",true); } while (rb->button_get(true) != TESTCODEC_EXITBUTTON); } exit: log_close(); #ifdef HAVE_ADJUSTABLE_CPU_FREQ rb->cpu_boost(false); #endif return res; } 479' href='#n479'>479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
/*
** $Id: lstrlib.c,v 1.132.1.4 2008/07/11 17:27:21 roberto Exp $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/


#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define lstrlib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"


/* macro to `unsign' a character */
#define uchar(c)        ((unsigned char)(c))



static int str_len (lua_State *L) {
  size_t l;
  luaL_checklstring(L, 1, &l);
  lua_pushinteger(L, l);
  return 1;
}


static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
  /* relative string position: negative means back from end */
  if (pos < 0) pos += (ptrdiff_t)len + 1;
  return (pos >= 0) ? pos : 0;
}


static int str_sub (lua_State *L) {
  size_t l;
  const char *s = luaL_checklstring(L, 1, &l);
  ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
  ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  if (start < 1) start = 1;
  if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
  if (start <= end)
    lua_pushlstring(L, s+start-1, end-start+1);
  else lua_pushliteral(L, "");
  return 1;
}


static int str_reverse (lua_State *L) {
  size_t l;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  while (l--) luaL_addchar(&b, s[l]);
  luaL_pushresult(&b);
  return 1;
}


static int str_lower (lua_State *L) {
  size_t l;
  size_t i;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  for (i=0; i<l; i++)
    luaL_addchar(&b, tolower(uchar(s[i])));
  luaL_pushresult(&b);
  return 1;
}


static int str_upper (lua_State *L) {
  size_t l;
  size_t i;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  for (i=0; i<l; i++)
    luaL_addchar(&b, toupper(uchar(s[i])));
  luaL_pushresult(&b);
  return 1;
}

static int str_rep (lua_State *L) {
  size_t l;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  int n = luaL_checkint(L, 2);
  luaL_buffinit(L, &b);
  while (n-- > 0)
    luaL_addlstring(&b, s, l);
  luaL_pushresult(&b);
  return 1;
}


static int str_byte (lua_State *L) {
  size_t l;
  const char *s = luaL_checklstring(L, 1, &l);
  ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  int n, i;
  if (posi <= 0) posi = 1;
  if ((size_t)pose > l) pose = l;
  if (posi > pose) return 0;  /* empty interval; return no values */
  n = (int)(pose -  posi + 1);
  if (posi + n <= pose)  /* overflow? */
    luaL_error(L, "string slice too long");
  luaL_checkstack(L, n, "string slice too long");
  for (i=0; i<n; i++)
    lua_pushinteger(L, uchar(s[posi+i-1]));
  return n;
}


static int str_char (lua_State *L) {
  int n = lua_gettop(L);  /* number of arguments */
  int i;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  for (i=1; i<=n; i++) {
    int c = luaL_checkint(L, i);
    luaL_argcheck(L, uchar(c) == c, i, "invalid value");
    luaL_addchar(&b, uchar(c));
  }
  luaL_pushresult(&b);
  return 1;
}


static int writer (lua_State *L, const void* b, size_t size, void* B) {
  (void)L;
  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  return 0;
}


static int str_dump (lua_State *L) {
  luaL_Buffer b;
  luaL_checktype(L, 1, LUA_TFUNCTION);
  lua_settop(L, 1);
  luaL_buffinit(L,&b);
  if (lua_dump(L, writer, &b) != 0)
    luaL_error(L, "unable to dump given function");
  luaL_pushresult(&b);
  return 1;
}



/*
** {======================================================
** PATTERN MATCHING
** =======================================================
*/


#define CAP_UNFINISHED	(-1)
#define CAP_POSITION	(-2)

typedef struct MatchState {
  const char *src_init;  /* init of source string */
  const char *src_end;  /* end (`\0') of source string */
  lua_State *L;
  int level;  /* total number of captures (finished or unfinished) */
  struct {
    const char *init;
    ptrdiff_t len;
  } capture[LUA_MAXCAPTURES];
} MatchState;


#define L_ESC		'%'
#define SPECIALS	"^$*+?.([%-"


static int check_capture (MatchState *ms, int l) {
  l -= '1';
  if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
    return luaL_error(ms->L, "invalid capture index");
  return l;
}


static int capture_to_close (MatchState *ms) {
  int level = ms->level;
  for (level--; level>=0; level--)
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
  return luaL_error(ms->L, "invalid pattern capture");
}


static const char *classend (MatchState *ms, const char *p) {
  switch (*p++) {
    case L_ESC: {
      if (*p == '\0')
        luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
      return p+1;
    }
    case '[': {
      if (*p == '^') p++;
      do {  /* look for a `]' */
        if (*p == '\0')
          luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
        if (*(p++) == L_ESC && *p != '\0')
          p++;  /* skip escapes (e.g. `%]') */
      } while (*p != ']');
      return p+1;
    }
    default: {
      return p;
    }
  }
}


static int match_class (int c, int cl) {
  int res;
  switch (tolower(cl)) {
    case 'a' : res = isalpha(c); break;
    case 'c' : res = iscntrl(c); break;
    case 'd' : res = isdigit(c); break;
    case 'l' : res = islower(c); break;
    case 'p' : res = ispunct(c); break;
    case 's' : res = isspace(c); break;
    case 'u' : res = isupper(c); break;
    case 'w' : res = isalnum(c); break;
    case 'x' : res = isxdigit(c); break;
    case 'z' : res = (c == 0); break;
    default: return (cl == c);
  }
  return (islower(cl) ? res : !res);
}


static int matchbracketclass (int c, const char *p, const char *ec) {
  int sig = 1;
  if (*(p+1) == '^') {
    sig = 0;
    p++;  /* skip the `^' */
  }
  while (++p < ec) {
    if (*p == L_ESC) {
      p++;
      if (match_class(c, uchar(*p)))
        return sig;
    }
    else if ((*(p+1) == '-') && (p+2 < ec)) {
      p+=2;
      if (uchar(*(p-2)) <= c && c <= uchar(*p))
        return sig;
    }
    else if (uchar(*p) == c) return sig;
  }
  return !sig;
}


static int singlematch (int c, const char *p, const char *ep) {
  switch (*p) {
    case '.': return 1;  /* matches any char */
    case L_ESC: return match_class(c, uchar(*(p+1)));
    case '[': return matchbracketclass(c, p, ep-1);
    default:  return (uchar(*p) == c);
  }
}


static const char *match (MatchState *ms, const char *s, const char *p);


static const char *matchbalance (MatchState *ms, const char *s,
                                   const char *p) {
  if (*p == 0 || *(p+1) == 0)
    luaL_error(ms->L, "unbalanced pattern");
  if (*s != *p) return NULL;
  else {
    int b = *p;
    int e = *(p+1);
    int cont = 1;
    while (++s < ms->src_end) {
      if (*s == e) {
        if (--cont == 0) return s+1;
      }
      else if (*s == b) cont++;
    }
  }
  return NULL;  /* string ends out of balance */
}


static const char *max_expand (MatchState *ms, const char *s,
                                 const char *p, const char *ep) {
  ptrdiff_t i = 0;  /* counts maximum expand for item */
  while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
    i++;
  /* keeps trying to match with the maximum repetitions */
  while (i>=0) {
    const char *res = match(ms, (s+i), ep+1);
    if (res) return res;
    i--;  /* else didn't match; reduce 1 repetition to try again */
  }
  return NULL;
}


static const char *min_expand (MatchState *ms, const char *s,
                                 const char *p, const char *ep) {
  for (;;) {
    const char *res = match(ms, s, ep+1);
    if (res != NULL)
      return res;
    else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
      s++;  /* try with one more repetition */
    else return NULL;
  }
}


static const char *start_capture (MatchState *ms, const char *s,
                                    const char *p, int what) {
  const char *res;
  int level = ms->level;
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  ms->capture[level].init = s;
  ms->capture[level].len = what;
  ms->level = level+1;
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
    ms->level--;  /* undo capture */
  return res;
}


static const char *end_capture (MatchState *ms, const char *s,
                                  const char *p) {
  int l = capture_to_close(ms);
  const char *res;
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
  return res;
}


static const char *match_capture (MatchState *ms, const char *s, int l) {
  size_t len;
  l = check_capture(ms, l);
  len = ms->capture[l].len;
  if ((size_t)(ms->src_end-s) >= len &&
      memcmp(ms->capture[l].init, s, len) == 0)
    return s+len;
  else return NULL;
}


static const char *match (MatchState *ms, const char *s, const char *p) {
  init: /* using goto's to optimize tail recursion */
  switch (*p) {
    case '(': {  /* start capture */
      if (*(p+1) == ')')  /* position capture? */
        return start_capture(ms, s, p+2, CAP_POSITION);
      else
        return start_capture(ms, s, p+1, CAP_UNFINISHED);
    }
    case ')': {  /* end capture */
      return end_capture(ms, s, p+1);
    }
    case L_ESC: {
      switch (*(p+1)) {
        case 'b': {  /* balanced string? */
          s = matchbalance(ms, s, p+2);
          if (s == NULL) return NULL;
          p+=4; goto init;  /* else return match(ms, s, p+4); */
        }
        case 'f': {  /* frontier? */
          const char *ep; char previous;
          p += 2;
          if (*p != '[')
            luaL_error(ms->L, "missing " LUA_QL("[") " after "
                               LUA_QL("%%f") " in pattern");
          ep = classend(ms, p);  /* points to what is next */
          previous = (s == ms->src_init) ? '\0' : *(s-1);
          if (matchbracketclass(uchar(previous), p, ep-1) ||
             !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
          p=ep; goto init;  /* else return match(ms, s, ep); */
        }
        default: {
          if (isdigit(uchar(*(p+1)))) {  /* capture results (%0-%9)? */
            s = match_capture(ms, s, uchar(*(p+1)));
            if (s == NULL) return NULL;
            p+=2; goto init;  /* else return match(ms, s, p+2) */
          }
          goto dflt;  /* case default */
        }
      }
    }
    case '\0': {  /* end of pattern */
      return s;  /* match succeeded */
    }
    case '$': {
      if (*(p+1) == '\0')  /* is the `$' the last char in pattern? */
        return (s == ms->src_end) ? s : NULL;  /* check end of string */
      else goto dflt;
    }
    default: dflt: {  /* it is a pattern item */
      const char *ep = classend(ms, p);  /* points to what is next */
      int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
      switch (*ep) {
        case '?': {  /* optional */
          const char *res;
          if (m && ((res=match(ms, s+1, ep+1)) != NULL))
            return res;
          p=ep+1; goto init;  /* else return match(ms, s, ep+1); */
        }
        case '*': {  /* 0 or more repetitions */
          return max_expand(ms, s, p, ep);
        }
        case '+': {  /* 1 or more repetitions */
          return (m ? max_expand(ms, s+1, p, ep) : NULL);
        }
        case '-': {  /* 0 or more repetitions (minimum) */
          return min_expand(ms, s, p, ep);
        }
        default: {
          if (!m) return NULL;
          s++; p=ep; goto init;  /* else return match(ms, s+1, ep); */
        }
      }
    }
  }
}



static const char *lmemfind (const char *s1, size_t l1,
                               const char *s2, size_t l2) {
  if (l2 == 0) return s1;  /* empty strings are everywhere */
  else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
  else {
    const char *init;  /* to search for a `*s2' inside `s1' */
    l2--;  /* 1st char will be checked by `memchr' */
    l1 = l1-l2;  /* `s2' cannot be found after that */
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
      init++;   /* 1st char is already checked */
      if (memcmp(init, s2+1, l2) == 0)
        return init-1;
      else {  /* correct `l1' and `s1' to try again */
        l1 -= init-s1;
        s1 = init;
      }
    }
    return NULL;  /* not found */
  }
}


static void push_onecapture (MatchState *ms, int i, const char *s,
                                                    const char *e) {
  if (i >= ms->level) {
    if (i == 0)  /* ms->level == 0, too */
      lua_pushlstring(ms->L, s, e - s);  /* add whole match */
    else
      luaL_error(ms->L, "invalid capture index");
  }
  else {
    ptrdiff_t l = ms->capture[i].len;
    if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
    if (l == CAP_POSITION)
      lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
    else
      lua_pushlstring(ms->L, ms->capture[i].init, l);
  }
}


static int push_captures (MatchState *ms, const char *s, const char *e) {
  int i;
  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  luaL_checkstack(ms->L, nlevels, "too many captures");
  for (i = 0; i < nlevels; i++)
    push_onecapture(ms, i, s, e);
  return nlevels;  /* number of strings pushed */
}


static int str_find_aux (lua_State *L, int find) {
  size_t l1, l2;
  const char *s = luaL_checklstring(L, 1, &l1);
  const char *p = luaL_checklstring(L, 2, &l2);
  ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  if (init < 0) init = 0;
  else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
  if (find && (lua_toboolean(L, 4) ||  /* explicit request? */
      strpbrk(p, SPECIALS) == NULL)) {  /* or no special characters? */
    /* do a plain search */
    const char *s2 = lmemfind(s+init, l1-init, p, l2);
    if (s2) {
      lua_pushinteger(L, s2-s+1);
      lua_pushinteger(L, s2-s+l2);
      return 2;
    }
  }
  else {
    MatchState ms;
    int anchor = (*p == '^') ? (p++, 1) : 0;
    const char *s1=s+init;
    ms.L = L;
    ms.src_init = s;
    ms.src_end = s+l1;
    do {
      const char *res;
      ms.level = 0;
      if ((res=match(&ms, s1, p)) != NULL) {
        if (find) {
          lua_pushinteger(L, s1-s+1);  /* start */
          lua_pushinteger(L, res-s);   /* end */
          return push_captures(&ms, NULL, 0) + 2;
        }
        else
          return push_captures(&ms, s1, res);
      }
    } while (s1++ < ms.src_end && !anchor);
  }
  lua_pushnil(L);  /* not found */
  return 1;
}


static int str_find (lua_State *L) {
  return str_find_aux(L, 1);
}


static int str_match (lua_State *L) {
  return str_find_aux(L, 0);
}


static int gmatch_aux (lua_State *L) {
  MatchState ms;
  size_t ls;
  const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  const char *p = lua_tostring(L, lua_upvalueindex(2));
  const char *src;
  ms.L = L;
  ms.src_init = s;
  ms.src_end = s+ls;
  for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
       src <= ms.src_end;
       src++) {
    const char *e;
    ms.level = 0;
    if ((e = match(&ms, src, p)) != NULL) {
      lua_Integer newstart = e-s;
      if (e == src) newstart++;  /* empty match? go at least one position */
      lua_pushinteger(L, newstart);
      lua_replace(L, lua_upvalueindex(3));
      return push_captures(&ms, src, e);
    }
  }
  return 0;  /* not found */
}


static int gmatch (lua_State *L) {
  luaL_checkstring(L, 1);
  luaL_checkstring(L, 2);
  lua_settop(L, 2);
  lua_pushinteger(L, 0);
  lua_pushcclosure(L, gmatch_aux, 3);
  return 1;
}


static int gfind_nodef (lua_State *L) {
  return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
                       LUA_QL("string.gmatch"));
}


static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
                                                   const char *e) {
  size_t l, i;
  const char *news = lua_tolstring(ms->L, 3, &l);
  for (i = 0; i < l; i++) {
    if (news[i] != L_ESC)
      luaL_addchar(b, news[i]);
    else {
      i++;  /* skip ESC */
      if (!isdigit(uchar(news[i])))
        luaL_addchar(b, news[i]);
      else if (news[i] == '0')
          luaL_addlstring(b, s, e - s);
      else {
        push_onecapture(ms, news[i] - '1', s, e);
        luaL_addvalue(b);  /* add capture to accumulated result */
      }
    }
  }
}


static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
                                                       const char *e) {
  lua_State *L = ms->L;
  switch (lua_type(L, 3)) {
    case LUA_TNUMBER:
    case LUA_TSTRING: {
      add_s(ms, b, s, e);
      return;
    }
    case LUA_TFUNCTION: {
      int n;
      lua_pushvalue(L, 3);
      n = push_captures(ms, s, e);
      lua_call(L, n, 1);
      break;
    }
    case LUA_TTABLE: {
      push_onecapture(ms, 0, s, e);
      lua_gettable(L, 3);
      break;
    }
  }
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
    lua_pop(L, 1);
    lua_pushlstring(L, s, e - s);  /* keep original text */
  }
  else if (!lua_isstring(L, -1))
    luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); 
  luaL_addvalue(b);  /* add result to accumulator */
}


static int str_gsub (lua_State *L) {
  size_t srcl;
  const char *src = luaL_checklstring(L, 1, &srcl);
  const char *p = luaL_checkstring(L, 2);
  int  tr = lua_type(L, 3);
  int max_s = luaL_optint(L, 4, srcl+1);
  int anchor = (*p == '^') ? (p++, 1) : 0;
  int n = 0;
  MatchState ms;
  luaL_Buffer b;
  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
                      "string/function/table expected");
  luaL_buffinit(L, &b);
  ms.L = L;
  ms.src_init = src;
  ms.src_end = src+srcl;
  while (n < max_s) {
    const char *e;
    ms.level = 0;
    e = match(&ms, src, p);
    if (e) {
      n++;
      add_value(&ms, &b, src, e);
    }
    if (e && e>src) /* non empty match? */
      src = e;  /* skip it */
    else if (src < ms.src_end)
      luaL_addchar(&b, *src++);
    else break;
    if (anchor) break;
  }
  luaL_addlstring(&b, src, ms.src_end-src);
  luaL_pushresult(&b);
  lua_pushinteger(L, n);  /* number of substitutions */
  return 2;
}

/* }====================================================== */


/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
#define MAX_ITEM	512
/* valid flags in a format specification */
#define FLAGS	"-+ #0"
/*
** maximum size of each format specification (such as '%-099.99d')
** (+10 accounts for %99.99x plus margin of error)
*/
#define MAX_FORMAT	(sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)


static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  size_t l;
  const char *s = luaL_checklstring(L, arg, &l);
  luaL_addchar(b, '"');
  while (l--) {
    switch (*s) {
      case '"': case '\\': case '\n': {
        luaL_addchar(b, '\\');
        luaL_addchar(b, *s);
        break;
      }
      case '\r': {
        luaL_addlstring(b, "\\r", 2);
        break;
      }
      case '\0': {
        luaL_addlstring(b, "\\000", 4);
        break;
      }
      default: {
        luaL_addchar(b, *s);
        break;
      }
    }
    s++;
  }
  luaL_addchar(b, '"');
}

static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  const char *p = strfrmt;
  while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */
  if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
    luaL_error(L, "invalid format (repeated flags)");
  if (isdigit(uchar(*p))) p++;  /* skip width */
  if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
  if (*p == '.') {
    p++;
    if (isdigit(uchar(*p))) p++;  /* skip precision */
    if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
  }
  if (isdigit(uchar(*p)))
    luaL_error(L, "invalid format (width or precision too long)");
  *(form++) = '%';
  strncpy(form, strfrmt, p - strfrmt + 1);
  form += p - strfrmt + 1;
  *form = '\0';
  return p;
}


static void addintlen (char *form) {
  size_t l = strlen(form);
  char spec = form[l - 1];
  strcpy(form + l - 1, LUA_INTFRMLEN);
  form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
  form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
}


static int str_format (lua_State *L) {
  int arg = 1;
  size_t sfl;
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  const char *strfrmt_end = strfrmt+sfl;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  while (strfrmt < strfrmt_end) {
    if (*strfrmt != L_ESC)
      luaL_addchar(&b, *strfrmt++);
    else if (*++strfrmt == L_ESC)
      luaL_addchar(&b, *strfrmt++);  /* %% */
    else { /* format item */
      char form[MAX_FORMAT];  /* to store the format (`%...') */
      char buff[MAX_ITEM];  /* to store the formatted item */
      arg++;
      strfrmt = scanformat(L, strfrmt, form);
      switch (*strfrmt++) {
        case 'c': {
          snprintf(buff, MAX_ITEM, form, (int)luaL_checknumber(L, arg));
          break;
        }
        case 'd':  case 'i': {
          addintlen(form);
          snprintf(buff, MAX_ITEM, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
          break;
        }
        case 'o':  case 'u':  case 'x':  case 'X': {
          addintlen(form);
          snprintf(buff, MAX_ITEM, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
          break;
        }
        case 'e':  case 'E': case 'f':
        case 'g': case 'G': {
          snprintf(buff, MAX_ITEM, form, (double)luaL_checknumber(L, arg));
          break;
        }
        case 'q': {
          addquoted(L, &b, arg);
          continue;  /* skip the 'addsize' at the end */
        }
        case 's': {
          size_t l;
          const char *s = luaL_checklstring(L, arg, &l);
          if (!strchr(form, '.') && l >= 100) {
            /* no precision and string is too long to be formatted;
               keep original string */
            lua_pushvalue(L, arg);
            luaL_addvalue(&b);
            continue;  /* skip the `addsize' at the end */
          }
          else {
            snprintf(buff, MAX_ITEM, form, s);
            break;
          }
        }
        default: {  /* also treat cases `pnLlh' */
          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
                               LUA_QL("format"), *(strfrmt - 1));
        }
      }
      luaL_addlstring(&b, buff, strlen(buff));
    }
  }
  luaL_pushresult(&b);
  return 1;
}


static const luaL_Reg strlib[] = {
  {"byte", str_byte},
  {"char", str_char},
  {"dump", str_dump},
  {"find", str_find},
  {"format", str_format},
  {"gfind", gfind_nodef},
  {"gmatch", gmatch},
  {"gsub", str_gsub},
  {"len", str_len},
  {"lower", str_lower},
  {"match", str_match},
  {"rep", str_rep},
  {"reverse", str_reverse},
  {"sub", str_sub},
  {"upper", str_upper},
  {NULL, NULL}
};


static void createmetatable (lua_State *L) {
  lua_createtable(L, 0, 1);  /* create metatable for strings */
  lua_pushliteral(L, "");  /* dummy string */
  lua_pushvalue(L, -2);
  lua_setmetatable(L, -2);  /* set string metatable */
  lua_pop(L, 1);  /* pop dummy string */
  lua_pushvalue(L, -2);  /* string library... */
  lua_setfield(L, -2, "__index");  /* ...is the __index metamethod */
  lua_pop(L, 1);  /* pop metatable */
}


/*
** Open string library
*/
LUALIB_API int luaopen_string (lua_State *L) {
  luaL_register(L, LUA_STRLIBNAME, strlib);
#if defined(LUA_COMPAT_GFIND)
  lua_getfield(L, -1, "gmatch");
  lua_setfield(L, -2, "gfind");
#endif
  createmetatable(L);
  return 1;
}