ede204437376a8eedd52c7911c1d631d8d07e204
[asterisk/asterisk.git] / apps / app_fax.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Simple fax applications
5  * 
6  * 2007-2008, Dmitry Andrianov <asterisk@dima.spb.ru>
7  *
8  * Code based on original implementation by Steve Underwood <steveu@coppice.org>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  *
13  */
14
15 /*** MODULEINFO
16          <depend>spandsp</depend>
17 ***/
18  
19 #include "asterisk.h"
20
21 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
22
23 #include <string.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <inttypes.h>
27 #include <pthread.h>
28 #include <errno.h>
29 #include <tiffio.h>
30
31 #define SPANDSP_EXPOSE_INTERNAL_STRUCTURES
32 #include <spandsp.h>
33 #include <spandsp/version.h>
34
35 #include "asterisk/lock.h"
36 #include "asterisk/file.h"
37 #include "asterisk/logger.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/app.h"
41 #include "asterisk/dsp.h"
42 #include "asterisk/module.h"
43 #include "asterisk/manager.h"
44
45 /*** DOCUMENTATION
46         <application name="SendFAX" language="en_US">
47                 <synopsis>
48                         Send a Fax
49                 </synopsis>
50                 <syntax>
51                         <parameter name="filename" required="true">
52                                 <para>Filename of TIFF file to fax</para>
53                         </parameter>
54                         <parameter name="a" required="false">
55                                 <para>Makes the application behave as the answering machine</para>
56                                 <para>(Default behavior is as calling machine)</para>
57                         </parameter>
58                 </syntax>
59                 <description>
60                         <para>Send a given TIFF file to the channel as a FAX.</para>
61                         <para>This application sets the following channel variables:</para>
62                         <variablelist>
63                                 <variable name="LOCALSTATIONID">
64                                         <para>To identify itself to the remote end</para>
65                                 </variable>
66                                 <variable name="LOCALHEADERINFO">
67                                         <para>To generate a header line on each page</para>
68                                 </variable>
69                                 <variable name="FAXSTATUS">
70                                         <value name="SUCCESS"/>
71                                         <value name="FAILED"/>
72                                 </variable>
73                                 <variable name="FAXERROR">
74                                         <para>Cause of failure</para>
75                                 </variable>
76                                 <variable name="REMOTESTATIONID">
77                                         <para>The CSID of the remote side</para>
78                                 </variable>
79                                 <variable name="FAXPAGES">
80                                         <para>Number of pages sent</para>
81                                 </variable>
82                                 <variable name="FAXBITRATE">
83                                         <para>Transmission rate</para>
84                                 </variable>
85                                 <variable name="FAXRESOLUTION">
86                                         <para>Resolution of sent fax</para>
87                                 </variable>
88                         </variablelist>
89                 </description>
90         </application>
91         <application name="ReceiveFAX" language="en_US">
92                 <synopsis>
93                         Receive a Fax
94                 </synopsis>
95                 <syntax>
96                         <parameter name="filename" required="true">
97                                 <para>Filename of TIFF file save incoming fax</para>
98                         </parameter>
99                         <parameter name="c" required="false">
100                                 <para>Makes the application behave as the calling machine</para> 
101                                 <para>(Default behavior is as answering machine)</para>
102                         </parameter>
103                 </syntax>
104                 <description>
105                         <para>Receives a FAX from the channel into the given filename 
106                         overwriting the file if it already exists.</para>
107                         <para>File created will be in TIFF format.</para>
108
109                         <para>This application sets the following channel variables:</para>
110                         <variablelist>
111                                 <variable name="LOCALSTATIONID">
112                                         <para>To identify itself to the remote end</para>
113                                 </variable>
114                                 <variable name="LOCALHEADERINFO">
115                                         <para>To generate a header line on each page</para>
116                                 </variable>
117                                 <variable name="FAXSTATUS">
118                                         <value name="SUCCESS"/>
119                                         <value name="FAILED"/>
120                                 </variable>
121                                 <variable name="FAXERROR">
122                                         <para>Cause of failure</para>
123                                 </variable>
124                                 <variable name="REMOTESTATIONID">
125                                         <para>The CSID of the remote side</para>
126                                 </variable>
127                                 <variable name="FAXPAGES">
128                                         <para>Number of pages sent</para>
129                                 </variable>
130                                 <variable name="FAXBITRATE">
131                                         <para>Transmission rate</para>
132                                 </variable>
133                                 <variable name="FAXRESOLUTION">
134                                         <para>Resolution of sent fax</para>
135                                 </variable>
136                         </variablelist>
137                 </description>
138         </application>
139
140  ***/
141
142 static const char app_sndfax_name[] = "SendFAX";
143 static const char app_rcvfax_name[] = "ReceiveFAX";
144
145 #define MAX_SAMPLES 240
146
147 /* Watchdog. I have seen situations when remote fax disconnects (because of poor line
148    quality) while SpanDSP continues staying in T30_STATE_IV_CTC state forever.
149    To avoid this, we terminate when we see that T30 state does not change for 5 minutes.
150    We also terminate application when more than 30 minutes passed regardless of
151    state changes. This is just a precaution measure - no fax should take that long */
152
153 #define WATCHDOG_TOTAL_TIMEOUT  30 * 60
154 #define WATCHDOG_STATE_TIMEOUT  5 * 60
155
156 typedef struct {
157         struct ast_channel *chan;
158         enum ast_t38_state t38state;    /* T38 state of the channel */
159         int direction;                  /* Fax direction: 0 - receiving, 1 - sending */
160         int caller_mode;
161         char *file_name;
162         struct ast_control_t38_parameters t38parameters;
163         volatile int finished;
164 } fax_session;
165
166 static void span_message(int level, const char *msg)
167 {
168         if (level == SPAN_LOG_ERROR) {
169                 ast_log(LOG_ERROR, "%s", msg);
170         } else if (level == SPAN_LOG_WARNING) {
171                 ast_log(LOG_WARNING, "%s", msg);
172         } else {
173                 ast_log(LOG_DEBUG, "%s", msg);
174         }
175 }
176
177 static int t38_tx_packet_handler(t38_core_state_t *s, void *user_data, const uint8_t *buf, int len, int count)
178 {
179         struct ast_channel *chan = (struct ast_channel *) user_data;
180
181         struct ast_frame outf = {
182                 .frametype = AST_FRAME_MODEM,
183                 .subclass.integer = AST_MODEM_T38,
184                 .src = __FUNCTION__,
185         };
186
187         /* TODO: Asterisk does not provide means of resending the same packet multiple
188           times so count is ignored at the moment */
189
190         AST_FRAME_SET_BUFFER(&outf, buf, 0, len);
191
192         if (ast_write(chan, &outf) < 0) {
193                 ast_log(LOG_WARNING, "Unable to write frame to channel; %s\n", strerror(errno));
194                 return -1;
195         }
196
197         return 0;
198 }
199
200 static void phase_e_handler(t30_state_t *f, void *user_data, int result)
201 {
202         const char *local_ident;
203         const char *far_ident;
204         char buf[20];
205         fax_session *s = (fax_session *) user_data;
206         t30_stats_t stat;
207         int pages_transferred;
208
209         ast_debug(1, "Fax phase E handler. result=%d\n", result);
210
211         t30_get_transfer_statistics(f, &stat);
212
213         s = (fax_session *) user_data;
214
215         if (result != T30_ERR_OK) {
216                 s->finished = -1;
217
218                 /* FAXSTATUS is already set to FAILED */
219                 pbx_builtin_setvar_helper(s->chan, "FAXERROR", t30_completion_code_to_str(result));
220
221                 ast_log(LOG_WARNING, "Error transmitting fax. result=%d: %s.\n", result, t30_completion_code_to_str(result));
222
223                 return;
224         }
225         
226         s->finished = 1; 
227         
228         local_ident = t30_get_tx_ident(f);
229         far_ident = t30_get_rx_ident(f);
230         pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "SUCCESS"); 
231         pbx_builtin_setvar_helper(s->chan, "FAXERROR", NULL); 
232         pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", far_ident);
233 #if SPANDSP_RELEASE_DATE >= 20090220
234         pages_transferred = (s->direction) ? stat.pages_tx : stat.pages_rx;
235 #else
236         pages_transferred = stat.pages_transferred;
237 #endif
238         snprintf(buf, sizeof(buf), "%d", pages_transferred);
239         pbx_builtin_setvar_helper(s->chan, "FAXPAGES", buf);
240         snprintf(buf, sizeof(buf), "%d", stat.y_resolution);
241         pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", buf);
242         snprintf(buf, sizeof(buf), "%d", stat.bit_rate);
243         pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", buf); 
244         
245         ast_debug(1, "Fax transmitted successfully.\n");
246         ast_debug(1, "  Remote station ID: %s\n", far_ident);
247         ast_debug(1, "  Pages transferred: %d\n", pages_transferred);
248         ast_debug(1, "  Image resolution:  %d x %d\n", stat.x_resolution, stat.y_resolution);
249         ast_debug(1, "  Transfer Rate:     %d\n", stat.bit_rate);
250         
251         ast_manager_event(s->chan, EVENT_FLAG_CALL,
252                       s->direction ? "FaxSent" : "FaxReceived", 
253                       "Channel: %s\r\n"
254                       "Exten: %s\r\n"
255                       "CallerID: %s\r\n"
256                       "RemoteStationID: %s\r\n"
257                       "LocalStationID: %s\r\n"
258                       "PagesTransferred: %d\r\n"
259                       "Resolution: %d\r\n"
260                       "TransferRate: %d\r\n"
261                       "FileName: %s\r\n",
262                       s->chan->name,
263                       s->chan->exten,
264                       S_OR(s->chan->cid.cid_num, ""),
265                       far_ident,
266                       local_ident,
267                       pages_transferred,
268                       stat.y_resolution,
269                       stat.bit_rate,
270                       s->file_name);
271 }
272
273 /* === Helper functions to configure fax === */
274
275 /* Setup SPAN logging according to Asterisk debug level */
276 static int set_logging(logging_state_t *state)
277 {
278         int level = SPAN_LOG_WARNING + option_debug;
279
280         span_log_set_message_handler(state, span_message);
281         span_log_set_level(state, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | level); 
282
283         return 0;
284 }
285
286 static void set_local_info(t30_state_t *state, fax_session *s)
287 {
288         const char *x;
289
290         x = pbx_builtin_getvar_helper(s->chan, "LOCALSTATIONID");
291         if (!ast_strlen_zero(x))
292                 t30_set_tx_ident(state, x);
293
294         x = pbx_builtin_getvar_helper(s->chan, "LOCALHEADERINFO");
295         if (!ast_strlen_zero(x))
296                 t30_set_tx_page_header_info(state, x);
297 }
298
299 static void set_file(t30_state_t *state, fax_session *s)
300 {
301         if (s->direction)
302                 t30_set_tx_file(state, s->file_name, -1, -1);
303         else
304                 t30_set_rx_file(state, s->file_name, -1);
305 }
306
307 static void set_ecm(t30_state_t *state, int ecm)
308 {
309         t30_set_ecm_capability(state, ecm);
310         t30_set_supported_compressions(state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
311 }
312
313 /* === Generator === */
314
315 /* This function is only needed to return passed params so
316    generator_activate will save it to channel's generatordata */
317 static void *fax_generator_alloc(struct ast_channel *chan, void *params)
318 {
319         return params;
320 }
321
322 static int fax_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
323 {
324         fax_state_t *fax = (fax_state_t*) data;
325         uint8_t buffer[AST_FRIENDLY_OFFSET + MAX_SAMPLES * sizeof(uint16_t)];
326         int16_t *buf = (int16_t *) (buffer + AST_FRIENDLY_OFFSET);
327     
328         struct ast_frame outf = {
329                 .frametype = AST_FRAME_VOICE,
330                 .subclass.codec = AST_FORMAT_SLINEAR,
331                 .src = __FUNCTION__,
332         };
333
334         if (samples > MAX_SAMPLES) {
335                 ast_log(LOG_WARNING, "Only generating %d samples, where %d requested\n", MAX_SAMPLES, samples);
336                 samples = MAX_SAMPLES;
337         }
338         
339         if ((len = fax_tx(fax, buf, samples)) > 0) {
340                 outf.samples = len;
341                 AST_FRAME_SET_BUFFER(&outf, buffer, AST_FRIENDLY_OFFSET, len * sizeof(int16_t));
342
343                 if (ast_write(chan, &outf) < 0) {
344                         ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", chan->name, strerror(errno));
345                         return -1;
346                 }
347         }
348
349         return 0;
350 }
351
352 static struct ast_generator generator = {
353         alloc:          fax_generator_alloc,
354         generate:       fax_generator_generate,
355 };
356
357
358 /* === Transmission === */
359
360 static int transmit_audio(fax_session *s)
361 {
362         int res = -1;
363         int original_read_fmt = AST_FORMAT_SLINEAR;
364         int original_write_fmt = AST_FORMAT_SLINEAR;
365         fax_state_t fax;
366         t30_state_t *t30state;
367         struct ast_frame *inf = NULL;
368         int last_state = 0;
369         struct timeval now, start, state_change;
370         enum ast_t38_state t38_state;
371         struct ast_control_t38_parameters t38_parameters = { .version = 0,
372                                                              .max_ifp = 800,
373                                                              .rate = AST_T38_RATE_14400,
374                                                              .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
375                                                              .fill_bit_removal = 1,
376 /*
377  * spandsp has API calls to support MMR and JBIG transcoding, but they aren't
378  * implemented quite yet... so don't offer them to the remote endpoint
379  *                                                           .transcoding_mmr = 1,
380  *                                                           .transcoding_jbig = 1,
381 */
382         };
383
384         /* if in called party mode, try to use T.38 */
385         if (s->caller_mode == FALSE) {
386                 /* check if we are already in T.38 mode (unlikely), or if we can request
387                  * a switch... if so, request it now and wait for the result, rather
388                  * than starting an audio FAX session that will have to be cancelled
389                  */
390                 if ((t38_state = ast_channel_get_t38_state(s->chan)) == T38_STATE_NEGOTIATED) {
391                         return 1;
392                 } else if ((t38_state != T38_STATE_UNAVAILABLE) &&
393                            (t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE,
394                             (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0))) {
395                         /* wait up to five seconds for negotiation to complete */
396                         unsigned int timeout = 5000;
397                         int ms;
398                         
399                         ast_debug(1, "Negotiating T.38 for receive on %s\n", s->chan->name);
400                         while (timeout > 0) {
401                                 ms = ast_waitfor(s->chan, 1000);
402                                 if (ms < 0) {
403                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", s->chan->name);
404                                         return -1;
405                                 }
406                                 if (!ms) {
407                                         /* nothing happened */
408                                         if (timeout > 0) {
409                                                 timeout -= 1000;
410                                                 continue;
411                                         } else {
412                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", s->chan->name);
413                                                 break;
414                                         }
415                                 }
416                                 if (!(inf = ast_read(s->chan))) {
417                                         return -1;
418                                 }
419                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
420                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
421                                     (inf->datalen == sizeof(t38_parameters))) {
422                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
423                                         
424                                         switch (parameters->request_response) {
425                                         case AST_T38_NEGOTIATED:
426                                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", s->chan->name);
427                                                 res = 1;
428                                                 break;
429                                         case AST_T38_REFUSED:
430                                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", s->chan->name);
431                                                 break;
432                                         default:
433                                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", s->chan->name);
434                                                 break;
435                                         }
436                                         ast_frfree(inf);
437                                         if (res == 1) {
438                                                 return 1;
439                                         } else {
440                                                 break;
441                                         }
442                                 }
443                                 ast_frfree(inf);
444                         }
445                 }
446         }
447
448 #if SPANDSP_RELEASE_DATE >= 20080725
449         /* for spandsp shaphots 0.0.6 and higher */
450         t30state = &fax.t30;
451 #else
452         /* for spandsp release 0.0.5 */
453         t30state = &fax.t30_state;
454 #endif
455
456         original_read_fmt = s->chan->readformat;
457         if (original_read_fmt != AST_FORMAT_SLINEAR) {
458                 res = ast_set_read_format(s->chan, AST_FORMAT_SLINEAR);
459                 if (res < 0) {
460                         ast_log(LOG_WARNING, "Unable to set to linear read mode, giving up\n");
461                         goto done;
462                 }
463         }
464
465         original_write_fmt = s->chan->writeformat;
466         if (original_write_fmt != AST_FORMAT_SLINEAR) {
467                 res = ast_set_write_format(s->chan, AST_FORMAT_SLINEAR);
468                 if (res < 0) {
469                         ast_log(LOG_WARNING, "Unable to set to linear write mode, giving up\n");
470                         goto done;
471                 }
472         }
473
474         /* Initialize T30 terminal */
475         fax_init(&fax, s->caller_mode);
476
477         /* Setup logging */
478         set_logging(&fax.logging);
479         set_logging(&t30state->logging);
480
481         /* Configure terminal */
482         set_local_info(t30state, s);
483         set_file(t30state, s);
484         set_ecm(t30state, TRUE);
485
486         fax_set_transmit_on_idle(&fax, TRUE);
487
488         t30_set_phase_e_handler(t30state, phase_e_handler, s);
489
490         start = state_change = ast_tvnow();
491
492         ast_activate_generator(s->chan, &generator, &fax);
493
494         while (!s->finished) {
495                 inf = NULL;
496
497                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
498                         ast_debug(1, "Error waiting for a frame\n");
499                         break;
500                 }
501
502                 /* Watchdog */
503                 now = ast_tvnow();
504                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
505                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
506                         res = -1;
507                         break;
508                 }
509
510                 if (!res) {
511                         /* There was timeout waiting for a frame. Loop around and wait again */
512                         continue;
513                 }
514
515                 /* There is a frame available. Get it */
516                 res = 0;
517
518                 if (!(inf = ast_read(s->chan))) {
519                         ast_debug(1, "Channel hangup\n");
520                         res = -1;
521                         break;
522                 }
523
524                 ast_debug(10, "frame %d/%llu, len=%d\n", inf->frametype, (unsigned long long) inf->subclass.codec, inf->datalen);
525
526                 /* Check the frame type. Format also must be checked because there is a chance
527                    that a frame in old format was already queued before we set channel format
528                    to slinear so it will still be received by ast_read */
529                 if (inf->frametype == AST_FRAME_VOICE && inf->subclass.codec == AST_FORMAT_SLINEAR) {
530                         if (fax_rx(&fax, inf->data.ptr, inf->samples) < 0) {
531                                 /* I know fax_rx never returns errors. The check here is for good style only */
532                                 ast_log(LOG_WARNING, "fax_rx returned error\n");
533                                 res = -1;
534                                 break;
535                         }
536                         if (last_state != t30state->state) {
537                                 state_change = ast_tvnow();
538                                 last_state = t30state->state;
539                         }
540                 } else if ((inf->frametype == AST_FRAME_CONTROL) &&
541                            (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS)) {
542                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
543
544                         if (parameters->request_response == AST_T38_NEGOTIATED) {
545                                 /* T38 switchover completed */
546                                 s->t38parameters = *parameters;
547                                 ast_debug(1, "T38 negotiated, finishing audio loop\n");
548                                 res = 1;
549                                 break;
550                         } else if (parameters->request_response == AST_T38_REQUEST_NEGOTIATE) {
551                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
552                                 ast_debug(1, "T38 request received, accepting\n");
553                                 /* Complete T38 switchover */
554                                 ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
555                                 /* Do not break audio loop, wait until channel driver finally acks switchover
556                                  * with AST_T38_NEGOTIATED
557                                  */
558                         }
559                 }
560
561                 ast_frfree(inf);
562         }
563
564         ast_debug(1, "Loop finished, res=%d\n", res);
565
566         if (inf)
567                 ast_frfree(inf);
568
569         ast_deactivate_generator(s->chan);
570
571         /* If we are switching to T38, remove phase E handler. Otherwise it will be executed
572            by t30_terminate, display diagnostics and set status variables although no transmittion
573            has taken place yet. */
574         if (res > 0) {
575                 t30_set_phase_e_handler(t30state, NULL, NULL);
576         }
577
578         t30_terminate(t30state);
579         fax_release(&fax);
580
581 done:
582         if (original_write_fmt != AST_FORMAT_SLINEAR) {
583                 if (ast_set_write_format(s->chan, original_write_fmt) < 0)
584                         ast_log(LOG_WARNING, "Unable to restore write format on '%s'\n", s->chan->name);
585         }
586
587         if (original_read_fmt != AST_FORMAT_SLINEAR) {
588                 if (ast_set_read_format(s->chan, original_read_fmt) < 0)
589                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", s->chan->name);
590         }
591
592         return res;
593
594 }
595
596 static int transmit_t38(fax_session *s)
597 {
598         int res = 0;
599         t38_terminal_state_t t38;
600         struct ast_frame *inf = NULL;
601         int last_state = 0;
602         struct timeval now, start, state_change, last_frame;
603         t30_state_t *t30state;
604         t38_core_state_t *t38state;
605
606 #if SPANDSP_RELEASE_DATE >= 20080725
607         /* for spandsp shaphots 0.0.6 and higher */
608         t30state = &t38.t30;
609         t38state = &t38.t38_fe.t38;
610 #else
611         /* for spandsp releases 0.0.5 */
612         t30state = &t38.t30_state;
613         t38state = &t38.t38;
614 #endif
615
616         /* Initialize terminal */
617         memset(&t38, 0, sizeof(t38));
618         if (t38_terminal_init(&t38, s->caller_mode, t38_tx_packet_handler, s->chan) == NULL) {
619                 ast_log(LOG_WARNING, "Unable to start T.38 termination.\n");
620                 res = -1;
621                 goto disable_t38;
622         }
623
624         t38_set_max_datagram_size(t38state, s->t38parameters.max_ifp);
625
626         if (s->t38parameters.fill_bit_removal) {
627                 t38_set_fill_bit_removal(t38state, TRUE);
628         }
629         if (s->t38parameters.transcoding_mmr) {
630                 t38_set_mmr_transcoding(t38state, TRUE);
631         }
632         if (s->t38parameters.transcoding_jbig) {
633                 t38_set_jbig_transcoding(t38state, TRUE);
634         }
635
636         /* Setup logging */
637         set_logging(&t38.logging);
638         set_logging(&t30state->logging);
639         set_logging(&t38state->logging);
640
641         /* Configure terminal */
642         set_local_info(t30state, s);
643         set_file(t30state, s);
644         set_ecm(t30state, TRUE);
645
646         t30_set_phase_e_handler(t30state, phase_e_handler, s);
647
648         now = start = state_change = ast_tvnow();
649
650         while (!s->finished) {
651                 inf = NULL;
652
653                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
654                         ast_debug(1, "Error waiting for a frame\n");
655                         break;
656                 }
657
658                 last_frame = now;
659
660                 /* Watchdog */
661                 now = ast_tvnow();
662                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
663                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
664                         res = -1;
665                         break;
666                 }
667                 
668                 t38_terminal_send_timeout(&t38, ast_tvdiff_us(now, last_frame) / (1000000 / 8000));
669
670                 if (!res) {
671                         /* There was timeout waiting for a frame. Loop around and wait again */
672                         continue;
673                 }
674
675                 /* There is a frame available. Get it */
676                 res = 0;
677
678                 if (!(inf = ast_read(s->chan))) {
679                         ast_debug(1, "Channel hangup\n");
680                         res = -1;
681                         break;
682                 }
683
684                 ast_debug(10, "frame %d/%d, len=%d\n", inf->frametype, inf->subclass.integer, inf->datalen);
685
686                 if (inf->frametype == AST_FRAME_MODEM && inf->subclass.integer == AST_MODEM_T38) {
687                         t38_core_rx_ifp_packet(t38state, inf->data.ptr, inf->datalen, inf->seqno);
688                         if (last_state != t30state->state) {
689                                 state_change = ast_tvnow();
690                                 last_state = t30state->state;
691                         }
692                 } else if (inf->frametype == AST_FRAME_CONTROL && inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
693                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
694                         if (parameters->request_response == AST_T38_TERMINATED) {
695                                 ast_debug(1, "T38 down, finishing\n");
696                                 break;
697                         }
698                 }
699
700                 ast_frfree(inf);
701         }
702
703         ast_debug(1, "Loop finished, res=%d\n", res);
704
705         if (inf)
706                 ast_frfree(inf);
707
708         t30_terminate(t30state);
709         t38_terminal_release(&t38);
710
711 disable_t38:
712         /* if we are not the caller, it's our job to shut down the T.38
713          * session when the FAX transmisson is complete.
714          */
715         if ((s->caller_mode == FALSE) &&
716             (ast_channel_get_t38_state(s->chan) == T38_STATE_NEGOTIATED)) {
717                 struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
718
719                 if (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0) {
720                         /* wait up to five seconds for negotiation to complete */
721                         unsigned int timeout = 5000;
722                         int ms;
723                         
724                         ast_debug(1, "Shutting down T.38 on %s\n", s->chan->name);
725                         while (timeout > 0) {
726                                 ms = ast_waitfor(s->chan, 1000);
727                                 if (ms < 0) {
728                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", s->chan->name);
729                                         return -1;
730                                 }
731                                 if (!ms) {
732                                         /* nothing happened */
733                                         if (timeout > 0) {
734                                                 timeout -= 1000;
735                                                 continue;
736                                         } else {
737                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 shutdown.\n", s->chan->name);
738                                                 break;
739                                         }
740                                 }
741                                 if (!(inf = ast_read(s->chan))) {
742                                         return -1;
743                                 }
744                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
745                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
746                                     (inf->datalen == sizeof(t38_parameters))) {
747                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
748                                         
749                                         switch (parameters->request_response) {
750                                         case AST_T38_TERMINATED:
751                                                 ast_debug(1, "Shut down T.38 on %s\n", s->chan->name);
752                                                 break;
753                                         case AST_T38_REFUSED:
754                                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", s->chan->name);
755                                                 break;
756                                         default:
757                                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", s->chan->name);
758                                                 break;
759                                         }
760                                         ast_frfree(inf);
761                                         break;
762                                 }
763                                 ast_frfree(inf);
764                         }
765                 }
766         }
767
768         return res;
769 }
770
771 static int transmit(fax_session *s)
772 {
773         int res = 0;
774
775         /* Clear all channel variables which to be set by the application.
776            Pre-set status to error so in case of any problems we can just leave */
777         pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "FAILED"); 
778         pbx_builtin_setvar_helper(s->chan, "FAXERROR", "Channel problems"); 
779
780         pbx_builtin_setvar_helper(s->chan, "FAXMODE", NULL);
781         pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", NULL);
782         pbx_builtin_setvar_helper(s->chan, "FAXPAGES", "0");
783         pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", NULL);
784         pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", NULL); 
785
786         if (s->chan->_state != AST_STATE_UP) {
787                 /* Shouldn't need this, but checking to see if channel is already answered
788                  * Theoretically asterisk should already have answered before running the app */
789                 res = ast_answer(s->chan);
790                 if (res) {
791                         ast_log(LOG_WARNING, "Could not answer channel '%s'\n", s->chan->name);
792                         return res;
793                 }
794         }
795
796         s->t38state = ast_channel_get_t38_state(s->chan);
797         if (s->t38state != T38_STATE_NEGOTIATED) {
798                 /* T38 is not negotiated on the channel yet. First start regular transmission. If it switches to T38, follow */ 
799                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "audio"); 
800                 res = transmit_audio(s);
801                 if (res > 0) {
802                         /* transmit_audio reports switchover to T38. Update t38state */
803                         s->t38state = ast_channel_get_t38_state(s->chan);
804                         if (s->t38state != T38_STATE_NEGOTIATED) {
805                                 ast_log(LOG_ERROR, "Audio loop reports T38 switchover but t38state != T38_STATE_NEGOTIATED\n");
806                         }
807                 }
808         }
809
810         if (s->t38state == T38_STATE_NEGOTIATED) {
811                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "T38"); 
812                 res = transmit_t38(s);
813         }
814
815         if (res) {
816                 ast_log(LOG_WARNING, "Transmission error\n");
817                 res = -1;
818         } else if (s->finished < 0) {
819                 ast_log(LOG_WARNING, "Transmission failed\n");
820         } else if (s->finished > 0) {
821                 ast_debug(1, "Transmission finished Ok\n");
822         }
823
824         return res;
825 }
826
827 /* === Application functions === */
828
829 static int sndfax_exec(struct ast_channel *chan, const char *data)
830 {
831         int res = 0;
832         char *parse;
833         fax_session session = { 0, };
834         char restore_digit_detect = 0;
835
836         AST_DECLARE_APP_ARGS(args,
837                 AST_APP_ARG(file_name);
838                 AST_APP_ARG(options);
839         );
840
841         if (chan == NULL) {
842                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
843                 return -1;
844         }
845
846         /* The next few lines of code parse out the filename and header from the input string */
847         if (ast_strlen_zero(data)) {
848                 /* No data implies no filename or anything is present */
849                 ast_log(LOG_ERROR, "SendFAX requires an argument (filename)\n");
850                 return -1;
851         }
852
853         parse = ast_strdupa(data);
854         AST_STANDARD_APP_ARGS(args, parse);
855         
856         session.caller_mode = TRUE;
857
858         if (args.options) {
859                 if (strchr(args.options, 'a'))
860                         session.caller_mode = FALSE;
861         }
862
863         /* Done parsing */
864         session.direction = 1;
865         session.file_name = args.file_name;
866         session.chan = chan;
867         session.finished = 0;
868
869         /* get current digit detection mode, then disable digit detection if enabled */
870         {
871                 int dummy = sizeof(restore_digit_detect);
872
873                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
874         }
875
876         if (restore_digit_detect) {
877                 char new_digit_detect = 0;
878
879                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
880         }
881
882         /* disable FAX tone detection if enabled */
883         {
884                 char new_fax_detect = 0;
885
886                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
887         }
888
889         res = transmit(&session);
890
891         if (restore_digit_detect) {
892                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
893         }
894
895         return res;
896 }
897
898 static int rcvfax_exec(struct ast_channel *chan, const char *data)
899 {
900         int res = 0;
901         char *parse;
902         fax_session session;
903         char restore_digit_detect = 0;
904
905         AST_DECLARE_APP_ARGS(args,
906                 AST_APP_ARG(file_name);
907                 AST_APP_ARG(options);
908         );
909
910         if (chan == NULL) {
911                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
912                 return -1;
913         }
914
915         /* The next few lines of code parse out the filename and header from the input string */
916         if (ast_strlen_zero(data)) {
917                 /* No data implies no filename or anything is present */
918                 ast_log(LOG_ERROR, "ReceiveFAX requires an argument (filename)\n");
919                 return -1;
920         }
921
922         parse = ast_strdupa(data);
923         AST_STANDARD_APP_ARGS(args, parse);
924         
925         session.caller_mode = FALSE;
926
927         if (args.options) {
928                 if (strchr(args.options, 'c'))
929                         session.caller_mode = TRUE;
930         }
931
932         /* Done parsing */
933         session.direction = 0;
934         session.file_name = args.file_name;
935         session.chan = chan;
936         session.finished = 0;
937
938         /* get current digit detection mode, then disable digit detection if enabled */
939         {
940                 int dummy = sizeof(restore_digit_detect);
941
942                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
943         }
944
945         if (restore_digit_detect) {
946                 char new_digit_detect = 0;
947
948                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
949         }
950
951         /* disable FAX tone detection if enabled */
952         {
953                 char new_fax_detect = 0;
954
955                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
956         }
957
958         res = transmit(&session);
959
960         if (restore_digit_detect) {
961                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
962         }
963
964         return res;
965 }
966
967 static int unload_module(void)
968 {
969         int res;
970
971         res = ast_unregister_application(app_sndfax_name);      
972         res |= ast_unregister_application(app_rcvfax_name);     
973
974         return res;
975 }
976
977 static int load_module(void)
978 {
979         int res ;
980
981         res = ast_register_application_xml(app_sndfax_name, sndfax_exec);
982         res |= ast_register_application_xml(app_rcvfax_name, rcvfax_exec);
983
984         /* The default SPAN message handler prints to stderr. It is something we do not want */
985         span_set_message_handler(NULL);
986
987         return res;
988 }
989
990
991 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Simple FAX Application",
992                 .load = load_module,
993                 .unload = unload_module,
994                 );
995
996