[xiph-commits] r7017 - in icecast/branches/kh/libshout: . examples

brendan at dactyl.lonelymoon.com brendan
Tue Jul 6 00:13:03 PDT 2004


include include/shout src
Message-ID: <20040706071303.4F17F9AAAB at dactyl.lonelymoon.com>

Author: brendan
Date: Tue Jul  6 00:13:03 2004
New Revision: 7017

Added:
icecast/branches/kh/libshout/NEWS
icecast/branches/kh/libshout/examples/example2.c
icecast/branches/kh/libshout/src/ogg.c
Modified:
icecast/branches/kh/libshout/Makefile.am
icecast/branches/kh/libshout/configure.in
icecast/branches/kh/libshout/examples/Makefile.am
icecast/branches/kh/libshout/examples/example.c
icecast/branches/kh/libshout/include/Makefile.am
icecast/branches/kh/libshout/include/shout/Makefile.am
icecast/branches/kh/libshout/include/shout/shout.h.in
icecast/branches/kh/libshout/src/Makefile.am
icecast/branches/kh/libshout/src/mp3.c
icecast/branches/kh/libshout/src/shout.c
icecast/branches/kh/libshout/src/shout_private.h
icecast/branches/kh/libshout/src/util.c
icecast/branches/kh/libshout/src/util.h
Log:
Finish import of KH branch.


Modified: icecast/branches/kh/libshout/Makefile.am
===================================================================
--- icecast/branches/kh/libshout/Makefile.am	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/Makefile.am	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,29 +1,23 @@
## Process this file with automake to produce Makefile.in

-AUTOMAKE_OPTIONS = 1.6 foreign
+AUTOMAKE_OPTIONS = 1.6 foreign dist-bzip2
ACLOCAL_AMFLAGS = -I m4

-SUBDIRS = include src examples debian doc win32
+SUBDIRS = include src examples

-EXTRA_DIST = INSTALL m4/shout.m4 m4/ac_config_libconfig_in.m4 m4/acx_pthread.m4 \
-	m4/ogg.m4 m4/vorbis.m4 m4/xiph_compiler.m4 m4/xiph_net.m4 \
-	m4/xiph_types.m4
+EXTRA_DIST = README COPYING NEWS m4

-DISTCLEANFILES = shout-config.in
-
-docdir = $(datadir)/doc/$(PACKAGE)
-doc_DATA = COPYING README examples/example.c
-
-m4datadir = $(datadir)/aclocal
-m4data_DATA = m4/shout.m4
-
if HAVE_PKGCONFIG
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = shout.pc
else
bin_SCRIPTS = shout-config
endif
+DISTCLEANFILES = shout-config.in

+## SCCS stuff (for BitKeeper)
+GET = true
+
debug:
$(MAKE) all CFLAGS="@DEBUG@"


Added: icecast/branches/kh/libshout/NEWS
===================================================================
--- icecast/branches/kh/libshout/NEWS	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/NEWS	2004-07-06 07:12:13 UTC (rev 7017)
@@ -0,0 +1,160 @@
+1.29
+----
+. theora wasn't optional, allow building without it
+. minor tweaks to build
+
+1.28
+----
+. fix silly build error in the examples. was actually a header issue
+
+1.27
+----
+. Add multiple ogg codec handling, time vorbis and theora logical
+  streams. Stream unhandled but paged ogg codecs.
+
+1.26
+----
+. state all dependent libs, or else static linking fails
+
+1.25
+----
+. update sock code
+. don't stall in non blocking mode waiting for reply from server
+. re-sync timing fixups in vorbis and mp3 handlers
+
+1.24
+----
+. minor memory leak on shout_new plugged
+. update the avl code, nothing significant wrt libshout, just sync-up
+
+1.23
+----
+. signal mask wokaround on openbsd
+
+1.22
+----
+. re-sync withe CVS and the icecast updates of net
+
+1.21
+----
+. added missing prototypes added in v1.0 CVS
+. fixed incorrect error return in the format specific send.
+. changed sock_connected to use sock_set_error for sock_error usage
+. remove bad use of sock_recoverable
+. some prototype cleanups
+. updated net, sock_connected API change, async blocking connect fix
+. added write check to autoconf, got lost from m4 update
+. reset header size on close, else it can cause an accumulation of
+  headers to be sent on subsequent connections to the server, even
+  causing it to fill up and bomb out with a malloc error.
+
+1.20
+----
+. Username default was not set correctly and a subsequent check
+  was missing.
+. some minor code cleanups
+
+1.19
+----
+. Add missing metadata functions
+. update the thread code, to fix potential leaks
+
+1.18
+----
+. added timeout (5s) when reading headers in blocking mode
+. added function to alter timeout setting (in ms)
+. fixed stuffed m4 macro
+
+1.17
+----
+. updated m4 macros to work done in CVS.
+. updated subtrees to include fixes sent to CVS
+. Added shout_init, shout_shutdown from CVS to bring back CVS compatability
+
+1.16
+----
+. fix serial number 0 bug left from cvs
+. use send_oggpage in send_vorbis, utilises the writev and queueing
+  facilities.
+. fixed a couple of silly bugs for shout_sync
+
+1.15
+----
+. update autoconf scripts
+. fix build problems for some platforms
+
+1.14
+----
+. Merge shout_send_ogg into shout_send using new format type
+  SHOUT_FORMAT_VORBISPAGE. This also means no shout substructure created
+  but not used. modified shout_send slightly
+. removed the last users of unhandled short write in sock_write_bytes.
+. Added shout-config, matches up with CVS now
+. check for __VAR_ARGS__
+. clean up top level Makefile.am, refers to m4 directory
+. fix leaks in shout_set_metadata
+
+1.13
+----
+. rework xaudiocast and icy logins, now they can handle short writes.
+. altered code route, so that that each protocol requires a handler for
+  creating requests and a handler for parsing responses.
+. state a limit on the amount of bytes stored in the pending queue,
+  currently 64k but a setter could be used to alter
+. misc cleanups left out from previous release.
+
+1.12
+----
+. removed static array representing pending write queue, replaced
+  with linked list with byte counts.
+. much code removal, due to old pending array removal and state
+  information migration. Pending Write queue implemented as list
+  simplified code as well.
+. Add hack for building on OBSD wrt _XOPEN_SOURCE
+
+1.11
+----
+. big cleanup release, mainly relating to connection logic.
+. Add the notion of state to a shout_t to help at connection time.
+. fix a potential thread attribute bug introduce last time.
+. Get nearer to the CVS updates.
+. Drop ICE logins as per CVS.
+. Updated ogg and vorbis autoconf macro's to mroe recent ones
+
+1.10
+----
+. minor compiler warning cleanups
+. re-sync to recent CVS code, mainly tab removal but code updates as well
+. all threads to inherit scheduling attributes, mainly for realtime
+
+1.9
+- change build setup to more like what I and brendan have put in CVS
+  . put headers in config.h
+  . use XIPH_CFLAGS
+  . check for various pthread flags
+  . build exmaples directory
+- update external shout codes to match CVS
+- deprecate the use of shout_set_bitrate, not sure if this is a good idea.
+- add shout-audio-info,  not nice at all but matches CVS.
+- update thread/avl/net/httpp to CVS.
+  . drops some of the unneeded -I flags.
+
+1.8
+- shout_close didn't free pending queue
+- only do so many non-blocking checks 60 for connection, 20 for header acceptance
+- REFUSED didn't have a pretty print message
+
+v1.7
+- fixed a couple of reuse after free cases and a pending write queue problem
+
+v1.6
+- changed mime header from x-ogg to ogg
+
+v1.5
+- make sure shout_close clear various flags.
+
+v1.4
+- Have a function for returning the version
+- writev support added.
+- non-blocking enabled on HTTP connections
+- sock uses newer posix calls for sockets, but falls back to ipv4 only

Modified: icecast/branches/kh/libshout/configure.in
===================================================================
--- icecast/branches/kh/libshout/configure.in	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/configure.in	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,21 +1,22 @@
-# Process this file with autoconf to produce a configure script.
-# $Id: configure.in,v 1.67 2004/01/30 00:17:26 oddsock Exp $
+dnl Process this file with autoconf to produce a configure script.

+
m4_define(libshout_major, 2)
m4_define(libshout_minor, 0)
m4_define(libshout_micro, 0)
m4_define(libshout_version,
-  m4_if(libshout_micro, 0, libshout_major.libshout_minor,
-   libshout_major.libshout_minor.libshout_micro))
+  m4_if(libshout_micro, 0, libshout_major.libshout_minor-kh30,
+   libshout_major.libshout_minor.libshout_micro-30))

-AC_INIT([libshout], libshout_version, [icecast-dev at xiph.org])
-AC_PREREQ([2.54])
+AC_INIT([libshout], libshout_version, [karl at xiph.org])
+AC_PREREQ(2.54)
AC_CONFIG_SRCDIR([src/shout.c])
-AM_CONFIG_HEADER(config.h)
+AM_INIT_AUTOMAKE
+AM_CONFIG_HEADER([config.h])
+
# config.h guard
AH_TOP([#ifndef __CONFIG_H__
#define __CONFIG_H__ 1])
-AH_BOTTOM([#endif])

AC_DEFINE([LIBSHOUT_MAJOR], libshout_major, [Shout library major version])
AC_DEFINE([LIBSHOUT_MINOR], libshout_minor, [Shout library minor version])
@@ -23,86 +24,87 @@

VERSION=libshout_version

-AM_INIT_AUTOMAKE([libshout], libshout_version)
AM_MAINTAINER_MODE

-dnl create our name mangling macro
-dnl the prefix must be hardwired because of AH limitations
-AH_VERBATIM([_mangle], [
-/* name mangling to protect code we share with other libraries */
-#define _mangle(proc) _shout_ ## proc
-])
-
AC_PROG_CC
-AM_PROG_LIBTOOL
+AC_PROG_LIBTOOL

dnl Set some options based on environment
-
-dnl openbsd headers break when _XOPEN_SOURCE is defined but without it seems
-dnl to be fine
-case "$ac_cv_host" in
-   *openbsd* | *solaris* | *irix*)
+# only openbsd has shown up as being broken wrt _XOPEN_SOURCE
+case $host in
+   *bsd* | *irix*)
;;
-   *) AC_DEFINE(_XOPEN_SOURCE, 600, [Define if you have POSIX and XPG specifications])
+   *) AC_DEFINE(_XOPEN_SOURCE, 600, [Define if you have POSIX and XPG])
;;
esac
-if test -z "$GCC"; then
-        case $host in
-        *-*-irix*)
-                DEBUG="-g -signed"
-                CFLAGS="-O2 -w -signed"
-                PROFILE="-p -g3 -O2 -signed"
-		;;
-        sparc-sun-solaris*)
-                DEBUG="-v -g"
-                CFLAGS="-xO4 -fast -w -fsimple -native -xcg92"
-                PROFILE="-v -xpg -g -xO4 -fast -native -fsimple -xcg92 -Dsuncc"
-		;;
-        *)
-                DEBUG="-g"
-                CFLAGS="-O"
-                PROFILE="-g -p"
-		;;
-        esac
-else
-        XIPH_CFLAGS="-Wall -ffast-math -fsigned-char"
-        AC_DEFINE(_GNU_SOURCE, ,[Define if you have POSIX and GNU specifications])
-        DEBUG="-g"
-        PROFILE="-pg -g"
+#
+case $host in
+*solaris*)
+        AC_DEFINE(__EXTENSIONS__, 1, [define to 1 for fix some headers])
+;;
+esac
+if test -n "$GCC"; then
+    XIPH_CPPFLAGS="-W"
+    dnl XIPH_CPPFLAGS="-ffast-math -fsigned-char"
+    DEBUG="-g"
+    PROFILE="-pg -g"
fi

dnl Checks for programs.

+dnl Checks for libraries.
+
dnl Checks for header files.
AC_HEADER_STDC
-AC_CHECK_HEADERS([strings.h])
+AC_HEADER_TIME
+AC_CHECK_HEADERS(sys/time.h)

dnl Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
-XIPH_C99_INTTYPES
+
+XIPH_FUNC_VA_COPY
+XIPH_C_ATTRIBUTE

+AC_TRY_COMPILE([#define f(x,...) printf(x , __VA_ARGS__)], ,
+    AC_DEFINE(HAVE_VA_ARGS,1,[Define if __VA_ARGS__ is supported]))
+
+AH_BOTTOM([
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#elif HAVE_STDINT_H
+#include <stdint.h>
+#endif
+])
+
+dnl Check for types
+AC_CHECK_TYPE([uint64_t],,AC_ERROR([could not find a uint64_t type]))
+
dnl Checks for library functions.
-AC_SEARCH_LIBS([nanosleep], [rt],
-  [AC_DEFINE([HAVE_NANOSLEEP], [1],
-    [Define if you have the nanosleep function])])
+ac_save_LIBS="$LIBS"
+LIBS=""
+AC_SEARCH_LIBS([nanosleep],[rt],
+        [AC_DEFINE([HAVE_NANOSLEEP],1,[Define if you have the nanosleep function])
+        XIPH_VAR_PREPEND([XIPH_LIBS],[$LIBS])
+        ])
+LIBS="$ac_save_LIBS"

dnl Module checks
XIPH_NET

-dnl Extra dependencies
-AC_ARG_ENABLE([thread],
-  AC_HELP_STRING([--disable-thread],[do not build with thread support even if it is available]))
-
+AC_ARG_ENABLE([pthread],
+  [AC_HELP_STRING([--disable-thread],[do not link with thread support even if it is available])])
SHOUT_THREADSAFE="0"
-if test "$enable_thread" != "no"
+if test "$enable_pthread" != "no"
then
ACX_PTHREAD([
-    LIBS="$LIBS $PTHREAD_LIBS"
-    XIPH_CFLAGS="$XIPH_CFLAGS $PTHREAD_CFLAGS $PTHREAD_CPPFLAGS"
+    XIPH_VAR_PREPEND([XIPH_LIBS],[$PTHREAD_LIBS])
+    XIPH_VAR_APPEND([XIPH_CPPFLAGS],[$PTHREAD_CPPFLAGS])
+    XIPH_VAR_APPEND([XIPH_CFLAGS],[$PTHREAD_CFLAGS])
CC="$PTHREAD_CC"
SHOUT_THREADSAFE="1"
])
fi
+
AC_SUBST([SHOUT_THREADSAFE])
AM_CONDITIONAL([HAVE_THREAD], [test "$SHOUT_THREADSAFE" = "1"])
if test "$SHOUT_THREADSAFE" != "1"
@@ -111,13 +113,17 @@
fi

XIPH_PATH_VORBIS
-VORBIS_LIBS="$VORBIS_LDFLAGS $VORBIS_LIBS"
-XIPH_CFLAGS="$XIPH_CFLAGS $VORBIS_CFLAGS"
+XIPH_VAR_APPEND([XIPH_CPPFLAGS],[$VORBIS_CFLAGS])
+XIPH_VAR_PREPEND([XIPH_LIBS],[$VORBIS_LDFLAGS $VORBISENC_LIBS $VORBIS_LIBS])

+XIPH_PATH_THEORA(,[AC_MSG_WARN([Theora lib not found, skipping])])
+XIPH_VAR_APPEND([XIPH_CPPFLAGS],[$THEORA_CFLAGS])
+XIPH_VAR_PREPEND([XIPH_LIBS],[$THEORA_LDFLAGS $THEORA_LIBS])
+
dnl pkgconfig/shout-config.
dnl If pkgconfig is found, use it and disable shout-config, otherwise do the
dnl opposite, unless the user overrides.
-
+
AC_ARG_ENABLE([pkgconfig],
AC_HELP_STRING([--disable-pkgconfig],[disable pkgconfig data files (auto)]),
[dopkgconfig="$enableval"], [dopkgconfig="maybe"])
@@ -132,7 +138,7 @@
AM_CONDITIONAL([HAVE_PKGCONFIG], [test "$PKGCONFIG" != "no"])

# Build shout-config, shout.pc
-
+
# I hate myself for doing this.
save_prefix="$prefix"
if test "$prefix" = "NONE"
@@ -142,32 +148,43 @@
eval shout_includedir="$includedir"
prefix="$save_prefix"

+
+# Build shout-config
SHOUT_VERSION="$VERSION"
-SHOUT_CPPFLAGS="-I$shout_includedir $VORBIS_CFLAGS $PTHREAD_CPPFLAGS"
+SHOUT_LIBS="-lshout"
+SHOUT_LIBDEPS="$THEORA_LIBS $VORBIS_LIBS $PTHREAD_LIBS"
+XIPH_VAR_APPEND([SHOUT_CPPFLAGS], [-I$shout_includedir $VORBIS_CFLAGS $PTHREAD_CPPFLAGS])
SHOUT_CFLAGS="$PTHREAD_CFLAGS"
-SHOUT_LIBS="-lshout"

-XIPH_CLEAN_CCFLAGS([$SHOUT_CPPFLAGS], [SHOUT_CPPFLAGS])
-XIPH_CLEAN_CCFLAGS([$SHOUT_CFLAGS], [SHOUT_CFLAGS])
-XIPH_CLEAN_CCFLAGS([$VORBIS_LIBS $PTHREAD_LIBS $LIBS], [SHOUT_LIBDEPS])
-AC_SUBST(SHOUT_LIBDEPS)
-AC_SUBST(SHOUT_CPPFLAGS)
-AC_SUBST(SHOUT_CFLAGS)
AC_CONFIG_LIBCONFIG_IN_STATIC
AC_CONFIG_LIBCONFIG_IN([shout])

+AH_BOTTOM([#endif])
+
dnl Make substitutions

AC_SUBST(LIBTOOL_DEPS)
-AC_SUBST(OPT)
-AC_SUBST(LIBS)
AC_SUBST(DEBUG)
-AC_SUBST(CFLAGS)
AC_SUBST(PROFILE)
AC_SUBST(XIPH_CFLAGS)
AC_SUBST(XIPH_CPPFLAGS)
+AC_SUBST(XIPH_LIBS)
+AC_SUBST(SHOUT_CPPFLAGS)
+AC_SUBST(SHOUT_CFLAGS)
+AC_SUBST(SHOUT_LIBS)
+AC_SUBST(SHOUT_LIBDEPS)

-AC_OUTPUT([Makefile debian/Makefile include/Makefile include/shout/Makefile
-  include/shout/shout.h src/Makefile src/net/Makefile src/timing/Makefile
-  src/thread/Makefile src/avl/Makefile src/httpp/Makefile doc/Makefile
-  examples/Makefile win32/Makefile shout-config shout.pc])
+AC_OUTPUT([Makefile
+include/Makefile
+include/shout/Makefile
+include/shout/shout.h
+src/Makefile
+src/net/Makefile
+src/timing/Makefile
+src/thread/Makefile
+src/avl/Makefile
+src/httpp/Makefile
+examples/Makefile
+shout-config
+shout.pc
+])

Modified: icecast/branches/kh/libshout/examples/Makefile.am
===================================================================
--- icecast/branches/kh/libshout/examples/Makefile.am	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/examples/Makefile.am	2004-07-06 07:12:13 UTC (rev 7017)
@@ -2,10 +2,12 @@

AUTOMAKE_OPTIONS = foreign

-noinst_PROGRAMS = example
+noinst_PROGRAMS = example example2

example_SOURCES = example.c
-example_LDADD = ../src/libshout.la $(VORBIS_LIBS)
+example2_SOURCES = example2.c
+LDADD = ../src/libshout.la $(XIPH_LIBS)
AM_CFLAGS = @XIPH_CFLAGS@
+AM_CPPFLAGS = @XIPH_CFLAGS@

INCLUDES = -I$(top_builddir)/include

Modified: icecast/branches/kh/libshout/examples/example.c
===================================================================
--- icecast/branches/kh/libshout/examples/example.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/examples/example.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -6,14 +6,13 @@

#include <shout/shout.h>

-int main()
+int main(int argc, char **argv)
{
+    FILE *fptr = stdin;
shout_t *shout;
char buff[4096];
long read, ret, total;

-	shout_init();
-
if (!(shout = shout_new())) {
printf("Could not allocate shout_t\n");
return 1;
@@ -23,17 +22,9 @@
printf("Error setting hostname: %s\n", shout_get_error(shout));
return 1;
}
-
-	if (shout_set_protocol(shout, SHOUT_PROTOCOL_HTTP) != SHOUTERR_SUCCESS) {
-		printf("Error setting protocol: %s\n", shout_get_error(shout));
-		return 1;
-	}
-
-	if (shout_set_port(shout, 8000) != SHOUTERR_SUCCESS) {
-		printf("Error setting port: %s\n", shout_get_error(shout));
-		return 1;
-	}
-
+	shout_set_user(shout, "source");
+	shout_set_password(shout, "hackem");
+	shout_set_port(shout, 8002);
if (shout_set_password(shout, "hackme") != SHOUTERR_SUCCESS) {
printf("Error setting password: %s\n", shout_get_error(shout));
return 1;
@@ -42,27 +33,20 @@
printf("Error setting mount: %s\n", shout_get_error(shout));
return 1;
}
+	shout_set_format(shout, SHOUT_FORMAT_OGG);

-	if (shout_set_user(shout, "source") != SHOUTERR_SUCCESS) {
-		printf("Error setting user: %s\n", shout_get_error(shout));
-		return 1;
-	}
-
-	if (shout_set_format(shout, SHOUT_FORMAT_VORBIS) != SHOUTERR_SUCCESS) {
-		printf("Error setting user: %s\n", shout_get_error(shout));
-		return 1;
-	}
-
if (shout_open(shout) == SHOUTERR_SUCCESS) {
printf("Connected to server...\n");
total = 0;
+        if (argc > 1)
+            fptr = fopen (argv[1], "rb");
while (1) {
-			read = fread(buff, 1, sizeof(buff), stdin);
+			read = fread(buff, 1, sizeof(buff), fptr);
total = total + read;

if (read > 0) {
ret = shout_send(shout, buff, read);
-				if (ret != SHOUTERR_SUCCESS) {
+				if (ret < SHOUTERR_SUCCESS) {
printf("DEBUG: Send error: %s\n", shout_get_error(shout));
break;
}
@@ -70,6 +54,7 @@
break;
}

+            printf ("delay is %d ms\n", shout_delay(shout));
shout_sync(shout);
}
} else {
@@ -77,8 +62,7 @@
}

shout_close(shout);
+    fclose (fptr);

-	shout_shutdown();
-
return 0;
}

Added: icecast/branches/kh/libshout/examples/example2.c
===================================================================
--- icecast/branches/kh/libshout/examples/example2.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/examples/example2.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -0,0 +1,72 @@
+/* example.c: Demonstration of the libshout API. */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <shout/shout.h>
+
+shout_t *shout;
+
+int try()
+{
+	int ret;
+
+	if (shout_set_host(shout, "localhost") != SHOUTERR_SUCCESS) {
+		printf("Error setting hostname: %s\n", shout_get_error(shout));
+		return 1;
+	}
+	shout_set_port(shout, 8000);
+	if (shout_set_password(shout, "hackme") != SHOUTERR_SUCCESS) {
+		printf("Error setting password: %s\n", shout_get_error(shout));
+		return 1;
+	}
+	if (shout_set_mount(shout, "/example.ogg") != SHOUTERR_SUCCESS) {
+		printf("Error setting mount: %s\n", shout_get_error(shout));
+		return 1;
+	}
+	/* shout_set_format(shout, SHOUT_FORMAT_MP3); */
+    shout_set_nonblocking (shout, 1);
+
+    while (1)
+    {
+        ret = shout_open(shout) == SHOUTERR_SUCCESS;
+        if (ret == SHOUTERR_SUCCESS)
+        {
+            /* printf("Connected to server...\n"); */
+            break;
+        } else if (ret == SHOUTERR_PENDING)
+            printf ("pending\n");
+        else
+        {
+            printf("Error connecting: %s\n", shout_get_error(shout));
+        }
+        usleep (300);
+    }
+
+    shout_close(shout);
+
+	return 0;
+}
+
+int main()
+{
+    int countdown = 100;
+
+	if (!(shout = shout_new()))
+    {
+		printf("Could not allocate shout_t\n");
+		return 1;
+	}
+
+    while (--countdown)
+    {
+        try ();
+        usleep(100);
+    }
+    shout_free (shout);
+
+    return 0;
+}
+

Modified: icecast/branches/kh/libshout/include/Makefile.am
===================================================================
--- icecast/branches/kh/libshout/include/Makefile.am	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/include/Makefile.am	2004-07-06 07:12:13 UTC (rev 7017)
@@ -4,4 +4,11 @@

SUBDIRS = shout

-EXTRA_DIST = os.h
+# SCCS stuff (for BitKeeper)
+GET = true
+
+debug:
+	$(MAKE) all CFLAGS="@DEBUG@"
+
+profile:
+	$(MAKE) all CFLAGS="@PROFILE@"

Modified: icecast/branches/kh/libshout/include/shout/Makefile.am
===================================================================
--- icecast/branches/kh/libshout/include/shout/Makefile.am	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/include/shout/Makefile.am	2004-07-06 07:12:13 UTC (rev 7017)
@@ -4,3 +4,12 @@

includedir = $(prefix)/include/shout
nodist_include_HEADERS = shout.h
+
+# SCCS stuff (for BitKeeper)
+GET = bk get -Sq
+
+debug:
+	$(MAKE) all CFLAGS="@DEBUG@"
+
+profile:
+	$(MAKE) all CFLAGS="@PROFILE@"

Modified: icecast/branches/kh/libshout/include/shout/shout.h.in
===================================================================
--- icecast/branches/kh/libshout/include/shout/shout.h.in	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/include/shout/shout.h.in	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,64 +1,50 @@
/*  shout.h
- *
- *  API for libshout, the streaming library for icecast
- *
- *  Copyright (C) 2002-2003 the Icecast team <team at icecast.org>
- *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Library General Public
- *  License as published by the Free Software Foundation; either
- *  version 2 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Library General Public License for more details.
- *
- *  You should have received a copy of the GNU Library General Public
- *  License along with this library; if not, write to the Free
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
+**
+**  API for libshout, the streaming library for icecast
+*/
#ifndef __LIBSHOUT_SHOUT_H__
#define __LIBSHOUT_SHOUT_H__

#include <sys/types.h>
-#ifdef WIN32
-#include <os.h>
-#endif

-#define SHOUTERR_SUCCESS	(0)
-#define SHOUTERR_INSANE		(-1)
-#define SHOUTERR_NOCONNECT	(-2)
-#define SHOUTERR_NOLOGIN	(-3)
-#define SHOUTERR_SOCKET		(-4)
-#define SHOUTERR_MALLOC		(-5)
-#define SHOUTERR_METADATA	(-6)
-#define SHOUTERR_CONNECTED	(-7)
-#define SHOUTERR_UNCONNECTED	(-8)
-#define SHOUTERR_UNSUPPORTED	(-9)
+#define SHOUTERR_SUCCESS            (0)
+#define SHOUTERR_INSANE             (-1)
+#define SHOUTERR_NOCONNECT          (-2)
+#define SHOUTERR_NOLOGIN            (-3)
+#define SHOUTERR_SOCKET             (-4)
+#define SHOUTERR_MALLOC             (-5)
+#define SHOUTERR_METADATA           (-6)
+#define SHOUTERR_CONNECTED          (-7)
+#define SHOUTERR_UNCONNECTED        (-8)
+#define SHOUTERR_UNSUPPORTED        (-9)
+#define SHOUTERR_PENDING            (-11)
+#define SHOUTERR_BUSY               (-12)
+#define SHOUTERR_PENDING_FULL       (-13)

-#define SHOUT_FORMAT_VORBIS	(0)
-#define SHOUT_FORMAT_MP3	(1)
+#define SHOUT_FORMAT_VORBIS         (0)
+#define SHOUT_FORMAT_MP3            (1)
+#define SHOUT_FORMAT_VORBISPAGE     (2)
+#define SHOUT_FORMAT_OGG            (3)

-#define SHOUT_PROTOCOL_HTTP		(0)
-#define SHOUT_PROTOCOL_XAUDIOCAST	(1)
-#define SHOUT_PROTOCOL_ICY		(2)
+#define SHOUT_PROTOCOL_HTTP         (0)
+#define SHOUT_PROTOCOL_XAUDIOCAST   (1)
+#define SHOUT_PROTOCOL_ICY          (2)

-#define SHOUT_AI_BITRATE	"bitrate"
-#define SHOUT_AI_SAMPLERATE	"samplerate"
-#define SHOUT_AI_CHANNELS	"channels"
-#define SHOUT_AI_QUALITY	"quality"
+#define SHOUT_AI_BITRATE            "bitrate"
+#define SHOUT_AI_SAMPLERATE         "samplerate"
+#define SHOUT_AI_CHANNELS           "channels"
+#define SHOUT_AI_QUALITY            "quality"

-typedef struct shout shout_t;
-typedef struct _util_dict shout_metadata_t;
-
#ifdef __cplusplus
extern "C" {
#endif

+typedef struct shout shout_t;
+typedef struct _util_dict shout_metadata_t;
+
/* initializes the shout library. Must be called before anything else */
void shout_init(void);
-
+
/* shuts down the shout library, deallocating any global storage. Don't call
* anything afterwards */
void shout_shutdown(void);
@@ -142,28 +128,25 @@
int shout_close(shout_t *self);

/* Send data to the server, parsing it for format specific timing info */
-int shout_send(shout_t *self, const unsigned char *data, size_t len);
+int shout_send(shout_t *self, const void *data, size_t len);

/* Send unparsed data to the server.  Do not use this unless you know
* what you are doing.
* Returns the number of bytes written, or < 0 on error.
*/
-ssize_t shout_send_raw(shout_t *self, const unsigned char *data, size_t len);
+int shout_send_raw (shout_t *self, const void *data, size_t len);

+
/* Puts caller to sleep until it is time to send more data to the server */
void shout_sync(shout_t *self);

/* Amount of time in ms caller should wait before sending again */
int shout_delay(shout_t *self);
-
+
/* Sets MP3 metadata.
* Returns:
- *   SHOUTERR_SUCCESS
- *   SHOUTERR_UNSUPPORTED if format isn't MP3
- *   SHOUTERR_MALLOC
- *   SHOUTERR_INSANE
- *   SHOUTERR_NOCONNECT
- *   SHOUTERR_SOCKET
+ *   SHOUTERR_SUCCESS on success
+ *   SHOUTERR_UNSUPPORTED if protocol isn't Icy or X-Audiocast
*/
int shout_set_metadata(shout_t *self, shout_metadata_t *metadata);

@@ -180,12 +163,21 @@
*   SHOUTERR_MALLOC if memory can't be allocated */
int shout_metadata_add(shout_metadata_t *self, const char *name, const char *value);

-#ifdef __cplusplus
-}
-#endif
+/* set/unset blocking mode on the shout socket */
+void shout_set_nonblocking (shout_t *self, const int nonblock);

+/* flush any outstanding buffers */
+int shout_send_pending (shout_t *self);
+
+/* report is connection is ready for audio data */
+int shout_connection_ready (shout_t *self);
+
/* --- Compiled features --- */

#define SHOUT_THREADSAFE @SHOUT_THREADSAFE@

+#ifdef __cplusplus
+}
+#endif
+
#endif /* __LIBSHOUT_SHOUT_H__ */

Modified: icecast/branches/kh/libshout/src/Makefile.am
===================================================================
--- icecast/branches/kh/libshout/src/Makefile.am	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/Makefile.am	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,22 +1,19 @@
## Process this with automake to create Makefile.in

-AUTOMAKE_OPTIONS = foreign 1.6
+AUTOMAKE_OPTIONS = foreign

-if HAVE_THREAD
-  MAYBE_THREAD = thread
-  MAYBE_THREAD_LIB = thread/libicethread.la
-endif
-SUBDIRS = avl net timing httpp $(MAYBE_THREAD)
+SUBDIRS = avl net timing httpp thread

lib_LTLIBRARIES = libshout.la
libshout_la_LDFLAGS = -version-info 3:0:0
+AM_CFLAGS = @XIPH_CFLAGS@
+AM_CPPFLAGS = @XIPH_CPPFLAGS@

noinst_HEADERS = shout_private.h util.h
-libshout_la_SOURCES = shout.c util.c vorbis.c mp3.c
-AM_CFLAGS = @XIPH_CFLAGS@
+libshout_la_SOURCES = shout.c util.c ogg.c mp3.c

libshout_la_LIBADD = net/libicenet.la timing/libicetiming.la avl/libiceavl.la\
-		httpp/libicehttpp.la $(MAYBE_THREAD_LIB) $(VORBIS_LIBS)
+		httpp/libicehttpp.la thread/libicethread.la

INCLUDES = -I$(top_builddir)/include

@@ -25,3 +22,4 @@

profile:
$(MAKE) all CFLAGS="@PROFILE@"
+

Modified: icecast/branches/kh/libshout/src/mp3.c
===================================================================
--- icecast/branches/kh/libshout/src/mp3.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/mp3.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,5 +1,4 @@
-/* -*- c-basic-offset: 8; -*- */
-/* mp3.c: libshout MP3 format handler
+/* mp3.c: libshout MP3 format handler
*
*  Copyright (C) 2002-2003 the Icecast team <team at icecast.org>
*
@@ -18,6 +17,10 @@
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -93,7 +96,7 @@
};

/* -- static prototypes -- */
-static int send_mp3(shout_t *self, const unsigned char *data, size_t len);
+static int send_mp3(shout_t *self, const void *data, unsigned len);
static void close_mp3(shout_t *self);

static void parse_header(mp3_header_t *mh, uint32_t header);
@@ -103,18 +106,22 @@
{
mp3_data_t *mp3_data;

-	if (!(mp3_data = (mp3_data_t *)calloc(1, sizeof(mp3_data_t))))
-		return SHOUTERR_MALLOC;
+    self->error = SHOUTERR_MALLOC;
+	if ((mp3_data = (mp3_data_t *)calloc(1, sizeof(mp3_data_t))) == NULL)
+		return -1;
self->format_data = mp3_data;

self->send = send_mp3;
self->close = close_mp3;
+    self->mime_type = "audio/mpeg";

-	return SHOUTERR_SUCCESS;
+    self->error = SHOUTERR_SUCCESS;
+	return 0;
}

-static int send_mp3(shout_t* self, const unsigned char* buff, size_t len)
+static int send_mp3(shout_t* self, const void *in_buff, unsigned len)
{
+    const unsigned char *buff = in_buff;
mp3_data_t* mp3_data = (mp3_data_t*) self->format_data;
unsigned long pos;
uint32_t head;
@@ -203,7 +210,7 @@
end = pos - 1;
count = end - start + 1;
if (count > 0)
-					ret = sock_write_bytes(self->socket, (char *)&buff[start], count);
+					ret = shout_send_raw (self, (char *)&buff[start], count);
else
ret = 0;

@@ -234,7 +241,7 @@
/* if there's no errors, lets send the frames */
count = end - start + 1;
if (count > 0)
-			ret = sock_write_bytes(self->socket, (char *)&buff[start], count);
+            ret = shout_send_raw (self, (char *)&buff[start], count);
else
ret = 0;


Added: icecast/branches/kh/libshout/src/ogg.c
===================================================================
--- icecast/branches/kh/libshout/src/ogg.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/ogg.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -0,0 +1,596 @@
+/* vorbis.c: Ogg Vorbis data handlers for libshout
+ *
+ * Copyright(c) 2003 Karl Heyes <karl at xiph.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; See the file COPYING;
+ * if not, write to the Free Software Foundation, Inc., 59 Temple
+ * Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+
+
+#ifdef HAVE_CONFIG_H
+ #include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <ogg/ogg.h>
+#include <vorbis/codec.h>
+#ifdef HAVE_THEORA
+#include <theora/theora.h>
+#endif
+
+#include <shout/shout.h>
+#include "shout_private.h"
+
+
+typedef struct _ogg_codec_tag
+{
+    char *name;
+    ogg_stream_state os;
+    unsigned headers;
+    uint64_t senttime;
+    void *specific;
+    struct _ogg_codec_tag *next;
+    int (*process_page)(shout_t *shout, struct _ogg_codec_tag *codec, ogg_page *page);
+    void (*codec_free)(struct _ogg_codec_tag *codec);
+} ogg_codec_t;
+
+
+typedef struct _ogg_info_tag
+{
+    ogg_sync_state oy;
+
+    ogg_codec_t *codecs;
+    int headers_completed;
+    int not_in_bos;
+} ogg_info_t;
+
+
+typedef struct _vorbis_codec_tag
+{
+    vorbis_info vi;
+    vorbis_comment vc;
+    int prevW;
+} vorbis_codec_t;
+
+
+
+/* -- static prototypes -- */
+static int send_oggpage (shout_t *self, const void *ptr,  unsigned len);
+static int send_ogg (shout_t *self, const void *ptr, unsigned len);
+static void close_ogg (shout_t *self);
+
+
+static void free_ogg_codecs (ogg_info_t *ogg_info)
+{
+    ogg_codec_t *codec;
+
+    if (ogg_info == NULL)
+       return;
+    // printf ("codec handlers are being cleared\n");
+    codec = ogg_info->codecs;
+    while (codec)
+    {
+        ogg_codec_t *next = codec->next;
+        codec->codec_free (codec);
+        codec = next;
+    }
+    ogg_info->codecs = NULL;
+    ogg_info->headers_completed = 0;
+}
+
+
+static void vorbis_codec_free (ogg_codec_t *codec)
+{
+    vorbis_codec_t *vorbis = codec->specific;
+
+    vorbis_info_clear (&vorbis->vi);
+    vorbis_comment_clear (&vorbis->vc);
+    ogg_stream_clear (&codec->os);
+    free (vorbis);
+    free (codec);
+}
+
+
+int shout_open_vorbis(shout_t *self)
+{
+    if (self->format == SHOUT_FORMAT_VORBISPAGE)
+        self->send = send_oggpage;
+    else
+    {
+        ogg_info_t *ogg_info;
+
+        self->error = SHOUTERR_MALLOC;
+        ogg_info = (ogg_info_t *)calloc (1, sizeof (ogg_info_t));
+        if (ogg_info == NULL)
+            return -1;
+        self->format_data = ogg_info;
+
+        ogg_sync_init (&ogg_info->oy);
+
+        self->send = send_ogg;
+    }
+	self->close = close_ogg;
+    self->mime_type = "application/ogg";
+
+    self->error = SHOUTERR_SUCCESS;
+	return 0;
+}
+
+
+static int blocksize (vorbis_codec_t *vd, ogg_packet *p)
+{
+    int this = vorbis_packet_blocksize(&vd->vi, p);
+    int ret = (this + vd->prevW)/4;
+
+    if(!vd->prevW) {
+        vd->prevW = this;
+        return 0;
+    }
+
+    vd->prevW = this;
+    return ret;
+}
+
+static int process_vorbis_page (shout_t *shout, ogg_codec_t *codec, ogg_page *page)
+{
+    ogg_packet packet;
+    vorbis_codec_t *vorbis = codec->specific;
+    int ret;
+
+    ogg_stream_pagein (&codec->os, page);
+    if (codec->headers < 3)
+    {
+
+        while (ogg_stream_packetout (&codec->os, &packet) > 0)
+        {
+           if (vorbis_synthesis_headerin (&vorbis->vi, &vorbis->vc, &packet) < 0)
+           {
+               /* set some error code */
+               return 0;
+           }
+           codec->headers++;
+        }
+    }
+    else
+    {
+        /* work out the number of samples in each page */
+        unsigned samples = 0;
+
+        while (ogg_stream_packetout (&codec->os, &packet) == 1)
+        {
+            unsigned size = blocksize (vorbis, &packet);
+            samples += size;
+        }
+        codec->senttime += (((uint64_t)samples * 1000000) / vorbis->vi.rate);
+        if (shout->senttime < codec->senttime)
+            shout->senttime = codec->senttime;
+#if 0
+        else
+            if (shout->senttime - codec->senttime > 300000)
+                printf ("vorbis lag of %lld\n", shout->senttime - codec->senttime);
+        printf ("vorbis sentime %lld\n", codec->senttime);
+#endif
+    }
+    ret = shout_send_raw (shout, page->header, page->header_len);
+    if (ret < page->header_len)
+        return -1;
+    ret = shout_send_raw (shout, page->body, page->body_len);
+    if (ret < page->body_len)
+        return -1;
+
+    return page->header_len + page->body_len;
+}
+
+
+static ogg_codec_t *initial_vorbis_page (shout_t *shout, ogg_page *page)
+{
+    ogg_codec_t *codec = calloc (1, sizeof (ogg_codec_t));
+    ogg_packet packet;
+
+    vorbis_codec_t *vorbis_codec = calloc (1, sizeof (vorbis_codec_t));
+
+    ogg_stream_init (&codec->os, ogg_page_serialno (page));
+    ogg_stream_pagein (&codec->os, page);
+
+    vorbis_info_init (&vorbis_codec->vi);
+    vorbis_comment_init (&vorbis_codec->vc);
+
+    ogg_stream_packetout (&codec->os, &packet);
+
+    codec->name = "Vorbis";
+    do
+    {
+        int ret;
+
+        if (vorbis_synthesis_headerin (&vorbis_codec->vi, &vorbis_codec->vc, &packet) < 0)
+        {
+            break;
+        }
+        codec->specific = vorbis_codec;
+        codec->process_page = process_vorbis_page;
+        codec->codec_free = vorbis_codec_free;
+        codec->headers = 1;
+        codec->senttime = shout->senttime;
+
+        ret = shout_send_raw (shout, page->header, page->header_len);
+        if (ret < 0)
+            break;
+        ret = shout_send_raw (shout, page->body, page->body_len);
+        if (ret < 0)
+            break;
+
+        return codec;
+    } while (0);
+
+    ogg_stream_clear (&codec->os);
+    vorbis_info_clear (&vorbis_codec->vi);
+    vorbis_comment_clear (&vorbis_codec->vc);
+    free (vorbis_codec);
+    free (codec);
+    return NULL;
+}
+
+#ifdef HAVE_THEORA
+typedef struct _theora_codec_tag
+{
+    theora_info ti;
+    theora_comment tc;
+    uint32_t granule_shift;
+    double prev_time;
+} theora_codec_t;
+
+
+static void theora_codec_free (ogg_codec_t *codec)
+{
+    theora_codec_t *theora = codec->specific;
+
+    theora_info_clear (&theora->ti);
+    theora_comment_clear (&theora->tc);
+    ogg_stream_clear (&codec->os);
+    free (theora);
+    free (codec);
+}
+
+
+static int _ilog (unsigned int v)
+{
+    int ret=0;
+    while(v){
+        ret++;
+        v>>=1;
+    }
+    return ret;
+}
+
+
+static int process_theora_page (shout_t *shout, ogg_codec_t *codec, ogg_page *page)
+{
+    theora_codec_t *theora = codec->specific;
+    ogg_packet packet;
+    int ret;
+
+    ogg_stream_pagein (&codec->os, page);
+    if (ogg_page_granulepos (page) == 0)
+    {
+        while (ogg_stream_packetout (&codec->os, &packet) > 0)
+        {
+           if (theora_decode_header (&theora->ti, &theora->tc, &packet) < 0)
+           {
+               /* set some error code */
+               // fprintf (stderr, "error from theora decode header\n");
+               return -1;
+           }
+           codec->headers++;
+        }
+        if (codec->headers == 3)
+        {
+            theora->prev_time = 0.0;
+            theora->granule_shift = _ilog (theora->ti.keyframe_frequency_force - 1);
+            // printf ("fps values %ld, %ld\n", theora->ti.fps_denominator , theora->ti.fps_numerator);
+        }
+    }
+    else
+    {
+        // double fps = theora->ti.fps_numerator / theora->ti.fps_denominator;
+        double per_frame = (double)theora->ti.fps_denominator / theora->ti.fps_numerator * 1000000;
+        double duration;
+#if 0
+        double from_start;
+        from_start = theora_granule_time (&theora->ti, ogg_page_granulepos (page));
+        duration = (from_start - theora->prev_time) * 1000000;
+#endif
+#if 0
+        int packets = ogg_page_packets(page);
+
+        duration = (packets / fps) * 1000000.0;
+        printf ("packets %d, fps is %.2f, duration %.3f\n", packets, fps, duration);
+        codec->senttime += (uint64_t)(duration + 0.5);
+#endif
+        ogg_int64_t granulepos = ogg_page_granulepos (page);
+        if (granulepos > 0)
+        {
+            ogg_int64_t iframe = granulepos >> theora->granule_shift;
+            ogg_int64_t pframe = granulepos - (iframe << theora->granule_shift);
+
+            uint64_t frames = iframe + pframe;
+            double new_time = (frames  * per_frame);
+            duration = new_time - theora->prev_time;
+            // printf ("frames %lld (%.2f), new %.2f, prev %.2f\n", frames, per_frame, new_time, theora->prev_time);
+            theora->prev_time = new_time;
+
+            codec->senttime += (uint64_t)(duration + 0.5);
+            if (shout->senttime < codec->senttime)
+                shout->senttime = codec->senttime;
+#if 0
+            else
+                if (shout->senttime - codec->senttime > 300000)
+                    printf ("theora lag of %lld\n", shout->senttime - codec->senttime);
+#endif
+        }
+        // printf ("theora sentime %lld\n", codec->senttime);
+    }
+    // printf ("page no is %ld\n", ogg_page_pageno (page));
+    ret = shout_send_raw (shout, page->header, page->header_len);
+    if (ret < page->header_len)
+        return -1;
+    ret = shout_send_raw (shout, page->body, page->body_len);
+    if (ret < page->body_len)
+        return -1;
+
+    return page->header_len + page->body_len;
+}
+
+
+static ogg_codec_t *initial_theora_page (shout_t *shout, ogg_page *page)
+{
+    ogg_codec_t *codec = calloc (1, sizeof (ogg_codec_t));
+    ogg_packet packet;
+
+    theora_codec_t *theora_codec = calloc (1, sizeof (theora_codec_t));
+
+    ogg_stream_init (&codec->os, ogg_page_serialno (page));
+    ogg_stream_pagein (&codec->os, page);
+
+    theora_info_init (&theora_codec->ti);
+    theora_comment_init (&theora_codec->tc);
+
+    ogg_stream_packetout (&codec->os, &packet);
+
+    do
+    {
+        int ret;
+
+        if (theora_decode_header (&theora_codec->ti, &theora_codec->tc, &packet) < 0)
+        {
+            break;
+        }
+        codec->specific = theora_codec;
+        codec->process_page = process_theora_page;
+        codec->codec_free = theora_codec_free;
+        codec->headers = 1;
+        codec->senttime = shout->senttime;
+
+        ret = shout_send_raw (shout, page->header, page->header_len);
+        if (ret < page->header_len)
+            break;
+        ret = shout_send_raw (shout, page->body, page->body_len);
+        if (ret < page->body_len)
+            break;
+
+        codec->name = "Theora";
+
+        return codec;
+    } while (0);
+
+    ogg_stream_clear (&codec->os);
+    theora_info_clear (&theora_codec->ti);
+    theora_comment_clear (&theora_codec->tc);
+    free (theora_codec);
+    free (codec);
+    return NULL;
+}
+#endif
+
+/* catch all for unknown codecs */
+
+static void unhandled_codec_free (ogg_codec_t *codec)
+{
+    ogg_stream_clear (&codec->os);
+    free (codec);
+}
+
+
+static int process_unhandled_page (shout_t *shout, ogg_codec_t *codec, ogg_page *page)
+{
+    int ret;
+
+    ret = shout_send_raw (shout, page->header, page->header_len);
+    if (ret < 0)
+        return SHOUTERR_SOCKET;
+    ret = shout_send_raw (shout, page->body, page->body_len);
+
+    return ret;
+}
+
+
+static ogg_codec_t *initial_unhandled_page (shout_t *shout, ogg_page *page)
+{
+    ogg_codec_t *codec = calloc (1, sizeof (ogg_codec_t));
+    codec->process_page = process_unhandled_page;
+    codec->codec_free = unhandled_codec_free;
+    codec->name = "not timed";
+    ogg_stream_init (&codec->os, ogg_page_serialno (page));
+
+    do
+    {
+        int ret = shout_send_raw (shout, page->header, page->header_len);
+        if (ret < 0)
+            break;
+        ret = shout_send_raw (shout, page->body, page->body_len);
+        if (ret < 0)
+            break;
+        return codec;
+    } while (0);
+
+    ogg_stream_clear (&codec->os);
+    free (codec);
+    return NULL;
+}
+
+
+static int process_initial_page (shout_t *shout, ogg_page *page)
+{
+	ogg_info_t *ogg_info = (ogg_info_t *)shout->format_data;
+    ogg_codec_t *codec;
+    int ret = SHOUTERR_SUCCESS;
+
+    if (ogg_info->not_in_bos)
+    {
+        free_ogg_codecs (ogg_info);
+    }
+    ogg_info->not_in_bos = 0;
+    do
+    {
+        codec = initial_vorbis_page (shout, page);
+        if (codec)
+            break;
+#ifdef HAVE_THEORA
+        codec = initial_theora_page (shout, page);
+        if (codec)
+            break;
+#endif
+        /* any others */
+        codec = initial_unhandled_page (shout, page);
+        if (codec)
+            break;
+        shout->error = SHOUTERR_INSANE;
+        ret = -1;
+
+    } while (0);
+
+    if (codec)
+    {
+        /* add codec to list */
+        /* printf ("Adding codec handler (%s) to list\n", codec->name); */
+        codec->next = ogg_info->codecs;
+        ogg_info->codecs = codec;
+    }
+    return ret;
+}
+
+
+static int send_ogg (shout_t *self, const void *ptr, unsigned len)
+{
+	ogg_info_t *ogg_info = (ogg_info_t *)self->format_data;
+	ogg_page page;
+    void *buffer;
+
+    /* lets chop up the data into pages */
+	buffer = ogg_sync_buffer (&ogg_info->oy, len);
+	memcpy (buffer, ptr, len);
+	ogg_sync_wrote (&ogg_info->oy, len);
+
+	while (ogg_sync_pageout (&ogg_info->oy, &page) == 1)
+    {
+        ogg_codec_t *codec;
+
+        if (ogg_page_bos (&page))
+        {
+            /* printf ("serial of bos page is %d\n", ogg_page_serialno (&page)); */
+            process_initial_page (self, &page);
+            return self->error;
+        }
+        ogg_info->not_in_bos = 1;
+
+        codec = ogg_info->codecs;
+        while (codec)
+        {
+            if (ogg_page_serialno (&page) == codec->os.serialno)
+            {
+                // printf ("page handler is %s, %lld", codec->name, codec->senttime);
+                codec->process_page (self, codec, &page);
+                // printf ("\n");
+                return self->error;
+            }
+
+            codec = codec->next;
+        }
+    }
+    return 0;
+}
+
+
+static void close_ogg(shout_t *self)
+{
+   free_ogg_codecs (self->format_data);
+}
+
+
+static int send_oggpage (shout_t *self, const void *ptr, unsigned unused)
+{
+    const ogg_page *page = ptr;
+    unsigned len = page->header_len + page->body_len;
+
+    if (self->pending_queue == NULL)
+    {
+        struct iovec vecs [2];
+        int ret;
+
+        vecs[0] . iov_base = page->header;
+        vecs[0] . iov_len  = page->header_len;
+        vecs[1] . iov_base = page->body;
+        vecs[1] . iov_len  = page->body_len;
+
+        ret = sock_writev (self->socket, vecs, 2);
+        if (ret == (int)len)
+            return self->error = SHOUTERR_SUCCESS;
+        if (ret < 0)
+        {
+            if (sock_recoverable (sock_error()))
+                ret = 0;
+            else
+            {
+                self->state = SHOUT_NOCONNECT;
+                return self->error = SHOUTERR_SOCKET;
+            }
+        }
+        if (ret < page->header_len)
+        {
+            if (shout_queue_raw (self, page->header+ret, page->header_len-ret) < 0)
+                return self->error;
+            ret = 0;
+        }
+        else
+            ret -= page->header_len;
+        if (shout_queue_raw (self, page->body+ret, page->body_len-ret) < 0)
+            return self->error;
+
+        return self->error = SHOUTERR_SUCCESS;
+    }
+    if (shout_queue_raw (self, page->header, page->header_len) < 0)
+        return self->error;
+    if (shout_queue_raw (self, page->body, page->body_len) < 0)
+        return self->error;
+
+    if (shout_send_pending (self) < 0)
+        return self->error;
+
+    return self->error = SHOUTERR_SUCCESS;
+}
+

Modified: icecast/branches/kh/libshout/src/shout.c
===================================================================
--- icecast/branches/kh/libshout/src/shout.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/shout.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,406 +1,669 @@
-/* -*- c-basic-offset: 8; -*- */
-/* shout.c: Implementation of public libshout interface shout.h
+/* shout.c  Implementation of public libshout interface shout.h
+ *
+ * Copyright(c) 2003-4 Karl Heyes <karl at xiph.org>
*
- *  Copyright (C) 2002-2003 the Icecast team <team at icecast.org>
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
*
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Library General Public
- *  License as published by the Free Software Foundation; either
- *  version 2 of the License, or (at your option) any later version.
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
*
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Library General Public License for more details.
- *
- *  You should have received a copy of the GNU Library General Public
- *  License along with this library; if not, write to the Free
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; see the file COPYING; if not,
+ * write to the Free Software Foundation, Inc., 59 Temple Place,
+ * Suite 330, Boston, MA  02111-1307  USA
*/

#ifdef HAVE_CONFIG_H
- #include <config.h>
+ #include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <errno.h>

#include <shout/shout.h>
#include <net/sock.h>
-#include "timing/timing.h"
-#include "httpp/httpp.h"
+#include <timing/timing.h>
+#include <httpp/httpp.h>
+#include <thread/thread.h>

#include "shout_private.h"
#include "util.h"

/* -- local prototypes -- */
-static int login_xaudiocast(shout_t *self);
-static int login_icy(shout_t *self);
-static int login_http_basic(shout_t *self);
static char *http_basic_authorization(shout_t *self);

/* -- static data -- */
static int _initialized = 0;

-/* -- public functions -- */

-void shout_init(void)
+static void shout_free_pending (shout_t *self)
{
-	if (_initialized)
-		return;
+    struct shout_pending_node *node = self->pending_queue, *next;

-	sock_initialize();
-	_initialized = 1;
+    while (node)
+    {
+        next = node->next;
+
+        if (node->data)
+            free (node->data);
+        free (node);
+
+        node = next;
+    }
+    self->pending_total = 0;
+    self->pending_queue = NULL;
+    self->pending_queue_tail = &self->pending_queue;
}

-void shout_shutdown(void)
+
+static int shout_try_write (shout_t *self, const void *data, unsigned len)
{
-	if (!_initialized)
-		return;
+    int ret = sock_write_bytes (self->socket, data, len);

-	sock_shutdown();
-	_initialized = 0;
+    if (ret < 0)
+    {
+        if (sock_recoverable (sock_error()))
+        {
+            self->error = SHOUTERR_BUSY;
+            return 0;
+        }
+        self->error = SHOUTERR_SOCKET;
+    }
+    return ret;
}

-shout_t *shout_new(void)
+
+/* -- static function definitions -- */
+static char *http_basic_authorization(shout_t *self)
{
-	shout_t *self;
+    char *out, *in;
+    int len;

-	/* in case users haven't done this explicitly. Should we error
-	 * if not initialized instead? */
-	shout_init();
-
-	if (!(self = (shout_t *)calloc(1, sizeof(shout_t)))) {
-		return NULL;
-	}
+    if (!self || !self->user || !self->password)
+        return NULL;

-	if (shout_set_host(self, LIBSHOUT_DEFAULT_HOST) != SHOUTERR_SUCCESS) {
-		shout_free(self);
+    len = strlen(self->user) + strlen(self->password) + 2;
+    if (!(in = malloc(len)))
+        return NULL;
+    sprintf(in, "%s:%s", self->user, self->password);
+    out = util_base64_encode(in);
+    free(in);

-		return NULL;
-	}
-	if (shout_set_user(self, LIBSHOUT_DEFAULT_USER) != SHOUTERR_SUCCESS) {
-		shout_free(self);
+    len = strlen(out) + 24;
+    if (!(in = malloc(len))) {
+        free(out);
+        return NULL;
+    }
+    sprintf(in, "Authorization: Basic %s\r\n", out);
+    free(out);

-		return NULL;
-	}
-	if (shout_set_agent(self, LIBSHOUT_DEFAULT_USERAGENT) != SHOUTERR_SUCCESS) {
-		shout_free(self);
+    return in;
+}

-		return NULL;
-	}
-	if (!(self->audio_info = _shout_util_dict_new())) {
-		shout_free(self);

-		return NULL;
-	}
+static int shout_connect (shout_t *self)
+{
+    if (self->pending_connection)
+    {
+        int ret;

-	self->port = LIBSHOUT_DEFAULT_PORT;
-	self->format = LIBSHOUT_DEFAULT_FORMAT;
-	self->protocol = LIBSHOUT_DEFAULT_PROTOCOL;
+        self->error = SHOUTERR_PENDING;
+        switch (sock_connected (self->socket, 0))
+        {
+            case 1:
+                self->error = SHOUTERR_SUCCESS;
+                self->state = SHOUT_CONNECTED;
+                self->pending_connection = 0;
+                return 0;
+            case SOCK_ERROR:
+                self->error = SHOUTERR_NOCONNECT;
+                self->pending_connection = 0;
+                /* fall thru */
+            case SOCK_TIMEOUT:
+            default:
+                return -1;
+        }
+    }

-	return self;
+    if (self->nonblocking)
+    {
+        self->error = SHOUTERR_PENDING;
+        self->socket = sock_connect_non_blocking (self->host, self->port);
+        if (self->socket < 0)
+            self->error = SHOUTERR_NOCONNECT;
+        else
+            self->pending_connection = 1;
+        return -1;
+    }
+    else
+    {
+        self->error = SHOUTERR_NOCONNECT;
+        self->socket = sock_connect(self->host, self->port);
+        if (self->socket < 0)
+            return -1;
+        self->error = SHOUTERR_SUCCESS;
+        self->state = SHOUT_CONNECTED;
+        return 0;
+    }
}

-void shout_free(shout_t *self)
+
+int shout_send_pending (shout_t *self)
{
-	if (!self) return;
+    if (self->pending_queue == NULL)
+        return 0;
+    else
+    {
+        struct shout_pending_node *node = self->pending_queue;
+        int written;

-	if (self->host) free(self->host);
-	if (self->password) free(self->password);
-	if (self->mount) free(self->mount);
-	if (self->name) free(self->name);
-	if (self->url) free(self->url);
-	if (self->genre) free(self->genre);
-	if (self->description) free(self->description);
-	if (self->user) free(self->user);
-	if (self->useragent) free(self->useragent);
-	if (self->audio_info) _shout_util_dict_free (self->audio_info);
+        while (node)
+        {
+            written = shout_try_write (self, node->start, node->len);
+            if (written == (int)node->len)
+            {
+                self->pending_queue = node->next;
+                if (self->pending_queue == NULL)
+                    self->pending_queue_tail = &self->pending_queue;
+                free (node->data);
+                free (node);
+                node = self->pending_queue;
+                self->pending_total -= written;
+            }
+            else
+            {
+                if (written < 0)
+                    return -1;

-	free(self);
+                node->start = (char*)node->start+written;
+                node->len -= written;
+                self->pending_total -= written;
+                self->error = SHOUTERR_SUCCESS;
+                break;
+            }
+        }
+    }
+    self->error = SHOUTERR_SUCCESS;
+
+    return 0;
}

-int shout_open(shout_t *self)
+
+static int create_http_request (shout_t *self)
{
-	/* sanity check */
-	if (!self)
-		return SHOUTERR_INSANE;
+    int ret = -1;
+    char *auth = NULL, *data = NULL;
+    self->error = SHOUTERR_MALLOC;

-	if (self->connected)
-		return SHOUTERR_CONNECTED;
+    while (1)
+    {
+        if (add_send_header (self, "SOURCE %s HTTP/1.0\r\n", self->mount))
+            break;

-	if (!self->host || !self->password || !self->port)
-		return self->error = SHOUTERR_INSANE;
+        if (add_send_header (self, "ice-name: %s\r\n", self->name != NULL ? self->name : "no name"))
+            break;
+        if (self->url)
+            if (add_send_header (self, "ice-url: %s\r\n", self->url))
+                break;
+        if (self->genre)
+            if (add_send_header (self, "ice-genre: %s\r\n", self->genre))
+                break;
+        if ((data = util_dict_urlencode(self->audio_info, ';')))
+            if (add_send_header (self, "ice-audio-info: %s\r\n", data))
+                break;
+        if (add_send_header (self, "ice-public: %d\r\n", self->public))
+            break;
+        if (self->description)
+            if (add_send_header (self, "ice-description: %s\r\n", self->description))
+                break;
+        if (self->useragent)
+            if (add_send_header (self, "User-Agent: %s\r\n", self->useragent))
+                break;
+        if (add_send_header (self, "Content-Type: %s\r\n", self->mime_type))
+            break;
+        auth = http_basic_authorization (self);
+        if (auth == NULL)
+        {
+            self->error = SHOUTERR_INSANE;
+            break; /* need username and password */
+        }
+        else
+        {
+            if (add_send_header (self, "%s", auth))
+                break;
+        }
+        if (add_send_header (self, "\r\n"))
+            break;
+        ret = 0;
+        self->error = SHOUTERR_SUCCESS;
+        break;
+    }
+    if (data)  free (data);

-	if (self->format == SHOUT_FORMAT_VORBIS && self->protocol != SHOUT_PROTOCOL_HTTP)
-		return self->error = SHOUTERR_UNSUPPORTED;
+    return ret;
+}

-	if(self->protocol != SHOUT_PROTOCOL_HTTP) {
-		if (self->protocol == SHOUT_PROTOCOL_ICY)
-			self->socket = sock_connect(self->host, self->port+1);
-		else
-			self->socket = sock_connect(self->host, self->port);
-		if (self->socket <= 0)
-			return self->error = SHOUTERR_NOCONNECT;
-	}

-	if (self->protocol == SHOUT_PROTOCOL_HTTP) {
-		if ((self->error = login_http_basic(self)) != SHOUTERR_SUCCESS) {
-			return self->error;
-		}
-	} else if (self->protocol == SHOUT_PROTOCOL_XAUDIOCAST) {
-		if ((self->error = login_xaudiocast(self)) != SHOUTERR_SUCCESS) {
-			sock_close(self->socket);
-			return self->error;
-		}
-	} else if (self->protocol == SHOUT_PROTOCOL_ICY) {
-		if ((self->error = login_icy(self)) != SHOUTERR_SUCCESS) {
-			sock_close(self->socket);
-			return self->error;
-		}
-
-	} else
-		return self->error = SHOUTERR_INSANE;
-
-	if (self->format == SHOUT_FORMAT_VORBIS) {
-		if ((self->error = shout_open_vorbis(self)) != SHOUTERR_SUCCESS) {
-			sock_close(self->socket);
-			return self->error;
-		}
-	} else if (self->format == SHOUT_FORMAT_MP3) {
-		if ((self->error = shout_open_mp3(self)) != SHOUTERR_SUCCESS) {
-			sock_close(self->socket);
-			return self->error;
-		}
-	} else {
-		sock_close(self->socket);
-		return self->error = SHOUTERR_INSANE;
-	}
+static int send_request(shout_t *self)
+{
+    switch (self->state)
+    {
+        case SHOUT_REQ_SENT:
+            self->error = SHOUTERR_CONNECTED;
+            return 0;

-	self->connected = 1;
+        case SHOUT_CONNECTED:
+            if (self->create_request)
+            {
+                if (self->create_request (self) < 0)
+                    return -1;
+                self->state = SHOUT_REQ_MADE;
+                /* ok, we've made the header */
+            }
+            else
+                break;

-	return self->error;
+        case SHOUT_REQ_MADE:
+            if (shout_send_raw (self, self->send_header + self->send_header_offset,
+                    self->send_header_size - self->send_header_offset) < 0)
+                 return -1;
+            break;
+        default:
+            self->error = SHOUTERR_INSANE;
+            return -1;
+    }
+    self->state = SHOUT_REQ_SENT;
+    self->response_senttime = time(NULL);
+    return 0;
}


-int shout_close(shout_t *self)
+
+static int shout_read_response (shout_t *self)
{
-	if (!self)
-		return SHOUTERR_INSANE;
+    char *ptr;

-	if (!self->connected)
-		return self->error = SHOUTERR_UNCONNECTED;
+    shout_send_pending (self);
+    if (self->state == SHOUT_REQ_SENT)
+    {
+        self->error = SHOUTERR_SOCKET;
+        while (1)
+        {
+            int bytes;
+            char  *start;

-	if (self->close)
-		self->close(self);
+            if (self->nonblocking == 0)
+            {
+                switch (sock_read_pending (self->socket, self->read_timeout*1000))
+                {
+                    case SOCK_ERROR:
+                        self->error = SHOUTERR_SOCKET;
+                        return -1;
+                    case SOCK_TIMEOUT:
+                        self->error = SHOUTERR_NOCONNECT;
+                        return -1;
+                    default:
+                        break;
+                }
+            }
+            else
+            {
+                time_t now = time (NULL);
+                if ((time_t)(self->response_senttime + self->read_timeout) < now)
+                {
+                    self->error = SHOUTERR_NOCONNECT;
+                    return -1;
+                }
+                self->error = SHOUTERR_PENDING;
+                switch (sock_read_pending (self->socket, 0))
+                {
+                    case SOCK_ERROR:
+                        self->error = SHOUTERR_SOCKET;
+                    case SOCK_TIMEOUT:
+                    case 0:
+                        return -1;
+                    default:
+                        break;
+                }
+            }
+            bytes = sock_read_bytes (self->socket, self->response + self->response_len,
+                    MAX_HTTP_RESPONSE - self->response_len - 1);
+            if (bytes == 0)
+            {
+                self->error = SHOUTERR_SOCKET;
+                return -1;
+            }
+            if (bytes < 0)
+            {
+                if (sock_stalled (sock_error()))
+                    self->error = SHOUTERR_PENDING;
+                return -1;
+            }

-	sock_close(self->socket);
-	self->connected = 0;
+            /* lets get rid of any '\r' in '\r\n' sequences */
+            start = ptr = (char *)(self->response + self->response_len);
+            ptr [bytes] = '\0';
+            while (1)
+            {
+                char * tmp_ptr;
+                tmp_ptr = strstr (ptr, "\r\n");
+                if (tmp_ptr)
+                {
+                    memmove (tmp_ptr, tmp_ptr+1, bytes-(tmp_ptr-ptr));
+                    bytes--;  /* removed \r */
+                    ptr = tmp_ptr+1;
+                }
+                else
+                    break;
+            }
+            self->response_len += bytes;

-	return self->error = SHOUTERR_SUCCESS;
+            if (strstr (start, "\n\n"))
+                break;
+        }
+
+        self->error = SHOUTERR_SUCCESS;
+        return self->response_len;
+    }
+    self->error = SHOUTERR_INSANE;
+    return -1;
}

-int shout_send(shout_t *self, const unsigned char *data, size_t len)
+
+static int shout_login (shout_t *self)
{
-	if (!self)
-		return SHOUTERR_INSANE;
+    if (self->state == SHOUT_NOCONNECT && shout_connect (self) < 0)
+        return -1;

-	if (!self->connected)
-		return self->error = SHOUTERR_UNCONNECTED;
+    if (send_request (self) < 0)
+        return -1;

-	if (self->starttime <= 0)
-		self->starttime = timing_get_time();
+    if (self->get_response (self) < 0)
+        return -1;
+    self->state = SHOUT_READY;
+    return 0;
+}

-	return self->send(self, data, len);
+
+static int login_http(shout_t *self)
+{
+    http_parser_t *parser;
+    int code;
+    char *retcode;
+
+    if (shout_read_response (self) < 0)
+        return -1;
+
+    self->error = SHOUTERR_NOLOGIN;
+    parser = httpp_create_parser();
+    httpp_initialize (parser, NULL);
+    if (httpp_parse_response (parser, (char*)self->response, self->response_len, self->mount))
+    {
+        retcode = httpp_getvar (parser, HTTPP_VAR_ERROR_CODE);
+        code = atoi(retcode);
+        if (code >= 200 && code < 300)
+        {
+            httpp_destroy (parser);
+            self->error = SHOUTERR_SUCCESS;
+            return 0;
+        }
+    }
+
+    httpp_destroy (parser);
+    return -1;
}

-ssize_t shout_send_raw(shout_t *self, const unsigned char *data, size_t len)
+
+static int create_xaudiocast_request (shout_t *self)
{
-	ssize_t ret;
-	size_t remaining = len;
+    int ret = -1;

-	if (!self)
-		return SHOUTERR_INSANE;
+    while (1)
+    {
+        self->error = SHOUTERR_SOCKET;
+        if (add_send_header (self, "SOURCE %s %s\r\n", self->password, self->mount))
+            break;

-	if (!self->connected)
-		return SHOUTERR_UNCONNECTED;
+        if (add_send_header (self, "x-audiocast-name: %s\n", self->name != NULL ? self->name : "unnamed"))
+            break;
+        if (add_send_header (self, "x-audiocast-url: %s\n", self->url != NULL ? self->url : "http://www.icecast.org/"))
+            break;
+        if (add_send_header (self, "x-audiocast-genre: %s\n", self->genre != NULL ? self->genre : "icecast"))
+            break;
+        if (add_send_header (self, "x-audiocast-bitrate: %i\n", self->bitrate))
+            break;
+        if (add_send_header (self, "x-audiocast-public: %i\n", self->public))
+            break;
+        if (add_send_header (self, "x-audiocast-description: %s\n", self->description != NULL ? self->description : "Broadcasting with the icecast streaming media server!"))
+            break;

-	self->error = SHOUTERR_SUCCESS;
+        if (add_send_header (self, "\n"))
+            break;

-	while(remaining) {
-		ret = sock_write_bytes(self->socket, data, remaining);
-		if(ret == (ssize_t)remaining)
-			return len;
-		else if(ret < 0) {
-			if(errno == EINTR)
-				ret = 0;
-			else
-				return self->error = SHOUTERR_SOCKET;
-		}
-		remaining -= ret;
-	}
+        self->error = SHOUTERR_SUCCESS;
+        ret = 0;
+        break;
+    }

-	return len;
+	return ret;
}

-void shout_sync(shout_t *self)
+
+static int login_ok(shout_t *self)
{
-	int64_t sleep;
+    if (shout_read_response (self) < 0)
+        return -1;
+    self->error = SHOUTERR_NOLOGIN;
+    if (!strstr(self->response, "OK"))
+        return -1;
+    self->error = SHOUTERR_SUCCESS;
+    return 0;
+}

-	if (!self)
-		return;

-	if (self->senttime == 0)
-		return;
+static int create_icy_request (shout_t *self)
+{
+    int ret = -1;

-	sleep = self->senttime / 1000 - (timing_get_time() - self->starttime);
-	if (sleep > 0)
-		timing_sleep((uint64_t)sleep);
-
+    while (1)
+    {
+        self->error = SHOUTERR_SOCKET;
+        /* no decent return code check */
+        if (add_send_header (self, "%s\n", self->password))
+            break;
+        if (add_send_header (self, "icy-name:%s\n", self->name != NULL ? self->name : "unnamed"))
+            break;
+        if (add_send_header (self, "icy-url:%s\n", self->url != NULL ? self->url : "http://www.icecast.org/"))
+            break;
+        /* Fields we don't use */
+        if (add_send_header (self, "icy-irc:\nicy-aim:\nicy-icq:\n"))
+            break;
+        if (add_send_header (self, "icy-pub:%i\n", self->public))
+            break;
+        if (add_send_header (self, "icy-genre:%s\n", self->genre != NULL ? self->genre : "icecast"))
+            break;
+        if (add_send_header (self, "icy-br:%i\n", self->bitrate))
+            break;
+        if (add_send_header (self, "\n"))
+            break;
+
+        ret = 0;
+        self->error = SHOUTERR_SUCCESS;
+        break;
+    }
+
+	return ret;
}

-int shout_delay(shout_t *self)
-{

-	if (!self)
-		return 0;
+/* -- public functions -- */

-	if (self->senttime == 0)
-		return 0;
-
-	/* Is this cast to double needed? */
-	return self->senttime / 1000 - (timing_get_time() - self->starttime);
-}
-
-shout_metadata_t *shout_metadata_new(void)
+void shout_init(void)
{
-	return _shout_util_dict_new();
+    if (_initialized)
+        return;
+
+    sock_initialize();
+    _initialized = 1;
}

-void shout_metadata_free(shout_metadata_t *self)
+void shout_shutdown(void)
{
-	if (!self)
-		return;
+    if (!_initialized)
+        return;

-	_shout_util_dict_free(self);
+    sock_shutdown();
+    _initialized = 0;
}
+

-int shout_metadata_add(shout_metadata_t *self, const char *name, const char *value)
+int shout_queue_raw (shout_t *self, const void *data, size_t len)
{
-	if (!self || !name)
-		return SHOUTERR_INSANE;
+    struct shout_pending_node *node = NULL;

-	return _shout_util_dict_set(self, name, value);
+    self->error = SHOUTERR_SOCKET;
+    do
+    {
+        void *ptr;
+
+        if (self->pending_total + len > self->pending_limit)
+            break;
+        node = calloc (1, sizeof (*node));
+        self->error = SHOUTERR_MALLOC;
+        if (node == NULL)
+            break;
+        ptr = malloc (len);
+        if (ptr == NULL)
+            break;
+        node->data = node->start = ptr;
+        memcpy (ptr, data, len);
+        node->len = len;
+        *self->pending_queue_tail = node;
+        self->pending_queue_tail = &node->next;
+        self->pending_total += len;
+        self->error = SHOUTERR_SUCCESS;
+        return 0;
+    } while (0);
+    if (node)
+        free (node);
+    return -1;
}

-/* open second socket to server, send HTTP request to change metadata.
- * TODO: prettier error-handling. */
-int shout_set_metadata(shout_t *self, shout_metadata_t *metadata)
+
+
+int shout_open(shout_t *self)
{
-	sock_t socket;
-	int rv;
-	char *encvalue;
-
-	if (!self || !metadata)
+	/* sanity check */
+	if (!self)
return SHOUTERR_INSANE;

-	if (!(encvalue = _shout_util_dict_urlencode(metadata, '&')))
-		return SHOUTERR_MALLOC;
+    do
+    {
+		self->error = SHOUTERR_INSANE;
+        if (!self->host || !self->password || !self->port)
+            break;

-	if ((socket = sock_connect(self->host, self->port)) <= 0)
-		return SHOUTERR_NOCONNECT;
+        self->error = SHOUTERR_CONNECTED;
+        if (self->state == SHOUT_CONNECTED)
+            break;

-	if (self->protocol == SHOUT_PROTOCOL_ICY)
-		rv = sock_write(socket, "GET /admin.cgi?mode=updinfo&pass=%s&%s HTTP/1.0\r\nUser-Agent: %s (Mozilla compatible)\r\n\r\n",
-		  self->password, encvalue, shout_get_agent(self));
-	else if (self->protocol == SHOUT_PROTOCOL_HTTP) {
-		char *auth = http_basic_authorization(self);
+        if (self->state == SHOUT_NOCONNECT && self->format_open (self) < 0)
+            break;

-		rv = sock_write(socket, "GET /admin/metadata?mode=updinfo&mount=%s&%s HTTP/1.0\r\nUser-Agent: %s\r\n%s\r\n",
-		  self->mount, encvalue, shout_get_agent(self), auth ? auth : "");
-	} else
-		rv = sock_write(socket, "GET /admin.cgi?mode=updinfo&pass=%s&mount=%s&%s HTTP/1.0\r\nUser-Agent: %s\r\n\r\n",
-		  self->password, self->mount, encvalue, shout_get_agent(self));
-	free(encvalue);
-	if (!rv) {
-		sock_close(socket);
-		return SHOUTERR_SOCKET;
-	}
+        if (shout_login (self) < 0)
+            break;

-	sock_close(socket);
+        self->starttime = timing_get_time();
+
+        self->error = SHOUTERR_SUCCESS;
+    } while (0);

-	return SHOUTERR_SUCCESS;
+	return self->error;
}

-/* getters/setters */
+
const char *shout_version(int *major, int *minor, int *patch)
{
-	if (major)
-		*major = LIBSHOUT_MAJOR;
-	if (minor)
-		*minor = LIBSHOUT_MINOR;
-	if (patch)
-		*patch = LIBSHOUT_MICRO;
-
-	return VERSION;
+    if (major)
+        *major = LIBSHOUT_MAJOR;
+    if (minor)
+        *minor = LIBSHOUT_MINOR;
+    if (patch)
+        *patch = LIBSHOUT_MICRO;
+    return VERSION;
}

int shout_get_errno(shout_t *self)
{
-	return self->error;
+    return self->error;
}

+
const char *shout_get_error(shout_t *self)
{
if (!self)
return "Invalid shout_t";

-	switch (self->error) {
-	case SHOUTERR_SUCCESS:
-		return "No error";
-	case SHOUTERR_INSANE:
-		return "Nonsensical arguments";
-	case SHOUTERR_NOCONNECT:
-		return "Couldn't connect";
-	case SHOUTERR_NOLOGIN:
-		return "Login failed";
-	case SHOUTERR_SOCKET:
-		return "Socket error";
-	case SHOUTERR_MALLOC:
-		return "Out of memory";
-	case SHOUTERR_CONNECTED:
-		return "Cannot set parameter while connected";
-	case SHOUTERR_UNCONNECTED:
-		return "Not connected";
-	case SHOUTERR_UNSUPPORTED:
-		return "This libshout doesn't support the requested option";
-	default:
-		return "Unknown error";
+	switch (self->error)
+    {
+        case SHOUTERR_SUCCESS:
+            return "No error";
+        case SHOUTERR_INSANE:
+            return "Nonsensical arguments";
+        case SHOUTERR_NOCONNECT:
+            return "Couldn't connect";
+        case SHOUTERR_NOLOGIN:
+            return "Login failed";
+        case SHOUTERR_SOCKET:
+            return "Socket error";
+        case SHOUTERR_MALLOC:
+            return "Out of memory";
+        case SHOUTERR_CONNECTED:
+            return "Still connected";
+        case SHOUTERR_UNCONNECTED:
+            return "Not connected";
+        case SHOUTERR_UNSUPPORTED:
+            return "This libshout doesn't support the requested option";
+        case SHOUTERR_PENDING:
+            return "Operation pending completion";
+        case SHOUTERR_PENDING_FULL:
+            return "Too much data waiting to be sent";
+        case SHOUTERR_BUSY:
+            return "Cannot perform task at the moment";
+        default:
+            return "Unknown error";
}
}

+
int shout_get_connected(shout_t *self)
{
-	if (self->connected)
-		return SHOUTERR_CONNECTED;
-	else
-		return SHOUTERR_UNCONNECTED;
+    if (self->state != SHOUT_NOCONNECT)
+        return SHOUTERR_CONNECTED;
+    else
+        return SHOUTERR_UNCONNECTED;
}

+
int shout_set_host(shout_t *self, const char *host)
{
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->host)
free(self->host);

-	if (!(self->host = _shout_util_strdup(host)))
+	self->host = util_strdup(host);
+	if (self->host == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -419,7 +682,7 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

self->port = port;
@@ -440,13 +703,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->password)
free (self->password);

-	if (!(self->password = _shout_util_strdup(password)))
+	self->password = util_strdup (password);
+	if (self->password == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -462,25 +726,26 @@

int shout_set_mount(shout_t *self, const char *mount)
{
-	size_t len;
+    size_t len;

if (!self || !mount)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;
-
+
if (self->mount)
free(self->mount);

-	len = strlen (mount) + 1;
-	if (mount[0] != '/')
-		len++;
+    len = strlen (mount) + 1;
+    if (mount[0] != '/')
+        len++;

-	if (!(self->mount = malloc(len)))
-		return self->error = SHOUTERR_MALLOC;
+    self->mount = malloc (len);
+    if (self->mount == NULL)
+        return self->error = SHOUTERR_MALLOC;

-	sprintf (self->mount, "%s%s", mount[0] == '/' ? "" : "/", mount);
+    sprintf (self->mount, "%s%s", mount[0] == '/' ? "" : "/", mount);

return self->error = SHOUTERR_SUCCESS;
}
@@ -498,13 +763,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->name)
free(self->name);

-	if (!(self->name = _shout_util_strdup(name)))
+	self->name = util_strdup (name);
+	if (self->name == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -523,13 +789,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->url)
free(self->url);

-	if (!(self->url = _shout_util_strdup(url)))
+	self->url = util_strdup(url);
+	if (self->url == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -548,13 +815,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->genre)
free(self->genre);

-	if (! (self->genre = _shout_util_strdup (genre)))
+	self->genre = util_strdup (genre);
+	if (self->genre == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -573,13 +841,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->useragent)
free(self->useragent);

-	if (! (self->useragent = _shout_util_strdup (agent)))
+	self->useragent = util_strdup (agent);
+	if (self->useragent == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -587,10 +856,10 @@

const char *shout_get_agent(shout_t *self)
{
-	if (!self)
-		return NULL;
+    if (!self)
+        return NULL;

-	return self->useragent;
+    return self->useragent;
}


@@ -599,13 +868,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->user)
free(self->user);

-	if (! (self->user = _shout_util_strdup (username)))
+	self->user = util_strdup (username);
+	if (self->user == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -613,10 +883,10 @@

const char *shout_get_user(shout_t *self)
{
-	if (!self)
-		return NULL;
+    if (!self)
+        return NULL;

-	return self->user;
+    return self->user;
}

int shout_set_description(shout_t *self, const char *description)
@@ -624,13 +894,14 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

if (self->description)
free(self->description);

-	if (! (self->description = _shout_util_strdup (description)))
+	self->description = util_strdup (description);
+	if (self->description == NULL)
return self->error = SHOUTERR_MALLOC;

return self->error = SHOUTERR_SUCCESS;
@@ -646,45 +917,50 @@

int shout_set_dumpfile(shout_t *self, const char *dumpfile)
{
-	if (!self)
-		return SHOUTERR_INSANE;
+    if (!self)
+        return SHOUTERR_INSANE;

-	if (self->connected)
-		return SHOUTERR_CONNECTED;
+    if (self->state != SHOUT_NOCONNECT)
+        return SHOUTERR_CONNECTED;

-	if (self->dumpfile)
-		free(self->dumpfile);
+    if (self->dumpfile)
+        free(self->dumpfile);

-	if (! (self->dumpfile = _shout_util_strdup (dumpfile)))
-		return self->error = SHOUTERR_MALLOC;
+    self->dumpfile = util_strdup (dumpfile);
+    if (self->dumpfile == NULL)
+        return self->error = SHOUTERR_MALLOC;

-	return self->error = SHOUTERR_SUCCESS;
+    return self->error = SHOUTERR_SUCCESS;
}

const char *shout_get_dumpfile(shout_t *self)
{
-	if (!self)
-		return NULL;
+    if (!self)
+        return NULL;

-	return self->dumpfile;
+    return self->dumpfile;
}

+
+
+/* this really needs looking at, embedding info into one headers can be limiting */
int shout_set_audio_info(shout_t *self, const char *name, const char *value)
{
-	return self->error = _shout_util_dict_set(self->audio_info, name, value);
+    return self->error = util_dict_set(self->audio_info, name, value);
}

const char *shout_get_audio_info(shout_t *self, const char *name)
{
-	return _shout_util_dict_get(self->audio_info, name);
+    return util_dict_get(self->audio_info, name);
}

+
int shout_set_public(shout_t *self, unsigned int public)
{
if (!self || (public != 0 && public != 1))
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

self->public = public;
@@ -705,11 +981,21 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

-	if (format != SHOUT_FORMAT_VORBIS && format != SHOUT_FORMAT_MP3)
-		return self->error = SHOUTERR_UNSUPPORTED;
+    switch (format)
+    {
+        case SHOUT_FORMAT_VORBISPAGE:
+        case SHOUT_FORMAT_VORBIS:
+            self->format_open = shout_open_vorbis;
+            break;
+        case SHOUT_FORMAT_MP3:
+            self->format_open = shout_open_mp3;
+            break;
+        default:
+            return self->error = SHOUTERR_UNSUPPORTED;
+    }

self->format = format;

@@ -729,13 +1015,26 @@
if (!self)
return SHOUTERR_INSANE;

-	if (self->connected)
+	if (self->state != SHOUT_NOCONNECT)
return self->error = SHOUTERR_CONNECTED;

-	if (protocol != SHOUT_PROTOCOL_HTTP &&
-	    protocol != SHOUT_PROTOCOL_XAUDIOCAST &&
-	    protocol != SHOUT_PROTOCOL_ICY)
-		return self->error = SHOUTERR_UNSUPPORTED;
+    switch (protocol)
+    {
+        case SHOUT_PROTOCOL_HTTP:
+            self->get_response = login_http;
+            self->create_request = create_http_request;
+            break;
+        case SHOUT_PROTOCOL_XAUDIOCAST:
+            self->get_response = login_ok;
+            self->create_request = create_xaudiocast_request;
+            break;
+        case SHOUT_PROTOCOL_ICY:
+            self->get_response = login_ok;
+            self->create_request = create_icy_request;
+            break;
+        default:
+            return self->error = SHOUTERR_UNSUPPORTED;
+    }

self->protocol = protocol;

@@ -750,253 +1049,267 @@
return self->protocol;
}

-/* -- static function definitions -- */
+int shout_connection_ready (shout_t *self)
+{
+    if (self)
+        return self->state == SHOUT_READY;
+    return 0;
+}

-static int send_http_request(shout_t *self, char *username, char *password)
+
+shout_metadata_t *shout_metadata_new(void)
{
-	char *auth;
-	char *ai;
+    return util_dict_new();
+}

-	if (!sock_write(self->socket, "SOURCE %s HTTP/1.0\r\n", self->mount))
-		return SHOUTERR_SOCKET;
+void shout_metadata_free(shout_metadata_t *self)
+{
+    if (!self)
+        return;
+
+    util_dict_free(self);
+}
+
+int shout_metadata_add(shout_metadata_t *self, const char *name, const char *value)
+{
+    if (!self || !name)
+        return SHOUTERR_INSANE;
+    return util_dict_set(self, name, value);
+}

-	if (self->password && (auth = http_basic_authorization(self))) {
-		if (!sock_write(self->socket, auth)) {
-			free(auth);
-			return SHOUTERR_SOCKET;
-		}
-		free(auth);
-	}

-	if (!sock_write(self->socket, "ice-name: %s\r\n", self->name != NULL ? self->name : "no name"))
-		return SHOUTERR_SOCKET;
-	if (self->url) {
-		if (!sock_write(self->socket, "ice-url: %s\r\n", self->url))
-			return SHOUTERR_SOCKET;
-	}
-	if (self->genre) {
-		if (!sock_write(self->socket, "ice-genre: %s\r\n", self->genre))
-			return SHOUTERR_SOCKET;
-	}
-#if 0
-	ai = shout_get_audio_info(self, SHOUT_AI_BITRATE);

-	if (bitrate && !sock_write(self->socket, "ice-bitrate: %s\r\n", bitrate))
-		return SHOUTERR_SOCKET;
-#else
-	if ((ai = _shout_util_dict_urlencode(self->audio_info, ';'))) {
-		if (!sock_write(self->socket, "ice-audio-info: %s\r\n", ai)) {
-			free(ai);
-			return SHOUTERR_SOCKET;
-		}
-	}
-#endif
-	if (!sock_write(self->socket, "ice-public: %d\r\n", self->public))
-		return SHOUTERR_SOCKET;
-	if (self->description) {
-		if (!sock_write(self->socket, "ice-description: %s\r\n", self->description))
-			return SHOUTERR_SOCKET;
-	}
-	if (self->useragent) {
-		if (!sock_write(self->socket, "User-Agent: %s\r\n", self->useragent))
-			return SHOUTERR_SOCKET;
-	}
-	if (self->format == SHOUT_FORMAT_VORBIS) {
-		if (!sock_write(self->socket, "Content-Type: application/ogg\r\n"))
-			return SHOUTERR_SOCKET;
-	} else if (self->format == SHOUT_FORMAT_MP3) {
-		if (!sock_write(self->socket, "Content-Type: audio/mpeg\r\n"))
-			return SHOUTERR_SOCKET;
-	}
+int shout_set_metadata(shout_t *self, shout_metadata_t *metadata)
+{
+    sock_t socket;
+    int ret;
+    char *encvalue;

-	if (!sock_write(self->socket, "\r\n"))
-		return SHOUTERR_SOCKET;
+    if (!self)
+        return SHOUTERR_INSANE;

-	return SHOUTERR_SUCCESS;
+    if (metadata == NULL)
+        return self->error = SHOUTERR_INSANE;
+
+    if (self->state != SHOUT_READY)
+        return self->error = SHOUTERR_UNCONNECTED;
+
+    encvalue = util_dict_urlencode(metadata, '&');
+    if (encvalue == NULL)
+        return self->error = SHOUTERR_MALLOC;
+
+    ret = SHOUTERR_NOCONNECT;
+    if ((socket = sock_connect(self->host, self->port)) >= 0)
+    {
+        int rv = 1;
+        if (self->protocol == SHOUT_PROTOCOL_ICY)
+            rv = sock_write(socket, "GET /admin.cgi?mode=updinfo&pass=%s&%s HTTP/1.0\r\nUser-Agent: %s (Mozilla compatible)\r\n\r\n",
+                    self->password, encvalue, shout_get_agent(self));
+        else if (self->protocol == SHOUT_PROTOCOL_HTTP)
+        {
+            char *auth = http_basic_authorization(self);
+
+            rv = sock_write(socket, "GET /admin/metadata?mode=updinfo&mount=%s&%s HTTP/1.0\r\nUser-Agent: %s\r\n%s\r\n",
+                    self->mount, encvalue, shout_get_agent(self), auth ? auth : "");
+        }
+        if (rv)
+            ret = SHOUTERR_SUCCESS;
+        else
+            ret = SHOUTERR_SOCKET;
+        sock_close(socket);
+    }
+
+    free (encvalue);
+
+    return self->error = ret;
}

-static char *http_basic_authorization(shout_t *self)
+
+int shout_send_raw (shout_t *self, const void *data, size_t len)
{
-	char *out, *in;
-	int len;
+    int written = 0;
+    const char *ptr = data;

-	if (!self || !self->user || !self->password)
-		return NULL;
+    if (self->pending_queue)
+        shout_send_pending (self);

-	len = strlen(self->user) + strlen(self->password) + 2;
-	if (!(in = malloc(len)))
-		return NULL;
-	sprintf(in, "%s:%s", self->user, self->password);
-	out = _shout_util_base64_encode(in);
-	free(in);
-
-	len = strlen(out) + 24;
-	if (!(in = malloc(len))) {
-		free(out);
-		return NULL;
-	}
-	sprintf(in, "Authorization: Basic %s\r\n", out);
-	free(out);
-
-	return in;
+    if (self->pending_queue == NULL)
+    {
+        written = shout_try_write (self, data, len);
+        if (written == (int)len || written < 0)
+            return written;
+    }
+    if (shout_queue_raw (self, ptr+written, len-written) < 0)
+        return -1;
+    return (int)len;
}

-static int login_http_basic(shout_t *self)
+
+
+void shout_sync(shout_t *self)
{
-	char header[4096];
-	http_parser_t *parser;
-	int code;
-	char *retcode;
-#if 0
-	char *realm;
-#endif
-
-	self->error = SHOUTERR_SOCKET;
+    int64_t sleep;

-   	self->socket = sock_connect(self->host, self->port);
-	if (self->socket < 0) {
-		return self->error = SHOUTERR_NOCONNECT;
-	}
+    if (!self)
+        return;

-#if 0
-	if(send_http_request(self, NULL, NULL) != 0) {
-#else
-	/* assume we'll have to authenticate, saves round trips on basic */
-	if(send_http_request(self, self->user, self->password) != 0) {
-#endif
-		return self->error = SHOUTERR_SOCKET;
-	}
+    if (self->senttime == 0)
+        return;

-	if (_shout_util_read_header(self->socket, header, 4096) == 0) {
-		/* either we didn't get a complete header, or we timed out */
-		return self->error = SHOUTERR_SOCKET;
-	}
+    sleep = self->senttime/1000 - (timing_get_time() - self->starttime);

-	parser = httpp_create_parser();
-	httpp_initialize(parser, NULL);
-	if (httpp_parse_response(parser, header, strlen(header), self->mount)) {
-		retcode = httpp_getvar(parser, HTTPP_VAR_ERROR_CODE);
-		code = atoi(retcode);
-		if(code >= 200 && code < 300) {
-			httpp_destroy(parser);
-			return SHOUTERR_SUCCESS;
-		}
-#if 0
-		else if(code == 401) {
-			/* Don't really use this right now other than to check that it's
-			* present.
-			*/
-			realm = httpp_getvar(parser, "www-authenticate");
-			if(realm) {
-				httpp_destroy(parser);
-				sock_close(self->socket);
+    // printf ("senttime is %lld, sleep is %lld\n", self->senttime, sleep);
+    if (sleep > 0)
+        timing_sleep((uint64_t)sleep);
+}

-				self->socket = sock_connect(self->host, self->port);
-				if (self->socket <= 0)
-					return self->error = SHOUTERR_NOCONNECT;
+int shout_delay(shout_t *self)
+{
+    if (!self)
+        return 0;

-				if(send_http_request(self, self->user, self->password) != 0) {
-					sock_close(self->socket);
-					return self->error = SHOUTERR_SOCKET;
-				}
+    if (self->senttime == 0)
+        return 0;

-				if (_shout_util_read_header(self->socket, header, 4096) == 0) {
-					/* either we didn't get a complete header, or we timed out */
-					sock_close(self->socket);
-					return self->error = SHOUTERR_SOCKET;
-				}
-				parser = httpp_create_parser();
-				httpp_initialize(parser, NULL);
-				if (httpp_parse_response(parser, header, strlen(header), self->mount)) {
-					retcode = httpp_getvar(parser, HTTPP_VAR_ERROR_CODE);
-					code = atoi(retcode);
-					if(code >= 200 && code < 300) {
-						httpp_destroy(parser);
-						return SHOUTERR_SUCCESS;
-					}
-				}
-			}
-		}
-#endif
-	}
+    return self->senttime / 1000 - (timing_get_time() - self->starttime);
+}

-	httpp_destroy(parser);
-	return self->error = SHOUTERR_NOLOGIN;
+
+int shout_send(shout_t *self, const void *data, size_t len)
+{
+    if (self)
+    {
+        if (self->state != SHOUT_READY)
+            return self->error = SHOUTERR_UNCONNECTED;
+
+        if (self->send)
+            return self->send(self, data, len);
+
+        self->error = SHOUTERR_INSANE;
+    }
+    return SHOUTERR_INSANE;
}

-static int login_xaudiocast(shout_t *self)
+
+shout_t *shout_new(void)
{
-	char response[4096];
-	const char *bitrate;
+	shout_t *self;

-	bitrate = shout_get_audio_info(self, SHOUT_AI_BITRATE);
-	if (!bitrate)
-		bitrate = "0";
+    shout_init();  /* initialise lib is not already */

-	if (!sock_write(self->socket, "SOURCE %s %s\n", self->password, self->mount))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-name: %s\n", self->name != NULL ? self->name : "unnamed"))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-url: %s\n", self->url != NULL ? self->url : "http://www.icecast.org/"))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-genre: %s\n", self->genre != NULL ? self->genre : "icecast"))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-bitrate: %s\n", bitrate))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-public: %i\n", self->public))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "x-audiocast-description: %s\n", self->description != NULL ? self->description : "Broadcasting with the icecast streaming media server!"))
-		return SHOUTERR_SOCKET;
-	if (self->dumpfile && !sock_write(self->socket, "x-audiocast-dumpfile: %s\n", self->dumpfile))
-		return SHOUTERR_SOCKET;
+	self = (shout_t *)calloc(1, sizeof(shout_t));
+	while (self)
+    {

-	if (!sock_write(self->socket, "\n"))
-		return SHOUTERR_SOCKET;
+        if (shout_set_host (self, LIBSHOUT_DEFAULT_HOST))
+            break;

-	if (!sock_read_line(self->socket, response, sizeof(response)))
-		return SHOUTERR_SOCKET;
+        self->port = LIBSHOUT_DEFAULT_PORT;
+        shout_set_format (self,  LIBSHOUT_DEFAULT_FORMAT);
+        shout_set_protocol (self, LIBSHOUT_DEFAULT_PROTOCOL);
+
+        if (shout_set_user (self, LIBSHOUT_DEFAULT_USER) < SHOUTERR_SUCCESS)
+            break;
+        if (shout_set_agent (self, LIBSHOUT_DEFAULT_USERAGENT) < SHOUTERR_SUCCESS)
+            break;

-	if (!strstr(response, "OK"))
-		return SHOUTERR_NOLOGIN;
+        if ((self->audio_info = util_dict_new()) == NULL)
+            break;
+
+        self->send_header = malloc (MAX_HTTP_SENT);
+        if (self->send_header == NULL)
+            break;
+        self->send_header_offset = 0;

-	return SHOUTERR_SUCCESS;
+        self->response = malloc (MAX_HTTP_RESPONSE);
+        if (self->response == NULL)
+            break;
+        self->read_timeout = 10;   /* default 10 seconds */
+        self->pending_total = 0;
+        self->pending_limit = 65535;  /* don't queue more than this */
+        self->pending_queue_tail = &self->pending_queue;
+        self->response_len = 0;
+
+        return self;
+    }
+    shout_free(self);
+
+	return NULL;
}

-int login_icy(shout_t *self)
+
+void shout_set_read_timeout (shout_t *self, unsigned timeout)
{
-	char response[4096];
-	const char *bitrate;
+    if (self)
+        self->read_timeout = timeout;
+}

-	bitrate = shout_get_audio_info(self, SHOUT_AI_BITRATE);
-	if (!bitrate)
-		bitrate = "0";

-	if (!sock_write(self->socket, "%s\n", self->password))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "icy-name:%s\n", self->name != NULL ? self->name : "unnamed"))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "icy-url:%s\n", self->url != NULL ? self->url : "http://www.icecast.org/"))
-		return SHOUTERR_SOCKET;
+void shout_set_nonblocking (shout_t *self, int nonblock)
+{
+     self->nonblocking = nonblock;
+     if (sock_valid_socket(self->socket))
+         sock_set_blocking (self->socket, nonblock?SOCK_NONBLOCK:SOCK_BLOCK);
+}

-	/* Fields we don't use */
-	if (!sock_write(self->socket, "icy-irc:\nicy-aim:\nicy-icq:\n"))
-		return SHOUTERR_SOCKET;

-	if (!sock_write(self->socket, "icy-pub:%i\n", self->public))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "icy-genre:%s\n", self->genre != NULL ? self->genre : "icecast"))
-		return SHOUTERR_SOCKET;
-	if (!sock_write(self->socket, "icy-br:%s\n", bitrate))
-		return SHOUTERR_SOCKET;
+int shout_close(shout_t *self)
+{
+    if (!self)
+        return SHOUTERR_INSANE;

-	if (!sock_write(self->socket, "\n"))
-		return SHOUTERR_SOCKET;
+    self->starttime = 0;
+    if (self->send_header)
+    {
+        self->send_header_offset = 0;
+        self->send_header_size = 0;
+    }
+    if (self->response)
+    {
+        self->response_len = 0;
+    }

-	if (!sock_read_line(self->socket, response, sizeof(response)))
-		return SHOUTERR_SOCKET;
+    /* send what we can if any pending */
+    shout_send_pending (self);
+    /* do memory cleanup */
+    shout_free_pending (self);

-	if (!strstr(response, "OK"))
-		return SHOUTERR_NOLOGIN;
+    if (self->close)
+        self->close(self);

-	return SHOUTERR_SUCCESS;
+    if (self->socket > -1)
+        sock_close(self->socket);
+    self->socket = -1;
+    self->pending_connection = 0;
+
+    if (self->state == SHOUT_NOCONNECT)
+        self->error = SHOUTERR_UNCONNECTED;
+    else
+        self->error = SHOUTERR_SUCCESS;
+
+    self->state = SHOUT_NOCONNECT;
+	return self->error;
}
+
+
+void shout_free(shout_t *self)
+{
+	if (!self) return;
+
+	if (self->host) free(self->host);
+	if (self->password) free(self->password);
+	if (self->mount) free(self->mount);
+	if (self->name) free(self->name);
+	if (self->url) free(self->url);
+	if (self->genre) free(self->genre);
+	if (self->description) free(self->description);
+	if (self->user) free(self->user);
+    if (self->useragent) free(self->useragent);
+    if (self->audio_info) util_dict_free (self->audio_info);
+    if (self->response) free (self->response);
+    if (self->send_header) free (self->send_header);
+
+    shout_free_pending (self);
+	free(self);
+}
+

Modified: icecast/branches/kh/libshout/src/shout_private.h
===================================================================
--- icecast/branches/kh/libshout/src/shout_private.h	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/shout_private.h	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,12 +1,28 @@
-/* shout.h: Private libshout data structures and declarations */
+/* shout.h: Private libshout data structures and declarations
+ *
+ * Copyright(c) 2003 Karl Heyes <karl at pts.tele2.co.uk>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; See the file COPYING
+ *
+ * if not, write to the Free Software Foundation, Inc., 59 Temple
+ * Place, Suite 330, Boston, MA  02111-1307  USA
+ */

+
#ifndef __LIBSHOUT_SHOUT_PRIVATE_H__
#define __LIBSHOUT_SHOUT_PRIVATE_H__

-#ifdef HAVE_CONFIG_H
-# include "config.h"
-#endif
-
#include <shout/shout.h>
#include <net/sock.h>
#include <timing/timing.h>
@@ -19,6 +35,12 @@
#  include <inttypes.h>
#endif

+
+/* anymore than this is silly */
+#define MAX_HTTP_SENT       4096
+#define MAX_HTTP_RESPONSE   1024
+
+
#define LIBSHOUT_DEFAULT_HOST "localhost"
#define LIBSHOUT_DEFAULT_PORT 8000
#define LIBSHOUT_DEFAULT_FORMAT SHOUT_FORMAT_VORBIS
@@ -26,57 +48,150 @@
#define LIBSHOUT_DEFAULT_USER "source"
#define LIBSHOUT_DEFAULT_USERAGENT "libshout/" VERSION

+typedef enum
+{
+    SHOUT_NOCONNECT,
+    SHOUT_CONNECTED,
+    SHOUT_REQ_MADE,
+    SHOUT_REQ_SENT,
+    SHOUT_READY
+} shout_state_t;
+
struct shout {
-	/* hostname or IP of icecast server */
-	char *host;
-	/* port of the icecast server */
-	int port;
-	/* login password for the server */
-	char *password;
-	/* server protocol to use */
-	unsigned int protocol;
-	/* type of data being sent */
-	unsigned int format;
-	/* audio encoding parameters */
-	util_dict *audio_info;
+    /* hostname or IP of icecast server */
+    char *host;
+    /* port of the icecast server */
+    int port;
+    /* login password for the server */
+    char *password;
+    /* server protocol to use */
+    unsigned int protocol;
+    /* type of data being sent */
+    unsigned int format;
+    /* audio encoding parameters */
+    util_dict *audio_info;

-	/* user-agent to use when doing HTTP login */
-	char *useragent;
-	/* mountpoint for this stream */
-	char *mount;
-	/* name of the stream */
-	char *name;
-	/* homepage of the stream */
-	char *url;
-	/* genre of the stream */
-	char *genre;
-	/* description of the stream */
-	char *description;
-	/* icecast 1.x dumpfile */
-	char *dumpfile;
-	/* username to use for HTTP auth. */
-	char *user;
-	/* is this stream private? */
-	int public;
+    /* user-agent to use when doing HTTP login */
+    char *useragent;
+    /* mountpoint for this stream */
+    char *mount;
+    /* name of the stream */
+    char *name;
+    /* homepage of the stream */
+    char *url;
+    /* genre of the stream */
+    char *genre;
+    /* description of the stream */
+    char *description;
+    /* icecast 1.x dumpfile */
+    char *dumpfile;
+    /* username to use for HTTP auth. */
+    char *user;
+    /* bitrate of this stream */
+    int bitrate;
+    /* is this stream private? */
+    int public;

-	/* are we connected to a server? */
-	int connected;
-	/* socket the connection is on */
-	sock_t socket;
+    /* socket the connection is on */
+    sock_t socket;

-	void *format_data;
-	int (*send)(shout_t* self, const unsigned char* buff, size_t len);
-	void (*close)(shout_t* self);
+    /* timeout for reading sockets in blocking mode */
+    unsigned read_timeout;

-	/* start of this period's timeclock */
-	uint64_t starttime;
-	/* amout of data we've sent (in milliseconds) */
-	uint64_t senttime;
+    void *format_data;
+    int (*send)(shout_t* self, const void * buff, unsigned len);
+    void (*close)(shout_t* self);
+    int (*get_response)(shout_t *self);
+    int (*format_open)(shout_t *self);
+    int (*create_request)(shout_t *self);

-	int error;
+    const char *mime_type;
+
+    /* start of this period's timeclock */
+    uint64_t starttime;
+    /* amount of data we've sent (in milliseconds) */
+    uint64_t senttime;
+
+    int error;
+
+    /* general state information */
+    shout_state_t  state;
+    int nonblocking;
+    int pending_connection;
+
+    signed char *send_header;
+    int send_header_size;
+    int send_header_offset;
+
+    unsigned char *response;
+    unsigned response_len;
+    time_t response_senttime;
+
+    unsigned pending_total;
+    unsigned pending_limit;
+    struct shout_pending_node *pending_queue, **pending_queue_tail;
};

+
+struct shout_metadata {
+	char *name;
+	char *value;
+	shout_metadata_t *next;
+};
+
+struct shout_pending_node
+{
+    void *data;   /* actual data start */
+    void *start;  /* somewhere in data */
+    unsigned len;
+    struct shout_pending_node *next;
+};
+
+static __inline__ int send_header_write (shout_t *self, int count)
+{
+    if (count < 0)
+        return 1;
+
+    self->send_header_size += count;
+    if (self->send_header_size >= MAX_HTTP_SENT)
+        return 1;
+    return 0;
+}
+
+static __inline__ signed char *send_header_end (shout_t *self)
+{
+    return self->send_header + self->send_header_size;
+}
+
+static __inline__ int send_header_remaining (shout_t *self)
+{
+    return MAX_HTTP_SENT - self->send_header_size;
+}
+
+#ifdef HAVE_VA_ARGS
+#define add_send_header(x, ...)  send_header_write((x),snprintf(send_header_end(x) , send_header_remaining(x) , __VA_ARGS__))
+#else
+static __inline__ int add_send_header (shout_t *self, const char *fmt, ...)
+{
+    char *start = send_header_end (self);
+    unsigned len = send_header_remaining (self);
+    int ret;
+    va_list ap;
+    va_start (ap, fmt);
+    ret = send_header_write (self, vsnprintf (start, len, fmt, ap));
+    va_end (ap);
+    return ret;
+}
+#endif
+
+
+
+
int shout_open_vorbis(shout_t *self);
int shout_open_mp3(shout_t *self);
+int shout_queue_raw (shout_t *self, const void *data, size_t len);
+int shout_write_direct (shout_t *self, const struct iovec *vecs, size_t count);
+int shout_store_vec (shout_t *self, const struct iovec *vecs, size_t count, size_t written);

+
#endif /* __LIBSHOUT_SHOUT_PRIVATE_H__ */

Modified: icecast/branches/kh/libshout/src/util.c
===================================================================
--- icecast/branches/kh/libshout/src/util.c	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/util.c	2004-07-06 07:12:13 UTC (rev 7017)
@@ -1,305 +1,237 @@
-/* util.c: libshout utility/portability functions
- *
- *  Copyright (C) 2002-2003 the Icecast team <team at icecast.org>
- *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Library General Public
- *  License as published by the Free Software Foundation; either
- *  version 2 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Library General Public License for more details.
- *
- *  You should have received a copy of the GNU Library General Public
- *  License along with this library; if not, write to the Free
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
+/* util.c: libshout utility/portability functions */

#ifdef HAVE_CONFIG_H
- #include <config.h>
+ #include "config.h"
#endif

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

#include <sys/types.h>
-#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
-#endif
-#ifdef HAVE_WINSOCK2_H
-#include <winsock2.h>
-#endif
+#include <errno.h>

#include <shout/shout.h>
+
#include "util.h"

-char *_shout_util_strdup(const char *s)
+char *util_strdup(const char *s)
{
-	if (!s)
-		return NULL;
-
+	if (!s) return NULL;
return strdup(s);
}

-int _shout_util_read_header(int sock, char *buff, unsigned long len)
-{
-	int read_bytes, ret;
-	unsigned long pos;
-	char c;

-	read_bytes = 1;
-	pos = 0;
-	ret = 0;
-
-	while ((read_bytes == 1) && (pos < (len - 1))) {
-		read_bytes = 0;
-
-		if ((read_bytes = recv(sock, &c, 1, 0))) {
-			if (c != '\r')
-				buff[pos++] = c;
-			if ((pos > 1) && (buff[pos - 1] == '\n' && buff[pos - 2] == '\n')) {
-				ret = 1;
-				break;
-			}
-		} else {
-			break;
-		}
-	}
-
-	if (ret) buff[pos] = '\0';
-
-	return ret;
-}
-
-static char base64table[65] = {
+static char base64table[64] = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
-    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
+    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};

/* This isn't efficient, but it doesn't need to be */
-char *_shout_util_base64_encode(char *data)
+char *util_base64_encode(char *data)
{
-	int len = strlen(data);
-	char *out = malloc(len*4/3 + 4);
-	char *result = out;
-	int chunk;
+    int len = strlen(data);
+    char *out = malloc(len*4/3 + 4);
+    char *result = out;
+    int chunk;

-	while(len > 0) {
-		chunk = (len >3)?3:len;
-		*out++ = base64table[(*data & 0xFC)>>2];
-		*out++ = base64table[((*data & 0x03)<<4) | ((*(data+1) & 0xF0) >> 4)];
+    while(len > 0) {
+        chunk = (len >3)?3:len;
+        *out++ = base64table[(*data & 0xFC)>>2];
+        *out++ = base64table[((*data & 0x03)<<4) | ((*(data+1) & 0xF0) >> 4)];
+        switch(chunk) {
+            case 3:
+                *out++ = base64table[((*(data+1) & 0x0F)<<2) | ((*(data+2) & 0xC0)>>6)];
+                *out++ = base64table[(*(data+2)) & 0x3F];
+                break;
+            case 2:
+                *out++ = base64table[((*(data+1) & 0x0F)<<2)];
+                *out++ = '=';
+                break;
+            case 1:
+                *out++ = '=';
+                *out++ = '=';
+                break;
+        }
+        data += chunk;
+        len -= chunk;
+    }
+    *out = 0;

-		switch(chunk) {
-		case 3:
-			*out++ = base64table[((*(data+1) & 0x0F)<<2) | ((*(data+2) & 0xC0)>>6)];
-			*out++ = base64table[(*(data+2)) & 0x3F];
-			break;
-		case 2:
-			*out++ = base64table[((*(data+1) & 0x0F)<<2)];
-			*out++ = '=';
-			break;
-		case 1:
-			*out++ = '=';
-			*out++ = '=';
-			break;
-		}
-		data += chunk;
-		len -= chunk;
-	}
-	*out = 0;
-
-	return result;
+    return result;
}

+
static char urltable[16] = {
-	'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
+            '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
};

-static char safechars[256] = {
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,
-      0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
-      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,
-      0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
-      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-};
-
/* modified from libshout1, which credits Rick Franchuk <rickf at transpect.net>.
* Caller must free result. */
-char *_shout_util_url_encode(const char *data) {
-	const char *p;
-	char *q, *dest;
-	int digit;
-	size_t n;
+char *util_url_encode(const char *data) {
+    const char *p;
+    char *q, *dest;
+    int digit;
+    size_t n;

-	for (p = data, n = 0; *p; p++) {
-		n++;
-		if (!safechars[(unsigned char)(*p)])
-			n += 2;
-	}
-	if (!(dest = malloc(n+1)))
-		return NULL;
-
-	for (p = data, q = dest; *p; p++, q++) {
-		if (safechars[(unsigned char)(*p)]) {
-			*q = *p;
-		} else {
-			*q++ = '%';
-			digit = (*p >> 4) & 0xF;
-			*q++ = urltable[digit];
-			digit = *p & 0xf;
-			*q = urltable[digit];
-			n += 2;
-		}
-	}
-	*q = '\0';
+    for (p = data, n = 0; *p; p++) {
+        n++;
+        if (!isalnum((int)*p))
+            n += 2;
+    }
+    if (!(dest = malloc(n+1)))
+        return NULL;

-	return dest;
+    for (p = data, q = dest; *p; p++, q++) {
+        if (isalnum((int)*p)) {
+            *q = *p;
+        } else {
+            *q++ = '%';
+            digit = (*p >> 4) & 0xF;
+            *q++ = urltable[digit];
+            digit = *p & 0xf;
+            *q = urltable[digit];
+            n += 2;
+        }
+    }
+    *q = '\0';
+
+    return dest;
}

-util_dict *_shout_util_dict_new(void)
+util_dict *util_dict_new(void)
{
-	return (util_dict *)calloc(1, sizeof(util_dict));
+    return (util_dict *)calloc(1, sizeof(util_dict));
}

-void _shout_util_dict_free(util_dict *dict)
+void util_dict_free(util_dict *dict)
{
-	util_dict *next;
+    util_dict *next;

-	while (dict) {
-		next = dict->next;
+    while (dict) {
+        next = dict->next;

-		if (dict->key)
-			free (dict->key);
-		if (dict->val)
-			free (dict->val);
-		free (dict);
+        if (dict->key)
+            free (dict->key);
+        if (dict->val)
+            free (dict->val);
+        free (dict);

-		dict = next;
-	}
+        dict = next;
+    }
}

-const char *_shout_util_dict_get(util_dict *dict, const char *key)
+const char *util_dict_get(util_dict *dict, const char *key)
{
-	while (dict) {
-		if (dict->key && !strcmp(key, dict->key))
-			return dict->val;
-		dict = dict->next;
-	}
+    while (dict) {
+        if (dict->key && !strcmp(key, dict->key))
+            return dict->val;
+        dict = dict->next;
+    }

-	return NULL;
+    return NULL;
}

-int _shout_util_dict_set(util_dict *dict, const char *key, const char *val)
+int util_dict_set(util_dict *dict, const char *key, const char *val)
{
-	util_dict *prev;
+    util_dict *prev;

-	if (!dict || !key)
-		return SHOUTERR_INSANE;
+    if (!dict || !key)
+        return SHOUTERR_INSANE;

-	prev = NULL;
-	while (dict) {
-		if (!dict->key || !strcmp(dict->key, key))
-			break;
-		prev = dict;
-		dict = dict->next;
-	}
+    prev = NULL;
+    while (dict) {
+        if (!dict->key || !strcmp(dict->key, key))
+            break;
+        prev = dict;
+        dict = dict->next;
+    }

-	if (!dict) {
-		dict = _shout_util_dict_new();
-		if (!dict)
-			return SHOUTERR_MALLOC;
-		if (prev)
-			prev->next = dict;
-	}
+    if (!dict) {
+        dict = util_dict_new();
+        if (!dict)
+            return SHOUTERR_MALLOC;
+        if (prev)
+            prev->next = dict;
+    }
+    if (dict->key)
+        free (dict->val);
+    else if (!(dict->key = strdup(key))) {
+        if (prev)
+            prev->next = NULL;
+        util_dict_free (dict);

-	if (dict->key)
-		free (dict->val);
-	else if (!(dict->key = strdup(key))) {
-		if (prev)
-			prev->next = NULL;
-		_shout_util_dict_free (dict);
+        return SHOUTERR_MALLOC;
+    }

-		return SHOUTERR_MALLOC;
-	}
+    dict->val = strdup(val);
+    if (!dict->val) {
+        return SHOUTERR_MALLOC;
+    }

-	dict->val = strdup(val);
-	if (!dict->val) {
-		return SHOUTERR_MALLOC;
-	}
-
-	return SHOUTERR_SUCCESS;
+    return SHOUTERR_SUCCESS;
}

/* given a dictionary, URL-encode each key and val and stringify them in order as
-  key=val&key=val... if val is set, or just key&key if val is NULL.
-  TODO: Memory management needs overhaul. */
-char *_shout_util_dict_urlencode(util_dict *dict, char delim)
+ *   key=val&key=val... if val is set, or just key&key if val is NULL.
+ *     TODO: Memory management needs overhaul. */
+char *util_dict_urlencode(util_dict *dict, char delim)
{
-	char *res, *tmp;
-	char *enc;
-	int start = 1;
+    char *res, *tmp;
+    char *enc;
+    int start = 1;

-	for (res = NULL; dict; dict = dict->next) {
-		/* encode key */
-		if (!dict->key)
-			continue;
-		if (!(enc = _shout_util_url_encode(dict->key))) {
-			if (res)
-				free(res);
-			return NULL;
-		}
-		if (start) {
-			if (!(res = malloc(strlen(enc) + 1))) {
-				free(enc);
-				return NULL;
-			}
-			sprintf(res, "%s", enc);
-			free(enc);
-			start = 0;
-		} else {
-			if (!(tmp = realloc(res, strlen(res) + strlen(enc) + 2))) {
-				free(enc);
-				free(res);
-				return NULL;
-			} else
-				res = tmp;
-			sprintf(res + strlen(res), "%c%s", delim, enc);
-			free(enc);
-		}
+    for (res = NULL; dict; dict = dict->next) {
+        /* encode key */
+        if (!dict->key)
+            continue;
+        if (!(enc = util_url_encode(dict->key))) {
+            if (res)
+                free(res);
+            return NULL;
+        }
+        if (start) {
+            if (!(res = malloc(strlen(enc) + 1))) {
+                free(enc);
+                return NULL;
+            }
+            sprintf(res, "%s", enc);
+            free(enc);
+            start = 0;
+        } else {
+            if (!(tmp = realloc(res, strlen(res) + strlen(enc) + 2))) {
+                free(enc);
+                free(res);
+                return NULL;
+            } else
+                res = tmp;
+            sprintf(res + strlen(res), "%c%s", delim, enc);
+            free(enc);
+        }

-		/* encode value */
-		if (!dict->val)
-			continue;
-		if (!(enc = _shout_util_url_encode(dict->val))) {
-			free(res);
-			return NULL;
-		}
+        /* encode value */
+        if (!dict->val)
+            continue;
+        if (!(enc = util_url_encode(dict->val))) {
+            free(res);
+            return NULL;
+        }

-		if (!(tmp = realloc(res, strlen(res) + strlen(enc) + 2))) {
-			free(enc);
-			free(res);
-			return NULL;
-		} else
-			res = tmp;
-		sprintf(res + strlen(res), "=%s", enc);
-		free(enc);
-	}
+        if (!(tmp = realloc(res, strlen(res) + strlen(enc) + 2))) {
+            free(enc);
+            free(res);
+            return NULL;
+        } else
+            res = tmp;
+        sprintf(res + strlen(res), "=%s", enc);
+        free(enc);
+    }

-	return res;
+    return res;
}
+
+

Modified: icecast/branches/kh/libshout/src/util.h
===================================================================
--- icecast/branches/kh/libshout/src/util.h	2004-07-06 07:05:05 UTC (rev 7016)
+++ icecast/branches/kh/libshout/src/util.h	2004-07-06 07:12:13 UTC (rev 7017)
@@ -4,24 +4,25 @@
#define __LIBSHOUT_UTIL_H__

/* String dictionary type, without support for NULL keys, or multiple
- * instances of the same key */
+ *  * instances of the same key */
typedef struct _util_dict {
-  char *key;
-  char *val;
-  struct _util_dict *next;
+    char *key;
+    char *val;
+    struct _util_dict *next;
} util_dict;

-char *_shout_util_strdup(const char *s);
+char *util_strdup(const char *s);

-util_dict *_shout_util_dict_new(void);
-void _shout_util_dict_free(util_dict *dict);
+util_dict *util_dict_new(void);
+void util_dict_free(util_dict *dict);
/* dict, key must not be NULL. */
-int _shout_util_dict_set(util_dict *dict, const char *key, const char *val);
-const char *_shout_util_dict_get(util_dict *dict, const char *key);
-char *_shout_util_dict_urlencode(util_dict *dict, char delim);
+int util_dict_set(util_dict *dict, const char *key, const char *val);
+const char *util_dict_get(util_dict *dict, const char *key);
+char *util_dict_urlencode(util_dict *dict, char delim);

-char *_shout_util_base64_encode(char *data);
-char *_shout_util_url_encode(const char *data);
-int _shout_util_read_header(int sock, char *buff, unsigned long len);
+char *util_strdup(const char *s);
+char *util_base64_encode(char *data);
+int util_read_header(int sock, char *buff, unsigned long len);

+
#endif /* __LIBSHOUT_UTIL_H__ */



More information about the commits mailing list