[asterisk-commits] dhubbard: branch dhubbard/res_fax_spandsp r203171 - in /team/dhubbard/res_fax...

SVN commits to the Asterisk project asterisk-commits at lists.digium.com
Thu Jun 25 11:30:53 CDT 2009


Author: dhubbard
Date: Thu Jun 25 11:30:49 2009
New Revision: 203171

URL: http://svn.asterisk.org/svn-view/asterisk?view=rev&rev=203171
Log:
add res_fax.c, res_fax.h, and res_fax.conf.sample

Added:
    team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample   (with props)
    team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h   (with props)
    team/dhubbard/res_fax_spandsp/res/res_fax.c   (with props)

Added: team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample
URL: http://svn.asterisk.org/svn-view/asterisk/team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample?view=auto&rev=203171
==============================================================================
--- team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample (added)
+++ team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample Thu Jun 25 11:30:49 2009
@@ -1,0 +1,24 @@
+; Generic Fax Application configuration 
+
+[general]
+; Maximum Transmission Rate
+; Possible values are { 2400 | 4800 | 7200 | 9600 | 12000 | 14400 }
+; Set this value to the maximum desired transfer rate.  Default: 14400
+maxrate=14400
+
+; Minimum Transmission Rate
+; Possible values are { 2400 | 4800 | 7200 | 9600 | 12000 | 14400 }
+; Set this value to the minimum desired transfer rate.  Default: 2400
+minrate=2400
+
+; Send Progress/Status events to manager session
+; Manager events with 'call' class permissions will receive events indicating the
+; steps to initiate a fax session.  Fax completion events are always sent to manager
+; sessions with 'call' class permissions, regardless of the value of this option.
+; Default: no
+statusevents=yes
+
+; modem capabilities
+; Possible values are { v17 | v27 | v29 }
+; Set this value to modify the default modem options.  Default: v17,v27,v29
+modems=v17,v27,v29

Propchange: team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Propchange: team/dhubbard/res_fax_spandsp/configs/res_fax.conf.sample
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h
URL: http://svn.asterisk.org/svn-view/asterisk/team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h?view=auto&rev=203171
==============================================================================
--- team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h (added)
+++ team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h Thu Jun 25 11:30:49 2009
@@ -1,0 +1,276 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008-2009, Digium, Inc.
+ *
+ * Dwayne M. Hubbard <dwayne.hubbard at gmail.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+#include "asterisk.h"
+#include "asterisk/lock.h"
+#include "asterisk/linkedlists.h"
+#include "asterisk/module.h"
+#include "asterisk/utils.h"
+#include "asterisk/options.h"
+#include "asterisk/frame.h"
+#include "asterisk/cli.h"
+#include "asterisk/stringfields.h"
+
+#ifndef _ASTERISK_RES_FAX_H
+#define _ASTERISK_RES_FAX_H
+
+/*! \brief capabilities for res_fax to locate a fax technology module */
+enum ast_fax_capabilities {
+	/*! SendFax is supported */
+	AST_FAX_TECH_SEND    = (1 << 0),
+	/*! ReceiveFax is supported */
+	AST_FAX_TECH_RECEIVE = (1 << 1),
+	/*! Audio FAX session required */
+	AST_FAX_TECH_AUDIO   = (1 << 2),
+	/*! T38/UDPTL FAX session required */
+	AST_FAX_TECH_UDP     = (1 << 3),
+	/*! TCP FAX session required */
+	AST_FAX_TECH_TCP     = (1 << 4),
+	/*! RTP FAX session required */
+	AST_FAX_TECH_RTP     = (1 << 5),
+};
+
+/*! \brief fax modem capabilities */
+enum ast_fax_modem {
+	/*! V.17 */
+	AST_FAX_MODEM_V17 = (1 << 0),
+	/*! V.27 */
+	AST_FAX_MODEM_V27 = (1 << 1),
+	/*! V.29 */
+	AST_FAX_MODEM_V29 = (1 << 2),
+	/*! V.34 */
+	AST_FAX_MODEM_V34 = (1 << 3),
+};
+
+/*! \brief current state of a fax session */
+enum ast_fax_state {
+	/*! uninitialized state */
+	AST_FAX_STATE_UNINITIALIZED = 0,
+	/*! initialized state */
+	AST_FAX_STATE_INITIALIZED,
+	/*! fax resources open state */
+	AST_FAX_STATE_OPEN,
+	/*! fax session in progress */
+	AST_FAX_STATE_ACTIVE,
+	/*! fax session complete */
+	AST_FAX_STATE_COMPLETE,
+	/*! fax session is a zombie and will be destroyed soon */
+	AST_FAX_STATE_ZOMBIE,
+};
+
+/*! \brief fax session options */
+enum ast_fax_optflag {
+	/*! false/disable configuration override */
+	AST_FAX_OPTFLAG_FALSE = 0,
+	/*! true/enable configuration override */
+	AST_FAX_OPTFLAG_TRUE,
+	/*! use the configured default */
+	AST_FAX_OPTFLAG_DEFAULT,
+};
+
+/*! \brief The data communicated between the high level applications and the generic fax function */
+struct ast_fax_session_details {
+	/*! fax session capability requirements.  The caps field is used to select
+ 	 * the proper fax technology module before the session starts */
+	enum ast_fax_capabilities caps;
+	/*! modem requirement for the session */
+	uint32_t modems;
+	/*! session id */
+	int id;
+	AST_DECLARE_STRING_FIELDS(
+		/*! filename for the fax to send or receive */
+		AST_STRING_FIELD(filename);
+		/*! resolution negotiated during the fax session.  This is stored in the
+	 	 * FAXRESOLUTION channel variable when the fax session completes */
+		AST_STRING_FIELD(resolution);
+		/*! transfer rate negotiated during the fax session.  This is stored in the
+	 	 * FAXBITRATE channel variable when the fax session completes */
+		AST_STRING_FIELD(transfer_rate);
+		/*! local station identification.  This is set from the LOCALSTATIONID
+	 	 * channel variable before the fax session starts */
+		AST_STRING_FIELD(localstationid);
+		/*! remote station identification.  This is stored in the REMOTESTATIONID
+	 	 * channel variable after the fax session completes */
+		AST_STRING_FIELD(remotestationid);
+		/*! headerinfo variable is set from the LOCALHEADERINFO channel variable
+	 	 * before the fax session starts */
+		AST_STRING_FIELD(headerinfo);
+		/*! the result of the fax session */
+		AST_STRING_FIELD(result);
+		/*! a more descriptive result string of the fax session */
+		AST_STRING_FIELD(resultstr);
+		/*! the error reason of the fax session */
+		AST_STRING_FIELD(error);
+	);
+	/*! the number of pages sent/received during a fax session */
+	int pages_transferred;
+	/*! session details flags for options */
+	union {
+		/*! dontuse dummy variable - do not ever use */	
+		uint32_t dontuse;
+		struct {
+			/*! flag to send debug manager events */
+			uint32_t debug:2;
+			/*! flag indicating the use of Error Correction Mode (ECM) */
+			uint32_t ecm:2;
+			/*! flag indicating the sending of status manager events */
+			uint32_t statusevents:2;
+			/*! request switch to T.38 */
+			uint32_t request_t38:2;
+			/*! indicating the session switched to T38 (and is 
+ 			 * the reason that the session was cancelled.
+			 */
+			uint32_t switch_to_t38:1;
+		};
+	} option;
+	/*! override the minimum transmission rate with a channel variable */
+	int minrate;
+	/*! override the maximum transmission rate with a channel varialbe */
+	int maxrate;
+	/*! override the maximum expected T38 delay with a channel variable */
+	int maxdelay;
+	/*! override the configured eccdata setting with a channel variable */
+	int eccdata;
+	/*! override the configured eccsignal setting with a channel variable */
+	int eccsignal;
+};
+
+struct ast_fax_tech;
+struct ast_fax_debug_info;
+	
+/*! \brief The data required to handle a fax session */
+struct ast_fax_session {
+	/*! session id */
+	int id;
+	/*! session file descriptor */
+	int fds;
+	/*! the number of open file descriptors */
+	int fdcount;
+	/*! fax session details structure */
+	struct ast_fax_session_details *details;
+	/*! session transport type */
+	int transport;
+	/*! fax frames received */
+	long frames_received;
+	/*! fax frames sent */
+	long frames_sent;
+	/*! the fax technology callbacks */
+	const struct ast_fax_tech *tech;
+	/*! private implementation pointer */
+	void *tech_pvt;
+	/*! stack-to-Asterisk UDPTL session */
+	struct sockaddr_in us;
+	/*! Asterisk-to-stack UDPTL session */
+	struct sockaddr_in them;
+	/*! fax state */
+	enum ast_fax_state state;
+	/*! name of the Asterisk channel using the fax session */
+	char *channame;
+	/*! the 'to Asterisk' frame used by the fax session */
+	struct ast_frame frame_toast;
+	/*! Asterisk channel using the fax session */
+	struct ast_channel *chan;
+	/*! fax debugging structure */
+	struct ast_fax_debug_info *debug_info;
+	/*! the start of time in reference to this fax session */
+	struct timeval base_tv;
+	/*! used to take variable-sized frames in and output frames of an expected size to the fax stack */
+	struct ast_smoother *smoother;
+};
+
+/*! \brief used to register a FAX technology module with res_fax */
+struct ast_fax_tech {
+	/*! the type of fax session supported with this ast_fax_tech structure */
+	const char * const type;
+	/*! a short description of the fax technology */
+	const char * const description;
+	/*! version string of the technology module */
+	const char * const version;
+	/*! the ast_fax_capabilities supported by the fax technology */
+	enum ast_fax_capabilities caps;
+	/*! module information for the fax technology */
+	struct ast_module *module;
+	/*! creates a new fax session */
+	void *(* const new_session)(struct ast_fax_session *session, struct ast_fax_session_details *req);
+	/*! destroys an existing fax session */
+	void *(* const destroy_session)(struct ast_fax_session *session);
+	/*! sends an Asterisk frame to res_fax */
+	struct ast_frame *(* read)(struct ast_fax_session *session);
+	/*! writes an Asterisk frame to the fax session */
+	int (* write)(struct ast_fax_session *session, struct ast_frame *frame);
+	/*! the type of frame expected by the fax session */;
+	int (* session_frametype)(struct ast_fax_session *session);
+	/*! starts the fax session */
+	int (* start_session)(struct ast_fax_session *session);
+	/*! cancels a fax session */
+	int (* cancel_session)(struct ast_fax_session *session);
+	/*! initiates the generation of silence to the fax session */
+	int (* generate_silence)(struct ast_fax_session *session);
+	/*! displays capabilities of the fax technology */
+	char * (* cli_show_capabilities)(int fd);
+	/*! displays details about the fax session */
+	char * (* cli_show_session)(struct ast_fax_session *session, int fd);
+	/*! displays statistics from the fax technology module */
+	char * (* cli_show_stats)(int fd);
+};
+  
+/*! \brief when fax debugging is enabled */
+struct ast_fax_debug_info {
+	/*! consecutive silence/non-silence frames from the stack to the channel */
+	int consec_s2c;
+	/*! consecutive silence/non-silence frames from the channel to the stack */
+	int consec_c2s;
+	union {
+		/*! dontuse dummy variable - do not ever use */	
+		uint32_t dontuse;
+		struct {
+			/*! silence flag in the stack to channel direction */
+			uint32_t silence_s2c:1;
+			/*! silence flag in the channel to stack direction */
+			uint32_t silence_c2s:1;
+		};
+	} flags;
+	/*! the frame to inspect in the stack to channel direction */
+	struct ast_frame *frame_s2c;
+	/*! the frame to inspect in the channel to stack direction */
+	struct ast_frame *frame_c2s;
+	/*! function to provide debug information on a per-frame bases */
+	int (* debug_frame_hook)(struct ast_fax_session *s);
+};
+
+/*! \brief register a fax technology */
+int ast_fax_tech_register(struct ast_fax_tech *tech);
+
+/*! \brief unregister a fax technology */
+void ast_fax_tech_unregister(struct ast_fax_tech *tech);
+
+/*! \brief unreference a ast_fax_session from a technology module.  This is used when a session
+ * switches from audio to T38 but the technology module must finish clearing out the session before the session can be destroyed.
+ */
+void *ast_fax_session_unreference(struct ast_fax_session *fax);
+
+/*! \brief get the minimum supported fax rate */
+unsigned short int ast_fax_minrate(void);
+
+/*! \brief get the maxiumum supported fax rate */
+unsigned short int ast_fax_maxrate(void);
+
+/*! \brief convert an ast_fax_state to a string */
+const char *ast_fax_state_to_str(enum ast_fax_state state);
+
+#endif

Propchange: team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Propchange: team/dhubbard/res_fax_spandsp/include/asterisk/res_fax.h
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dhubbard/res_fax_spandsp/res/res_fax.c
URL: http://svn.asterisk.org/svn-view/asterisk/team/dhubbard/res_fax_spandsp/res/res_fax.c?view=auto&rev=203171
==============================================================================
--- team/dhubbard/res_fax_spandsp/res/res_fax.c (added)
+++ team/dhubbard/res_fax_spandsp/res/res_fax.c Thu Jun 25 11:30:49 2009
@@ -1,0 +1,1750 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008-2009, Digium, Inc.
+ *
+ * Dwayne M. Hubbard <dwayne.hubbard at gmail.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Generic Fax Resource for FAX technology resource modules
+ *
+ * \author Dwayne M. Hubbard <dwayne.hubbard at gmail.com>
+ * 
+ * A generic fax resource module that provides SendFAX and ReceiveFAX applications.
+ * This module requires a fax technology module, like res_fax_spandsp or res_fax_digium, 
+ * to register with it so it can use the technology module to perform the actual 
+ * fax transmissions.
+ * \ingroup applications
+ */
+
+#include <asterisk.h>
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <time.h>
+#include <sys/time.h>
+
+#include <asterisk/io.h>
+#include <asterisk/file.h>
+#include <asterisk/logger.h>
+#include <asterisk/module.h>
+#include <asterisk/app.h>
+#include <asterisk/lock.h>
+#include <asterisk/options.h>
+#include <asterisk/strings.h>
+#include <asterisk/cli.h>
+#include <asterisk/utils.h>
+#include <asterisk/config.h>
+#include <asterisk/astobj2.h>
+#include <asterisk/res_fax.h>
+#include <asterisk/file.h>
+#include <asterisk/channel.h>
+#include <asterisk/pbx.h>
+#include <asterisk/manager.h>
+
+//#include "version.h"
+#ifndef PRODUCT_VERSION
+#define PRODUCT_VERSION "trunk"
+#endif
+
+static const char app_receivefax[] = "ReceiveFAX";
+static const char synopsis_receivefax[] = "Receive a FAX and save as a TIFF/F file.";
+static const char descrip_receivefax[] = "ReceiveFAX(filename[,options]):\n"
+ " The ReceiveFAX() application receives a FAX as a TIFF file with specified filename.\n"
+ " The application arguments are:\n"
+ "    'd' - enables FAX debugging\n"
+ "    's' - send progress Manager events (overrides statusevents setting in res_fax.conf)\n"
+ "\n"
+ " Use the FAXOPT function to specify session arguments prior to calling ReceiveFAX()\n"
+ " and use FAXOPT after ReceiveFAX completes to query result status for the session.\n"
+ " The ReceiveFAX() is provided by res_fax, which is a fax technology agnostic module\n"
+ " that utilizes fax technology resource modules to complete a fax transmission.\n";
+
+static const char app_sendfax[] = "SendFAX";
+static const char synopsis_sendfax[] = "SendFAX a specified TIFF/F file during a FAX transmission.";
+static const char descrip_sendfax[] = "SendFAX(filename[,options]):\n"
+ " The SendFAX() application sends the specified TIFF file during a FAX transmission.\n"
+ " The application arguments are:\n"
+ "    'd' - enables FAX debugging\n"
+ "    's' - send progress Manager events (overrides statusevents setting in res_fax.conf)\n"
+ "    'z' - request channel switch to T.38 mode\n"
+ "\n"
+ " Use the FAXOPT function to specify session arguments prior to calling SendFAX()\n"
+ " and use FAXOPT after SendFAX completes to query result status for the session.\n"
+ " The SendFAX() application is provided by res_fax, which is a fax technology agnostic module\n"
+ " that utilizes fax technology resource modules to complete a fax transmission.\n";
+
+static struct ast_fax_session_details *session_details_new(void);
+
+static int debug_check_frame_for_silence(struct ast_fax_session *s)
+{	
+	int index, c2s, sil = 0;
+	int *consec, lastconsec = 0, issil, wassil = 0;
+	unsigned short sflag;
+	struct timeval now, diff;
+	struct ast_frame *frame;
+
+	now = ast_tvnow();
+
+	if (s->debug_info->frame_s2c) {
+		c2s = 0;
+		frame = s->debug_info->frame_s2c;
+		sflag = s->debug_info->flags.silence_s2c;
+		consec = &s->debug_info->consec_s2c;
+	} else if (s->debug_info->frame_c2s) {
+		c2s = 1;
+		frame = s->debug_info->frame_c2s;
+		sflag = s->debug_info->flags.silence_c2s;
+		consec = &s->debug_info->consec_c2s;
+	} else {
+		ast_log(LOG_WARNING, "Channel '%s' fax session '%d' failed to debug frame.\n", s->channame, s->id);
+		return -1;
+	}
+
+	diff = ast_tvsub(now, s->base_tv);
+
+	/* scan a large section of the frame payload for silence.  If there is mostly silence
+	 * in the range that we scanned, then assume that the entire frame is silence. */
+	for (index = 40; index < MIN(120, frame->samples); index++) {
+		if ((((unsigned short *) frame->data.ptr) + index) == 0) {
+			sil++;
+		}
+	}
+
+	if (sil > 50) {
+		issil = 1;
+		if (!sflag) {
+			wassil = 0;
+			sflag = 1;
+			lastconsec = *consec;
+			*consec = 0;
+		}
+	} else {
+		issil = 0;
+		if (sflag) {
+			wassil = 1;
+			sflag = 0;
+			lastconsec = *consec;
+			*consec = 0;
+		}
+	}
+
+	if (!(*consec) && (option_verbose > 5)) {
+		ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' fax session '%d', [ %.3ld.%.6ld ],  %-18s completed sending '%4d' frames (%6d ms) of '%-7s', now sending '%-7s'.\n",
+			    s->channame, s->id, (long)diff.tv_sec, (long int)diff.tv_usec,
+			    (c2s) ? ">>>>>> (to stack)" : "<<<<<< (to chan)", lastconsec, (lastconsec * 20),
+			    (wassil) ? "silence" : "energy", (issil) ? "silence" : "energy");
+	}
+
+	if (c2s) {
+		s->debug_info->flags.silence_c2s = sflag;
+		s->debug_info->consec_c2s++;
+	} else {
+		s->debug_info->flags.silence_s2c = sflag;
+		s->debug_info->consec_s2c++;
+	}
+
+	return 0;
+}
+
+static void destroy_callback(void *data) 
+{
+	struct ast_fax_session_details *details = data;
+	
+	if (details) {
+		ao2_ref(details, -1);
+	}
+}
+
+static const struct ast_datastore_info fax_datastore = {
+	.type = "fax",
+	.destroy = destroy_callback,
+};
+
+/*! \brief returns a reference counted pointer to a fax datastore, if it exists */
+static struct ast_fax_session_details *find_details(struct ast_channel *chan)
+{
+	struct ast_fax_session_details *details = NULL;
+	struct ast_datastore *datastore = NULL;
+
+	ast_channel_lock(chan);	
+	datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL);
+	if (datastore == NULL) {
+		ast_channel_unlock(chan);	
+		return NULL;
+	}
+	if (!(details = datastore->data)) {
+		ast_log(LOG_WARNING, "Huh?  channel '%s' has a fax datastore without data!\n", chan->name);
+		ast_channel_unlock(chan);
+		return NULL;
+	}
+	ao2_ref(details, 1);	
+	ast_channel_unlock(chan);	
+
+	return details;
+}
+
+/*! \brief returns a reference counted details structure from the channel's fax datastore.  If the datastore
+ * does not exist it will be created */	
+static struct ast_fax_session_details *get_details(struct ast_channel *chan)
+{
+	struct ast_fax_session_details *details = NULL;
+	struct ast_datastore *datastore = NULL;
+
+	if ((details = find_details(chan))) {
+		return details;
+	}
+
+	/* channel does not have one so we must create one */
+	if (!(details = session_details_new())) {
+		ast_log(LOG_WARNING, "channel '%s' can't get a fax details structure for the datastore!\n", chan->name);
+		return NULL;
+	}
+	if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
+		ao2_ref(details, -1);
+		ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", chan->name);
+		return NULL;
+	}
+	datastore->data = details;
+
+	/* add the datastore to the channel and increment the refcount */
+	ast_channel_lock(chan);
+	ast_channel_datastore_add(chan, datastore);
+	ast_channel_unlock(chan);
+	ao2_ref(details, 1);
+
+	return details;
+}
+
+enum {
+	OPT_CALLEDMODE = (1 << 0),
+	OPT_CALLERMODE = (1 << 1),
+	OPT_DEBUG      = (1 << 2),
+	OPT_STATUS     = (1 << 3),
+	OPT_T38SWITCH  = (1 << 4),
+};
+
+AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
+	AST_APP_OPTION('a', OPT_CALLEDMODE),
+	AST_APP_OPTION('c', OPT_CALLERMODE),
+	AST_APP_OPTION('d', OPT_DEBUG),
+	AST_APP_OPTION('s', OPT_STATUS),
+	AST_APP_OPTION('z', OPT_T38SWITCH),
+END_OPTIONS);
+
+/*! \brief maximum buckets for res_fax ao2 containers */
+#define DGMFAX_MAXBUCKETS 10
+
+#define RES_FAX_TIMEOUT 10000
+
+#define APP_FAX_ERROR(fax, chan, reason)	\
+	do {	\
+		ast_log(LOG_ERROR, "channel '%s' fax session '%d' failure, reason: '%s'\n", chan->name, fax->id, reason); \
+		pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", reason); \
+		res = ms = -1; \
+	} while (0)
+
+/*! \brief The faxregistry is used to manage information and statistics for all fax sessions. */
+static struct {
+	/*! The number of active fax sessions */
+	int active_sessions;
+	/*! active sessions are astobj2 objects */
+	struct ao2_container *container;
+	/*! Total number of Tx fax attempts */
+	int fax_tx_attempts;
+	/*! Total number of Rx fax attempts */
+	int fax_rx_attempts;
+	/*! Number of successful fax transmissions */
+	int fax_complete;
+	/*! Number of failed fax transmissions */
+	int fax_failures;
+	/*! the next unique session name */
+	int nextsessionname;
+} faxregistry;
+
+/*! \brief registered fax technology modules are put into this list */
+struct fax_module_list {
+	const struct ast_fax_tech *tech;
+	AST_RWLIST_ENTRY(fax_module_list) list;
+};
+static int fax_module_list_size;
+static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module_list);
+
+/*! \brief The astobj2 hash callback for sessions */
+static int session_hash_cb(const void *obj, const int flags);
+/*! \brief The astobj2 compare callback for sessions */
+static int session_cmp_cb(void *obj, void *arg, int flags);
+
+#define RES_FAX_MINRATE 2400
+#define RES_FAX_MAXRATE 14400
+#define RES_FAX_STATUSEVENTS 0
+#define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
+
+static struct {
+	uint32_t modem;
+	uint32_t statusevents:1;
+	unsigned short minrate;	
+	unsigned short maxrate;
+} general_options;
+
+static const char *config = "res_fax.conf";
+
+static int global_fax_debug = 0;
+
+unsigned short ast_fax_maxrate(void)
+{
+	return general_options.maxrate;
+}
+
+unsigned short ast_fax_minrate(void)
+{
+	return general_options.minrate;
+}
+
+static int update_modem_bits(uint32_t *bits, const char *value)
+{		
+	char *m[5], *tok, *v = (char *)value;
+	int i = 0, j;
+
+	if (!(tok = strchr(v, ','))) {
+		m[i++] = v;
+		m[i] = NULL;
+	} else {
+		tok = strtok(v, ", ");
+		while (tok && (i < 5)) {
+			m[i++] = tok;
+			tok = strtok(NULL, ", ");
+		}
+		m[i] = NULL;
+	}
+
+	*bits = 0;
+	for (j = 0; j < i; j++) {
+		if (!strcasecmp(m[j], "v17")) {
+			*bits |= AST_FAX_MODEM_V17;
+		} else if (!strcasecmp(m[j], "v27")) {
+			*bits |= AST_FAX_MODEM_V27;
+		} else if (!strcasecmp(m[j], "v29")) {
+			*bits |= AST_FAX_MODEM_V29;
+		} else {
+			ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29}\n", m[j]);
+		}
+	}
+	return 0;
+}
+
+static int ast_fax_modem_to_str(uint32_t bits, char *tbuf, size_t bufsize)
+{
+	int count = 0;
+
+	if (bits & AST_FAX_MODEM_V17) {
+		strcat(tbuf, "V17");
+		count++;
+	}
+	if (bits & AST_FAX_MODEM_V27) {
+		if (count) {
+			strcat(tbuf, ",");
+		}
+		strcat(tbuf, "V27");
+		count++;
+	}
+	if (bits & AST_FAX_MODEM_V29) {
+		if (count) {
+			strcat(tbuf, ",");
+		}
+		strcat(tbuf, "V29");
+		count++;
+	}
+
+	return 0;
+}
+
+/*! \brief register a fax technology module */
+int ast_fax_tech_register(struct ast_fax_tech *tech)
+{
+	struct fax_module_list *fax;
+
+	if (!tech || !tech->module) {
+		ast_log(LOG_ERROR, "Cannot register a fax technology missing '%s' structure!\n", tech ? "technology module" : "ast_fax_tech");
+		return -1;
+	}
+	/* make sure the required callbacks are available */
+	if (!tech->new_session ||
+	    !tech->destroy_session ||
+	    !tech->read ||
+	    !tech->write ||
+	    !tech->session_frametype ||
+	    !tech->start_session ||
+	    !tech->cancel_session ||
+	    !tech->cli_show_capabilities ||
+	    !tech->cli_show_session ||
+	    !tech->cli_show_stats) {
+		ast_log(LOG_ERROR, "'%s' fax technology module is missing required callbacks and cannot be registered.\n", tech->description);
+		return -1;
+	}
+
+	AST_RWLIST_WRLOCK(&faxmodules);
+	AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
+		if (!strcasecmp(tech->type, fax->tech->type)) {
+			AST_RWLIST_UNLOCK(&faxmodules);
+			ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
+			return -1;
+		}
+	}
+	
+	if (!(fax = ast_calloc(1, sizeof(*fax)))) {
+		AST_RWLIST_UNLOCK(&faxmodules);
+		return -1;
+	}
+	fax->tech = tech;
+	AST_RWLIST_INSERT_HEAD(&faxmodules, fax, list);
+	fax_module_list_size++;
+	AST_RWLIST_UNLOCK(&faxmodules);
+	ast_module_ref(ast_module_info->self);
+
+	if (option_verbose > 3) {
+		ast_verbose(VERBOSE_PREFIX_3 "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
+	}
+
+	return 0;
+}
+
+/*! \brief unregister a fax technology module */
+void ast_fax_tech_unregister(struct ast_fax_tech *tech)
+{
+	struct fax_module_list *fax;
+
+	if (option_verbose > 3) {
+		ast_verbose(VERBOSE_PREFIX_3 "Unregistering fax module type '%s'\n", tech->type);
+	}
+
+	AST_RWLIST_WRLOCK(&faxmodules);
+	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
+		if (fax->tech != tech) {
+			continue;
+		}
+		AST_RWLIST_REMOVE_CURRENT(list);
+		ast_module_unref(ast_module_info->self);
+		ast_free(fax);
+		fax_module_list_size--;
+		ast_verb(4, "Unregistered fax module type '%s'\n", tech->type);
+		break;	
+	}
+	AST_RWLIST_TRAVERSE_SAFE_END;
+	AST_RWLIST_UNLOCK(&faxmodules);
+}
+
+/*! \brief unreference a fax session */
+void *ast_fax_session_unreference(struct ast_fax_session *fax)
+{
+	if (!fax) {
+		ast_log(LOG_ERROR, "no fax session to unreference!\n");
+		return NULL;
+	}
+	ao2_lock(faxregistry.container);
+	if (ao2_ref(fax, -1) == 2) {
+		ao2_unlink(faxregistry.container, fax);
+	}
+	ao2_unlock(faxregistry.container);
+	return NULL;
+}
+
+/*! \brief convert a ast_fax_state to a string */
+const char *ast_fax_state_to_str(enum ast_fax_state state)
+{
+	switch (state) {
+	case AST_FAX_STATE_UNINITIALIZED:
+		return "Uninitialized";
+	case AST_FAX_STATE_INITIALIZED:
+		return "Initialized";
+	case AST_FAX_STATE_OPEN:
+		return "Open";
+	case AST_FAX_STATE_ACTIVE:
+		return "Active";
+	case AST_FAX_STATE_COMPLETE:
+		return "Complete";
+	case AST_FAX_STATE_ZOMBIE:
+		return "Zombie";
+	default:
+		ast_log(LOG_WARNING, "unhandled fax state: %d\n", state);
+		return "Unknown";
+	}
+}
+
+/*! \brief convert a rate string to a rate */
+static int fax_rate_str_to_int(const char *ratestr)
+{
+	int rate;
+
+	if (sscanf(ratestr, "%d", &rate) != 1) {
+		ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
+		return -1;
+	}
+	switch (rate) {
+	case 2400:
+	case 4800:
+	case 7200:
+	case 9600:
+	case 12200:
+	case 14400:
+		return rate;
+	default:
+		ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12200 | 14400}\n", ratestr);
+		return -1;
+	}
+}
+
+/*! \brief destroy a fax session details structure */
+static void destroy_session_details(void *details)
+{
+	struct ast_fax_session_details *d = details;
+	
+	ast_debug(4, "destroying session details (filename: '%s')\n", d->filename ? d->filename : "<none>");
+	ast_string_field_free_memory(d);	
+}
+
+/*! \brief destroy a fax session structure */
+static void destroy_session(void *session)
+{
+	struct ast_fax_session *s = session;
+	int n = s->id;
+
+	if (s->details) {
+		ao2_ref(s->details, -1);
+	}
+	
+	if (s->tech_pvt) {
+		ast_debug(4, "freeing technology implementation structure.\n");
+		ast_free(s->tech_pvt);
+	}
+
+	if (s->debug_info) {
+		ast_debug(4, "freeing debug_info.\n");
+		ast_free(s->debug_info);
+	}
+
+	if (s->tech) {
+		ast_module_unref(s->tech->module);
+	}
+
+	if (s->smoother) {
+		ast_smoother_free(s->smoother);
+	}
+
+	ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
+
+	ast_debug(4, "channel '%s' fax session '%d' destroyed\n", s->channame, n);
+
+	ast_free(s->channame);
+}
+
+/*! \brief create a fax session details structure */
+static struct ast_fax_session_details *session_details_new(void)
+{
+	struct ast_fax_session_details *d;
+
+	if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
+		return NULL;
+	}
+	
+	if (ast_string_field_init(d, 512)) {
+		ao2_ref(d, -1);
+		return NULL;
+	}
+	/* These options need to be set to the configured default and may be overridden by
+ 	 * SendFAX, ReceiveFAX, or FAXOPT */
+	d->option.ecm = AST_FAX_OPTFLAG_DEFAULT;
+	d->option.statusevents = general_options.statusevents;
+	d->modems = general_options.modem;
+	d->minrate = -1;
+	d->maxrate = -1;
+	d->maxdelay = -1;
+	d->eccdata = -1;
+	d->eccsignal = -1;
+
+	return d;
+}
+
+/*! \brief create a fax session */
+static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan)
+{
+	struct ast_fax_session *s;
+	struct fax_module_list *faxmod;
+
+	if (!details || !chan) {
+		ast_log(LOG_ERROR, "Missing '%s' structure.\n", details ? "session details" : "channel");
+		return NULL;
+	}
+
+	if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
+		return NULL;
+	}
+
+	if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
+		if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
+			ao2_ref(s, -1);
+			return NULL;
+		}
+		s->debug_info->debug_frame_hook = debug_check_frame_for_silence;
+	}	
+
+	if (!(s->channame = ast_strdup(chan->name))) {
+		ao2_ref(s, -1);
+		return NULL;
+	}
+	s->chan = chan;
+	s->details = details;
+	ao2_ref(s->details, 1);
+	s->state = AST_FAX_STATE_UNINITIALIZED;
+
+	ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
+	details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
+
+	/* locate a fax technology module that can handle said requirements */
+	AST_RWLIST_RDLOCK(&faxmodules);
+	AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
+		if ((faxmod->tech->caps & details->caps) != details->caps) {
+			continue;
+		}
+		ast_debug(4, "Requesting a new fax session from '%s'.\n", faxmod->tech->description);
+		s->tech = faxmod->tech;
+		break;
+	}
+	AST_RWLIST_UNLOCK(&faxmodules);
+
+	if (!s->tech) {
+		ast_log(LOG_ERROR, "Could not locate a fax technology module with capabilities (0x%X)\n", details->caps);
+		ao2_ref(s, -1);
+		return NULL;
+	}
+	ast_module_ref(s->tech->module);
+
+	if (!(s->tech_pvt = s->tech->new_session(s, details))) {
+		ast_log(LOG_ERROR, "Fax session failed to initialize.\n");
+		ao2_ref(s, -1);
+		return NULL;
+	}
+	/* link the session to the session container */
+	if (!(ao2_link(faxregistry.container, s))) {
+		ast_log(LOG_ERROR, "failed to add fax session '%d' to container.\n", s->id);
+		ao2_ref(s, -1);
+		return NULL;
+	}
+	ast_debug(4, "channel '%s' using fax session '%d'\n", s->channame, s->id);
+
+	return s;
+}
+
+/*! \brief cancel an audio fax session and create a T.38 fax session */
+static struct ast_fax_session *switch_session_to_t38(struct ast_fax_session *fax, struct ast_channel *chan)
+{
+	struct ast_fax_session *t38fax;
+	struct ast_fax_session_details *t38details;
+
+	if (!(t38details = find_details(chan))) {
+		ast_log(LOG_WARNING, "channel '%s' cannot find session details.\n", chan->name);
+		return fax;
+	}
+	fax->details->option.switch_to_t38 = 1;
+	fax->tech->cancel_session(fax);
+	/* set the capabilities for a T.38 session */	
+	t38details->caps = (t38details->caps & (AST_FAX_TECH_SEND | AST_FAX_TECH_RECEIVE));
+	t38details->caps |= AST_FAX_TECH_UDP;
+
+	if (!(t38fax = fax_session_new(t38details, chan))) {
+		ast_log(LOG_ERROR, "Can't create a T.38 fax session, fax attempt failed.\n");
+		ao2_ref(t38details, -1);
+		return fax;
+	}
+	ao2_ref(t38details, -1);
+	return t38fax;
+}
+
+struct manager_event_info {
+	char context[AST_MAX_CONTEXT];
+	char exten[AST_MAX_EXTENSION];
+	char cid[128];
+};
+
+static void get_manager_event_info(struct ast_channel *chan, struct manager_event_info *info)
+{
+	pbx_substitute_variables_helper(chan, "${CONTEXT}", info->context, sizeof(info->context));
+	pbx_substitute_variables_helper(chan, "${EXTEN}", info->exten, sizeof(info->exten));
+	pbx_substitute_variables_helper(chan, "${CALLERID(num)}", info->cid, sizeof(info->cid));
+}
+
+/*! \brief send a fax status manager event */
+static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
+{
+	ast_channel_lock(chan);
+	pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", status);
+	if (details->option.statusevents) {
+		struct manager_event_info info;
+
+		get_manager_event_info(chan, &info);
+		manager_event(EVENT_FLAG_CALL,
+			      (details->caps & AST_FAX_TECH_RECEIVE) ? "ReceiveFAXStatus" : "SendFAXStatus",
+			      "%s\r\n"
+			      "Channel: %s\r\n"
+			      "Context: %s\r\n"
+			      "Exten: %s\r\n"
+			      "CallerID: %s\r\n"
+			      "LocalStationID: %s\r\n"
+			      "FileName: %s\r\n",
+			      status,
+			      chan->name,
+			      info.context,
+			      info.exten,
+			      info.cid,
+			      details->localstationid,
+			      details->filename);
+	}
+	ast_channel_unlock(chan);
+
+	return 0;
+}
+
+/*! \brief this is the generic fax session handling function */
+static int generic_fax_exec(struct ast_channel *chan, struct ast_fax_session_details *details)
+{
+	int ms = 1000;
+	int timeout = RES_FAX_TIMEOUT;
+	int res = 0, chancount, ofd;
+	int exception, expected_frametype;
+	char tbuf[10];
+	int t38negotiated = 0;
+	const char *tempvar;
+	enum ast_control_t38 t38control;
+	struct ast_fax_session *fax = NULL;
+	struct ast_frame *frame = NULL;
+	struct ast_channel *c = chan;
+
+	if (!chan || !details) {
+		ast_log(LOG_ERROR, "missing '%s' structure.\n", chan ? "session requirements" : "channel");
+		return -1;
+	}
+	chancount = 1;
+
+	/* get the session capability requirements */
+	if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
+		details->caps |= AST_FAX_TECH_UDP;
+		t38negotiated = 1;
+	} else {
+		details->caps |= AST_FAX_TECH_AUDIO;
+	}
+
+	ast_channel_lock(chan);
+	/* update session details */	
+	if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
+		ast_string_field_set(details, headerinfo, tempvar);
+	}
+	if (ast_strlen_zero(details->localstationid)) {
+		tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
+		ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
+	}
+	ast_channel_unlock(chan);
+
+	report_fax_status(chan, details, "Allocating Resources");
+
+	/* create the fax session */
+	if (!(fax = fax_session_new(details, chan))) {
+		ast_log(LOG_ERROR, "Can't create a fax session, fax attempt failed.\n");
+		report_fax_status(chan, details, "No Available Resource");
+		return -1;
+	}
+	expected_frametype = fax->tech->session_frametype(fax);
+
+	if (details->caps & AST_FAX_TECH_AUDIO) {
+		if ((res = ast_set_write_format(chan, AST_FORMAT_SLINEAR)) < 0) {
+			ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", chan->name);
+			ast_fax_session_unreference(fax);
+			ast_channel_unlock(chan);
+			return res;
+		}
+		if ((res = ast_set_read_format(chan, AST_FORMAT_SLINEAR)) < 0) {
+			ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", chan->name);
+			ast_fax_session_unreference(fax);
+			ast_channel_unlock(chan);
+			return res;
+		}
+		if (fax->smoother) {
+			ast_smoother_free(fax->smoother);
+			fax->smoother = NULL;
+		}
+		if (!(fax->smoother = ast_smoother_new(320))) {
+			ast_log(LOG_WARNING, "Channel '%s' fax session '%d' failed to obtain a smoother.\n", chan->name, fax->id);
+		}
+	}
+
+	if (t38negotiated) {
+		report_fax_status(chan, details, "T.38 Negotiated");
+	} else if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
+		/* let's try to negotiate T.38 to see if we can switch */
+		t38control = AST_T38_REQUEST_NEGOTIATE;
+		ast_indicate_data(chan, AST_CONTROL_T38, &t38control, sizeof(t38control));
+		report_fax_status(chan, details, "Negotiating T.38");
+		/* wait for result of negotiation before proceeding */
+	}
+
+	fax->base_tv = ast_tvnow();
+	if (fax->tech->start_session(fax) < 0) {
+		APP_FAX_ERROR(fax, chan, "failed to start fax session");
+	}
+
+	pbx_builtin_setvar_helper(chan, "FAXSTATUS", NULL);
+	pbx_builtin_setvar_helper(chan, "FAXERROR", NULL);
+	report_fax_status(chan, details, "Fax Transmission In Progress");
+
+	/* handle frames for the session */
+	while ((ms > -1) && (timeout > 0)) {
+		ms = 1000;
+		ast_waitfor_nandfds(&c, chancount, &fax->fds, fax->fdcount, &exception, &ofd, &ms);
+		if (ms < 0) {
+			/* bad stuff happened */
+			ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", chan->name);
+			res = ms;
+			break;
+		}
+		if (!ms) {
+			/* nothing happened */
+			if (timeout > 0) {
+				timeout -= 1000;
+				continue;
+			} else {
+				ast_log(LOG_WARNING, "channel '%s' timed-out during the fax transmission.\n", chan->name);
+				APP_FAX_ERROR(fax, chan, "fax session timed-out");
+				break;
+			}
+		}
+		if (fax->fdcount && (ofd == fax->fds)) {
+			/* read a frame from the fax stack and send it out the channel.
+ 			 * the fax stack will return a NULL if the fax session has already completed */
+			if (!(frame = fax->tech->read(fax))) {
+				break;
+			}
+
+			if (fax->debug_info && fax->debug_info->debug_frame_hook) {
+				ao2_lock(fax);
+				fax->debug_info->frame_s2c = frame;
+				fax->debug_info->debug_frame_hook(fax);
+				fax->debug_info->frame_s2c = NULL;
+				ao2_unlock(fax);
+			}
+
+			ast_write(chan, frame);
+			fax->frames_sent++;
+			ast_frfree(frame);
+			timeout = RES_FAX_TIMEOUT;
+			continue;
+		} else {
+			if (!(frame = ast_read(chan))) {
+				/* the channel is probably gone, so lets stop polling on it and let the
+ 				 * fax session complete before we exit the application.  BUT, we need to
+ 				 * send the fax stack silence so the modems can finish their session without
+ 				 * any problems */
+				c = NULL;
+				chancount = 0;
+				timeout -= (1000 - ms);
+				if (fax->tech->generate_silence) {
+					fax->tech->generate_silence(fax);
+				}
+				continue;
+			}
+
+			if (fax->debug_info && fax->debug_info->debug_frame_hook) {
+				ao2_lock(fax);
+				fax->debug_info->frame_c2s = frame;

[... 891 lines stripped ...]



More information about the asterisk-commits mailing list