Fri Jul 3 20:35:32 2009

Asterisk developer's documentation


app_fax.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Simple fax applications
00005  * 
00006  * 2007-2008, Dmitry Andrianov <asterisk@dima.spb.ru>
00007  *
00008  * Code based on original implementation by Steve Underwood <steveu@coppice.org>
00009  *
00010  * This program is free software, distributed under the terms of
00011  * the GNU General Public License
00012  *
00013  */
00014 
00015 /*** MODULEINFO
00016         <depend>spandsp</depend>
00017 ***/
00018  
00019 #include "asterisk.h"
00020 
00021 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00022 
00023 #include <string.h>
00024 #include <stdlib.h>
00025 #include <stdio.h>
00026 #include <inttypes.h>
00027 #include <pthread.h>
00028 #include <errno.h>
00029 #include <tiffio.h>
00030 
00031 #include <spandsp.h>
00032 
00033 #include "asterisk/lock.h"
00034 #include "asterisk/file.h"
00035 #include "asterisk/logger.h"
00036 #include "asterisk/channel.h"
00037 #include "asterisk/pbx.h"
00038 #include "asterisk/app.h"
00039 #include "asterisk/dsp.h"
00040 #include "asterisk/module.h"
00041 #include "asterisk/manager.h"
00042 extern int option_debug;
00043 
00044 /* Compatibility with Asterisk 1.6 */
00045 /* from logger.h: */
00046 #define ast_debug(level, ...) do {       \
00047    if (option_debug >= (level) ) \
00048       ast_log(LOG_DEBUG, __VA_ARGS__); \
00049 } while (0)
00050 
00051 /* from time.h: */
00052 inline int ast_tvdiff_sec(struct timeval end, struct timeval start)
00053 {
00054    int result = end.tv_sec - start.tv_sec;
00055    if (result > 0 && end.tv_usec < start.tv_usec)
00056       result--;
00057    else if (result < 0 && end.tv_usec > start.tv_usec)
00058       result++;
00059 
00060    return result;
00061 }
00062 
00063 int64_t ast_tvdiff_us(struct timeval end, struct timeval start)
00064 {
00065    return (end.tv_sec - start.tv_sec) * (int64_t) 1000000 +
00066       end.tv_usec - start.tv_usec;
00067 }
00068 
00069 /* End of backports */
00070 
00071 static char *app_sndfax_name = "SendFAX";
00072 static char *app_txfax_name = "TxFAX";
00073 static char *app_sndfax_synopsis = "Send a FAX";
00074 static char *app_sndfax_desc = 
00075 "  SendFAX(filename[|options]):\n"
00076 "Send a given TIFF file to the channel as a FAX.\n"
00077 "The option string may contain zero or more of the following characters:\n"
00078 "     'a' -- makes the application behave as an answering machine\n"
00079 "      The default behaviour is to behave as a calling machine.\n"
00080 "\n"
00081 "This application uses following variables:\n"
00082 "     LOCALSTATIONID to identify itself to the remote end.\n"
00083 "     LOCALHEADERINFO to generate a header line on each page.\n"
00084 "\n"
00085 "This application sets the following channel variables upon completion:\n"
00086 "     FAXSTATUS       - status of operation:\n"
00087 "           SUCCESS | FAILED\n"
00088 "     FAXERROR - Error when FAILED\n"
00089 "     REMOTESTATIONID - CSID of the remote side.\n"
00090 "     FAXPAGES - number of pages sent.\n"
00091 "     FAXBITRATE      - transmition rate.\n"
00092 "     FAXRESOLUTION   - resolution.\n"
00093 "\n"
00094 "Returns -1 in case of user hang up or any channel error.\n"
00095 "Returns 0 on success.\n";
00096 
00097 static char *app_rcvfax_name = "ReceiveFAX";
00098 static char *app_rxfax_name = "RxFAX";
00099 static char *app_rcvfax_synopsis = "Receive a FAX";
00100 static char *app_rcvfax_desc = 
00101 "  ReceiveFAX(filename[|options]):\n"
00102 "Receives a fax from the channel into the given filename overwriting\n"
00103 "the file if it already exists. File created will have TIFF format.\n"
00104 "The option string may contain zero or more of the following characters:\n"
00105 "     'c' -- makes the application behave as a calling machine\n"
00106 "      The default behaviour is to behave as an answering machine.\n"
00107 "\n"
00108 "This application uses following variables:\n"
00109 "     LOCALSTATIONID to identify itself to the remote end.\n"
00110 "     LOCALHEADERINFO to generate a header line on each page.\n"
00111 "\n"
00112 "This application sets the following channel variables upon completion:\n"
00113 "     FAXSTATUS       - status of operation:\n"
00114 "           SUCCESS | FAILED\n"
00115 "     FAXERROR - Error when FAILED\n"
00116 "     REMOTESTATIONID - CSID of the remote side.\n"
00117 "     FAXPAGES - number of pages sent.\n"
00118 "     FAXBITRATE      - transmition rate.\n"
00119 "     FAXRESOLUTION   - resolution.\n"
00120 "\n"
00121 "Returns -1 in case of user hang up or any channel error.\n"
00122 "Returns 0 on success.\n";
00123 
00124 #define MAX_SAMPLES 240
00125 
00126 /* Watchdog. I have seen situations when remote fax disconnects (because of poor line
00127    quality) while SpanDSP continues staying in T30_STATE_IV_CTC state forever.
00128    To avoid this, we terminate when we see that T30 state does not change for 5 minutes.
00129    We also terminate application when more than 30 minutes passed regardless of
00130    state changes. This is just a precaution measure - no fax should take that long */
00131 
00132 #define WATCHDOG_TOTAL_TIMEOUT   30 * 60
00133 #define WATCHDOG_STATE_TIMEOUT   5 * 60
00134 
00135 #undef AST_HAS_T38_SUPPORT
00136 
00137 typedef struct {
00138    struct ast_channel *chan;
00139 #ifdef AST_HAS_T38_SUPPORT
00140    enum ast_t38_state t38state;  /* T38 state of the channel */
00141 #endif
00142    int direction;       /* Fax direction: 0 - receiving, 1 - sending */
00143    int caller_mode;
00144    char *file_name;
00145    
00146    volatile int finished;
00147 } fax_session;
00148 
00149 static void span_message(int level, const char *msg)
00150 {
00151    if (level == SPAN_LOG_ERROR) {
00152       ast_log(LOG_ERROR, "%s", msg);
00153    } else if (level == SPAN_LOG_WARNING) {
00154       ast_log(LOG_WARNING, "%s", msg);
00155    } else {
00156       ast_log(LOG_DEBUG, "%s", msg);
00157    }
00158 }
00159 
00160 static int t38_tx_packet_handler(t38_core_state_t *s, void *user_data, const uint8_t *buf, int len, int count)
00161 {
00162    struct ast_channel *chan = (struct ast_channel *) user_data;
00163 
00164    struct ast_frame outf = {
00165       .frametype = AST_FRAME_MODEM,
00166       .subclass = AST_MODEM_T38,
00167       .src = __FUNCTION__,
00168    };
00169 
00170    /* TODO: Asterisk does not provide means of resending the same packet multiple
00171      times so count is ignored at the moment */
00172 
00173    AST_FRAME_SET_BUFFER(&outf, buf, 0, len);
00174 
00175    if (ast_write(chan, &outf) < 0) {
00176       ast_log(LOG_WARNING, "Unable to write frame to channel; %s\n", strerror(errno));
00177       return -1;
00178    }
00179 
00180    return 0;
00181 }
00182 
00183 static void phase_e_handler(t30_state_t *f, void *user_data, int result)
00184 {
00185    const char *local_ident;
00186    const char *far_ident;
00187    char buf[20];
00188    fax_session *s = (fax_session *) user_data;
00189    t30_stats_t stat;
00190 
00191    ast_debug(1, "Fax phase E handler. result=%d\n", result);
00192 
00193    t30_get_transfer_statistics(f, &stat);
00194 
00195    s = (fax_session *) user_data;
00196 
00197    if (result != T30_ERR_OK) {
00198       s->finished = -1;
00199 
00200       /* FAXSTATUS is already set to FAILED */
00201       pbx_builtin_setvar_helper(s->chan, "FAXERROR", t30_completion_code_to_str(result));
00202 
00203       ast_log(LOG_WARNING, "Error transmitting fax. result=%d: %s.\n", result, t30_completion_code_to_str(result));
00204 
00205       return;
00206    }
00207    
00208    s->finished = 1; 
00209    
00210    local_ident = t30_get_tx_ident(f);
00211    far_ident = t30_get_rx_ident(f);
00212    pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "SUCCESS"); 
00213    pbx_builtin_setvar_helper(s->chan, "FAXERROR", NULL); 
00214    pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", far_ident);
00215    snprintf(buf, sizeof(buf), "%d", stat.pages_transferred);
00216    pbx_builtin_setvar_helper(s->chan, "FAXPAGES", buf);
00217    snprintf(buf, sizeof(buf), "%d", stat.y_resolution);
00218    pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", buf);
00219    snprintf(buf, sizeof(buf), "%d", stat.bit_rate);
00220    pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", buf); 
00221    
00222    ast_debug(1, "Fax transmitted successfully.\n");
00223    ast_debug(1, "  Remote station ID: %s\n", far_ident);
00224    ast_debug(1, "  Pages transferred: %d\n", stat.pages_transferred);
00225    ast_debug(1, "  Image resolution:  %d x %d\n", stat.x_resolution, stat.y_resolution);
00226    ast_debug(1, "  Transfer Rate:     %d\n", stat.bit_rate);
00227    
00228    manager_event(EVENT_FLAG_CALL,
00229             s->direction ? "FaxSent" : "FaxReceived", 
00230             "Channel: %s\r\n"
00231             "Exten: %s\r\n"
00232             "CallerID: %s\r\n"
00233             "RemoteStationID: %s\r\n"
00234             "LocalStationID: %s\r\n"
00235             "PagesTransferred: %d\r\n"
00236             "Resolution: %d\r\n"
00237             "TransferRate: %d\r\n"
00238             "FileName: %s\r\n",
00239             s->chan->name,
00240             s->chan->exten,
00241             S_OR(s->chan->cid.cid_num, ""),
00242             far_ident,
00243             local_ident,
00244             stat.pages_transferred,
00245             stat.y_resolution,
00246             stat.bit_rate,
00247             s->file_name);
00248 }
00249 
00250 /* === Helper functions to configure fax === */
00251 
00252 /* Setup SPAN logging according to Asterisk debug level */
00253 static int set_logging(logging_state_t *state)
00254 {
00255    int level = SPAN_LOG_WARNING + option_debug;
00256 
00257    span_log_set_message_handler(state, span_message);
00258    span_log_set_level(state, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | level); 
00259 
00260    return 0;
00261 }
00262 
00263 static void set_local_info(t30_state_t *state, fax_session *s)
00264 {
00265    const char *x;
00266 
00267    x = pbx_builtin_getvar_helper(s->chan, "LOCALSTATIONID");
00268    if (!ast_strlen_zero(x))
00269       t30_set_tx_ident(state, x);
00270 
00271    x = pbx_builtin_getvar_helper(s->chan, "LOCALHEADERINFO");
00272    if (!ast_strlen_zero(x))
00273       t30_set_tx_page_header_info(state, x);
00274 }
00275 
00276 static void set_file(t30_state_t *state, fax_session *s)
00277 {
00278    if (s->direction)
00279       t30_set_tx_file(state, s->file_name, -1, -1);
00280    else
00281       t30_set_rx_file(state, s->file_name, -1);
00282 }
00283 
00284 static void set_ecm(t30_state_t *state, int ecm)
00285 {
00286    t30_set_ecm_capability(state, ecm);
00287    t30_set_supported_compressions(state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
00288 }
00289 
00290 /* === Generator === */
00291 
00292 /* This function is only needed to return passed params so
00293    generator_activate will save it to channel's generatordata */
00294 static void *fax_generator_alloc(struct ast_channel *chan, void *params)
00295 {
00296    return params;
00297 }
00298 
00299 static int fax_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
00300 {
00301    fax_state_t *fax = (fax_state_t*) data;
00302    uint8_t buffer[AST_FRIENDLY_OFFSET + MAX_SAMPLES * sizeof(uint16_t)];
00303    int16_t *buf = (int16_t *) (buffer + AST_FRIENDLY_OFFSET);
00304     
00305    struct ast_frame outf = {
00306       .frametype = AST_FRAME_VOICE,
00307       .subclass = AST_FORMAT_SLINEAR,
00308       .src = __FUNCTION__,
00309    };
00310 
00311    if (samples > MAX_SAMPLES) {
00312       ast_log(LOG_WARNING, "Only generating %d samples, where %d requested\n", MAX_SAMPLES, samples);
00313       samples = MAX_SAMPLES;
00314    }
00315    
00316    if ((len = fax_tx(fax, buf, samples)) > 0) {
00317       outf.samples = len;
00318       AST_FRAME_SET_BUFFER(&outf, buffer, AST_FRIENDLY_OFFSET, len * sizeof(int16_t));
00319 
00320       if (ast_write(chan, &outf) < 0) {
00321          ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", chan->name, strerror(errno));
00322          return -1;
00323       }
00324    }
00325 
00326    return 0;
00327 }
00328 
00329 struct ast_generator generator = {
00330    alloc:      fax_generator_alloc,
00331    generate:   fax_generator_generate,
00332 };
00333 
00334 
00335 /* === Transmission === */
00336 
00337 static int transmit_audio(fax_session *s)
00338 {
00339    int res = -1;
00340    int original_read_fmt = AST_FORMAT_SLINEAR;
00341    int original_write_fmt = AST_FORMAT_SLINEAR;
00342    fax_state_t fax;
00343    struct ast_dsp *dsp = NULL;
00344    int detect_tone = 0;
00345    struct ast_frame *inf = NULL;
00346    struct ast_frame *fr;
00347    int last_state = 0;
00348    struct timeval now, start, state_change;
00349 #ifdef AST_HAS_T38_SUPPORT
00350    enum ast_control_t38 t38control;
00351 #endif
00352 
00353    original_read_fmt = s->chan->readformat;
00354    if (original_read_fmt != AST_FORMAT_SLINEAR) {
00355       res = ast_set_read_format(s->chan, AST_FORMAT_SLINEAR);
00356       if (res < 0) {
00357          ast_log(LOG_WARNING, "Unable to set to linear read mode, giving up\n");
00358          goto done;
00359       }
00360    }
00361 
00362    original_write_fmt = s->chan->writeformat;
00363    if (original_write_fmt != AST_FORMAT_SLINEAR) {
00364       res = ast_set_write_format(s->chan, AST_FORMAT_SLINEAR);
00365       if (res < 0) {
00366          ast_log(LOG_WARNING, "Unable to set to linear write mode, giving up\n");
00367          goto done;
00368       }
00369    }
00370 
00371    /* Initialize T30 terminal */
00372    fax_init(&fax, s->caller_mode);
00373 
00374    /* Setup logging */
00375    set_logging(&fax.logging);
00376    set_logging(&fax.t30_state.logging);
00377 
00378    /* Configure terminal */
00379    set_local_info(&fax.t30_state, s);
00380    set_file(&fax.t30_state, s);
00381    set_ecm(&fax.t30_state, TRUE);
00382 
00383    fax_set_transmit_on_idle(&fax, TRUE);
00384 
00385    t30_set_phase_e_handler(&fax.t30_state, phase_e_handler, s);
00386 
00387 #ifdef AST_HAS_T38_SUPPORT
00388    if (s->t38state == T38_STATE_UNAVAILABLE) {
00389       ast_debug(1, "T38 is unavailable on %s\n", s->chan->name);
00390    } else if (!s->direction) {
00391       /* We are receiving side and this means we are the side which should
00392          request T38 when the fax is detected. Use DSP to detect fax tone */
00393       ast_debug(1, "Setting up CNG detection on %s\n", s->chan->name);
00394       dsp = ast_dsp_new();
00395       ast_dsp_set_features(dsp, DSP_FEATURE_FAX_DETECT);
00396       ast_dsp_set_faxmode(dsp, DSP_FAXMODE_DETECT_CNG);
00397       detect_tone = 1;
00398    }
00399 #endif
00400 
00401    start = state_change = ast_tvnow();
00402 
00403    ast_activate_generator(s->chan, &generator, &fax);
00404 
00405    while (!s->finished) {
00406       res = ast_waitfor(s->chan, 20);
00407       if (res < 0)
00408          break;
00409       else if (res > 0)
00410          res = 0;
00411 
00412       inf = ast_read(s->chan);
00413       if (inf == NULL) {
00414          ast_debug(1, "Channel hangup\n");
00415          res = -1;
00416          break;
00417       }
00418 
00419       ast_debug(10, "frame %d/%d, len=%d\n", inf->frametype, inf->subclass, inf->datalen);
00420 
00421 /* FIXME: that part should probably be included, not cut off (Tzafrir)*/
00422 #ifdef AST_HAS_T38_SUPPORT
00423       /* Detect fax tone */
00424       if (detect_tone && inf->frametype == AST_FRAME_VOICE) {
00425          /* Duplicate frame because ast_dsp_process may free the frame passed */
00426          fr = ast_frdup(inf);
00427 
00428          /* Do not pass channel to ast_dsp_process otherwise it may queue modified audio frame back */
00429          fr = ast_dsp_process(NULL, dsp, fr);
00430          if (fr && fr->frametype == AST_FRAME_DTMF && fr->subclass == 'f') {
00431             ast_debug(1, "Fax tone detected. Requesting T38\n");
00432             t38control = AST_T38_REQUEST_NEGOTIATE;
00433             ast_indicate_data(s->chan, AST_CONTROL_T38, &t38control, sizeof(t38control));
00434             detect_tone = 0;
00435          }
00436 
00437          ast_frfree(fr);
00438       }
00439 #endif
00440 
00441 
00442       /* Check the frame type. Format also must be checked because there is a chance
00443          that a frame in old format was already queued before we set chanel format
00444          to slinear so it will still be received by ast_read */
00445       if (inf->frametype == AST_FRAME_VOICE && inf->subclass == AST_FORMAT_SLINEAR) {
00446 
00447          if (fax_rx(&fax, inf->data, inf->samples) < 0) {
00448             /* I know fax_rx never returns errors. The check here is for good style only */
00449             ast_log(LOG_WARNING, "fax_rx returned error\n");
00450             res = -1;
00451             break;
00452          }
00453 
00454          /* Watchdog */
00455          if (last_state != fax.t30_state.state) {
00456             state_change = ast_tvnow();
00457             last_state = fax.t30_state.state;
00458          }
00459 #ifdef AST_HAS_T38_SUPPORT
00460       } else if (inf->frametype == AST_FRAME_CONTROL && inf->subclass == AST_CONTROL_T38 &&
00461             inf->datalen == sizeof(enum ast_control_t38)) {
00462          t38control =*((enum ast_control_t38 *) inf->data);
00463          if (t38control == AST_T38_NEGOTIATED) {
00464             /* T38 switchover completed */
00465             ast_debug(1, "T38 negotiated, finishing audio loop\n");
00466             res = 1;
00467             break;
00468          }
00469 #endif
00470       }
00471 
00472       ast_frfree(inf);
00473       inf = NULL;
00474 
00475       /* Watchdog */
00476       now = ast_tvnow();
00477       if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
00478          ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
00479          res = -1;
00480          break;
00481       }
00482    }
00483 
00484    ast_debug(1, "Loop finished, res=%d\n", res);
00485 
00486    if (inf)
00487       ast_frfree(inf);
00488 
00489    if (dsp)
00490       ast_dsp_free(dsp);
00491 
00492    ast_deactivate_generator(s->chan);
00493 
00494    /* If we are switching to T38, remove phase E handler. Otherwise it will be executed
00495       by t30_terminate, display diagnostics and set status variables although no transmittion
00496       has taken place yet. */
00497    if (res > 0) {
00498       t30_set_phase_e_handler(&fax.t30_state, NULL, NULL);
00499    }
00500 
00501    t30_terminate(&fax.t30_state);
00502    fax_release(&fax);
00503 
00504 done:
00505    if (original_write_fmt != AST_FORMAT_SLINEAR) {
00506       if (ast_set_write_format(s->chan, original_write_fmt) < 0)
00507          ast_log(LOG_WARNING, "Unable to restore write format on '%s'\n", s->chan->name);
00508    }
00509 
00510    if (original_read_fmt != AST_FORMAT_SLINEAR) {
00511       if (ast_set_read_format(s->chan, original_read_fmt) < 0)
00512          ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", s->chan->name);
00513    }
00514 
00515    return res;
00516 
00517 }
00518 
00519 static int transmit_t38(fax_session *s)
00520 {
00521    int res = 0;
00522    t38_terminal_state_t t38;
00523    struct ast_frame *inf = NULL;
00524    int last_state = 0;
00525    struct timeval now, start, state_change, last_frame;
00526 #ifdef AST_HAS_T38_SUPPORT
00527    enum ast_control_t38 t38control;
00528 #endif
00529 
00530    /* Initialize terminal */
00531    memset(&t38, 0, sizeof(t38));
00532    if (t38_terminal_init(&t38, s->caller_mode, t38_tx_packet_handler, s->chan) == NULL) {
00533       ast_log(LOG_WARNING, "Unable to start T.38 termination.\n");
00534       return -1;
00535    }
00536 
00537    /* Setup logging */
00538    set_logging(&t38.logging);
00539    set_logging(&t38.t30_state.logging);
00540    set_logging(&t38.t38.logging);
00541 
00542    /* Configure terminal */
00543    set_local_info(&t38.t30_state, s);
00544    set_file(&t38.t30_state, s);
00545    set_ecm(&t38.t30_state, TRUE);
00546 
00547    t30_set_phase_e_handler(&t38.t30_state, phase_e_handler, s);
00548 
00549    now = start = state_change = ast_tvnow();
00550 
00551    while (!s->finished) {
00552 
00553       res = ast_waitfor(s->chan, 20);
00554       if (res < 0)
00555          break;
00556       else if (res > 0)
00557          res = 0;
00558 
00559       last_frame = now;
00560       now = ast_tvnow();
00561       t38_terminal_send_timeout(&t38, ast_tvdiff_us(now, last_frame) / (1000000 / 8000));
00562 
00563       inf = ast_read(s->chan);
00564       if (inf == NULL) {
00565          ast_debug(1, "Channel hangup\n");
00566          res = -1;
00567          break;
00568       }
00569 
00570       ast_debug(10, "frame %d/%d, len=%d\n", inf->frametype, inf->subclass, inf->datalen);
00571 
00572       if (inf->frametype == AST_FRAME_MODEM && inf->subclass == AST_MODEM_T38) {
00573          t38_core_rx_ifp_packet(&t38.t38, inf->data, inf->datalen, inf->seqno);
00574 
00575          /* Watchdog */
00576          if (last_state != t38.t30_state.state) {
00577             state_change = ast_tvnow();
00578             last_state = t38.t30_state.state;
00579          }
00580 #ifdef AST_HAS_T38_SUPPORT
00581       } else if (inf->frametype == AST_FRAME_CONTROL && inf->subclass == AST_CONTROL_T38 &&
00582             inf->datalen == sizeof(enum ast_control_t38)) {
00583 
00584          t38control = *((enum ast_control_t38 *) inf->data);
00585 
00586          if (t38control == AST_T38_TERMINATED || t38control == AST_T38_REFUSED) {
00587             ast_debug(1, "T38 down, terminating\n");
00588             res = -1;
00589             break;
00590          }
00591 #endif
00592       }
00593 
00594       ast_frfree(inf);
00595       inf = NULL;
00596 
00597       /* Watchdog */
00598       if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
00599          ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
00600          res = -1;
00601          break;
00602       }
00603    }
00604 
00605    ast_debug(1, "Loop finished, res=%d\n", res);
00606 
00607    if (inf)
00608       ast_frfree(inf);
00609 
00610    t30_terminate(&t38.t30_state);
00611    t38_terminal_release(&t38);
00612 
00613    return res;
00614 }
00615 
00616 static int transmit(fax_session *s)
00617 {
00618    int res = 0;
00619 
00620    /* Clear all channel variables which to be set by the application.
00621       Pre-set status to error so in case of any problems we can just leave */
00622    pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "FAILED"); 
00623    pbx_builtin_setvar_helper(s->chan, "FAXERROR", "Channel problems"); 
00624 
00625    pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", NULL);
00626    pbx_builtin_setvar_helper(s->chan, "FAXPAGES", NULL);
00627    pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", NULL);
00628    pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", NULL); 
00629 
00630    if (s->chan->_state != AST_STATE_UP) {
00631       /* Shouldn't need this, but checking to see if channel is already answered
00632        * Theoretically asterisk should already have answered before running the app */
00633       res = ast_answer(s->chan);
00634       if (res) {
00635          ast_log(LOG_WARNING, "Could not answer channel '%s'\n", s->chan->name);
00636          return res;
00637       }
00638    }
00639 
00640 #ifdef AST_HAS_T38_SUPPORT
00641    s->t38state = ast_channel_get_t38_state(s->chan);
00642    if (s->t38state != T38_STATE_NEGOTIATED) {
00643 #endif
00644       /* T38 is not negotiated on the channel yet. First start regular transmission. If it switches to T38, follow */   
00645       res = transmit_audio(s);
00646       if (res > 0) {
00647          /* transmit_audio reports switchover to T38. Update t38state */
00648 #ifdef AST_HAS_T38_SUPPORT
00649          s->t38state = ast_channel_get_t38_state(s->chan);
00650          if (s->t38state != T38_STATE_NEGOTIATED) {
00651             ast_log(LOG_ERROR, "Audio loop reports T38 switchover but t38state != T38_STATE_NEGOTIATED\n");
00652          }
00653 #endif
00654       }
00655 #ifdef AST_HAS_T38_SUPPORT
00656    }
00657 
00658    if (s->t38state == T38_STATE_NEGOTIATED) {
00659       res = transmit_t38(s);
00660    }
00661 #endif
00662 
00663    if (res) {
00664       ast_log(LOG_WARNING, "Transmission error\n");
00665       res = -1;
00666    } else if (s->finished < 0) {
00667       ast_log(LOG_WARNING, "Transmission failed\n");
00668    } else if (s->finished > 0) {
00669       ast_debug(1, "Transmission finished Ok\n");
00670    }
00671 
00672    return res;
00673 }
00674 
00675 /* === Application functions === */
00676 
00677 static int sndfax_exec(struct ast_channel *chan, void *data)
00678 {
00679    int res = 0;
00680    char *parse;
00681    fax_session session;
00682 
00683    AST_DECLARE_APP_ARGS(args,
00684       AST_APP_ARG(file_name);
00685       AST_APP_ARG(options);
00686    );
00687 
00688    if (chan == NULL) {
00689       ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
00690       return -1;
00691    }
00692 
00693    /* The next few lines of code parse out the filename and header from the input string */
00694    if (ast_strlen_zero(data)) {
00695       /* No data implies no filename or anything is present */
00696       ast_log(LOG_ERROR, "SendFAX requires an argument (filename)\n");
00697       return -1;
00698    }
00699 
00700    parse = ast_strdupa(data);
00701    AST_STANDARD_APP_ARGS(args, parse);
00702    
00703    session.caller_mode = TRUE;
00704 
00705    if (args.options) {
00706       if (strchr(args.options, 'a'))
00707          session.caller_mode = FALSE;
00708    }
00709 
00710    /* Done parsing */
00711    session.direction = 1;
00712    session.file_name = args.file_name;
00713    session.chan = chan;
00714    session.finished = 0;
00715 
00716    res = transmit(&session);
00717 
00718    return res;
00719 }
00720 
00721 static int rcvfax_exec(struct ast_channel *chan, void *data)
00722 {
00723    int res = 0;
00724    char *parse;
00725    fax_session session;
00726 
00727    AST_DECLARE_APP_ARGS(args,
00728       AST_APP_ARG(file_name);
00729       AST_APP_ARG(options);
00730    );
00731 
00732    if (chan == NULL) {
00733       ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
00734       return -1;
00735    }
00736 
00737    /* The next few lines of code parse out the filename and header from the input string */
00738    if (ast_strlen_zero(data)) {
00739       /* No data implies no filename or anything is present */
00740       ast_log(LOG_ERROR, "ReceiveFAX requires an argument (filename)\n");
00741       return -1;
00742    }
00743 
00744    parse = ast_strdupa(data);
00745    AST_STANDARD_APP_ARGS(args, parse);
00746    
00747    session.caller_mode = FALSE;
00748 
00749    if (args.options) {
00750       if (strchr(args.options, 'c'))
00751          session.caller_mode = TRUE;
00752    }
00753 
00754    /* Done parsing */
00755    session.direction = 0;
00756    session.file_name = args.file_name;
00757    session.chan = chan;
00758    session.finished = 0;
00759 
00760    res = transmit(&session);
00761 
00762    return res;
00763 }
00764 
00765 static int unload_module(void)
00766 {
00767    int res;
00768 
00769    res = ast_unregister_application(app_sndfax_name); 
00770    res |= ast_unregister_application(app_txfax_name);
00771    res |= ast_unregister_application(app_rcvfax_name);   
00772    res |= ast_unregister_application(app_rxfax_name);
00773 
00774    return res;
00775 }
00776 
00777 static int load_module(void)
00778 {
00779    int res ;
00780 
00781    res = ast_register_application(app_sndfax_name, sndfax_exec, app_sndfax_synopsis, app_sndfax_desc);
00782    res |= ast_register_application(app_txfax_name, sndfax_exec, app_sndfax_synopsis, app_sndfax_desc);
00783    res |= ast_register_application(app_rcvfax_name, rcvfax_exec, app_rcvfax_synopsis, app_rcvfax_desc);
00784    res |= ast_register_application(app_rxfax_name, rcvfax_exec, app_rcvfax_synopsis, app_rcvfax_desc);
00785 
00786    /* The default SPAN message handler prints to stderr. It is something we do not want */
00787    span_set_message_handler(NULL);
00788 
00789    return res;
00790 }
00791 
00792 
00793 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Simple FAX Application",
00794       .load = load_module,
00795       .unload = unload_module,
00796       );
00797 
00798 

Generated on Fri Jul 3 20:35:32 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9