6a33fe7a3040087a0f9b460822bbf7360487a2d9
[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_9600,
374                                                              .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
375                                                              .fill_bit_removal = 1,
376                                                              .transcoding_mmr = 1,
377                                                              .transcoding_jbig = 1,
378         };
379
380         /* if in called party mode, try to use T.38 */
381         if (s->caller_mode == FALSE) {
382                 /* check if we are already in T.38 mode (unlikely), or if we can request
383                  * a switch... if so, request it now and wait for the result, rather
384                  * than starting an audio FAX session that will have to be cancelled
385                  */
386                 if ((t38_state = ast_channel_get_t38_state(s->chan)) == T38_STATE_NEGOTIATED) {
387                         return 1;
388                 } else if ((t38_state != T38_STATE_UNAVAILABLE) &&
389                            (t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE,
390                             (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0))) {
391                         /* wait up to five seconds for negotiation to complete */
392                         unsigned int timeout = 5000;
393                         int ms;
394                         
395                         ast_debug(1, "Negotiating T.38 for receive on %s\n", s->chan->name);
396                         while (timeout > 0) {
397                                 ms = ast_waitfor(s->chan, 1000);
398                                 if (ms < 0) {
399                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", s->chan->name);
400                                         return -1;
401                                 }
402                                 if (!ms) {
403                                         /* nothing happened */
404                                         if (timeout > 0) {
405                                                 timeout -= 1000;
406                                                 continue;
407                                         } else {
408                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", s->chan->name);
409                                                 break;
410                                         }
411                                 }
412                                 if (!(inf = ast_read(s->chan))) {
413                                         return -1;
414                                 }
415                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
416                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
417                                     (inf->datalen == sizeof(t38_parameters))) {
418                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
419                                         
420                                         switch (parameters->request_response) {
421                                         case AST_T38_NEGOTIATED:
422                                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", s->chan->name);
423                                                 res = 1;
424                                                 break;
425                                         case AST_T38_REFUSED:
426                                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", s->chan->name);
427                                                 break;
428                                         default:
429                                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", s->chan->name);
430                                                 break;
431                                         }
432                                         ast_frfree(inf);
433                                         if (res == 1) {
434                                                 return 1;
435                                         } else {
436                                                 break;
437                                         }
438                                 }
439                                 ast_frfree(inf);
440                         }
441                 }
442         }
443
444 #if SPANDSP_RELEASE_DATE >= 20080725
445         /* for spandsp shaphots 0.0.6 and higher */
446         t30state = &fax.t30;
447 #else
448         /* for spandsp release 0.0.5 */
449         t30state = &fax.t30_state;
450 #endif
451
452         original_read_fmt = s->chan->readformat;
453         if (original_read_fmt != AST_FORMAT_SLINEAR) {
454                 res = ast_set_read_format(s->chan, AST_FORMAT_SLINEAR);
455                 if (res < 0) {
456                         ast_log(LOG_WARNING, "Unable to set to linear read mode, giving up\n");
457                         goto done;
458                 }
459         }
460
461         original_write_fmt = s->chan->writeformat;
462         if (original_write_fmt != AST_FORMAT_SLINEAR) {
463                 res = ast_set_write_format(s->chan, AST_FORMAT_SLINEAR);
464                 if (res < 0) {
465                         ast_log(LOG_WARNING, "Unable to set to linear write mode, giving up\n");
466                         goto done;
467                 }
468         }
469
470         /* Initialize T30 terminal */
471         fax_init(&fax, s->caller_mode);
472
473         /* Setup logging */
474         set_logging(&fax.logging);
475         set_logging(&t30state->logging);
476
477         /* Configure terminal */
478         set_local_info(t30state, s);
479         set_file(t30state, s);
480         set_ecm(t30state, TRUE);
481
482         fax_set_transmit_on_idle(&fax, TRUE);
483
484         t30_set_phase_e_handler(t30state, phase_e_handler, s);
485
486         start = state_change = ast_tvnow();
487
488         ast_activate_generator(s->chan, &generator, &fax);
489
490         while (!s->finished) {
491                 inf = NULL;
492
493                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
494                         ast_debug(1, "Error waiting for a frame\n");
495                         break;
496                 }
497
498                 /* Watchdog */
499                 now = ast_tvnow();
500                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
501                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
502                         res = -1;
503                         break;
504                 }
505
506                 if (!res) {
507                         /* There was timeout waiting for a frame. Loop around and wait again */
508                         continue;
509                 }
510
511                 /* There is a frame available. Get it */
512                 res = 0;
513
514                 if (!(inf = ast_read(s->chan))) {
515                         ast_debug(1, "Channel hangup\n");
516                         res = -1;
517                         break;
518                 }
519
520                 ast_debug(10, "frame %d/%llu, len=%d\n", inf->frametype, (unsigned long long) inf->subclass.codec, inf->datalen);
521
522                 /* Check the frame type. Format also must be checked because there is a chance
523                    that a frame in old format was already queued before we set channel format
524                    to slinear so it will still be received by ast_read */
525                 if (inf->frametype == AST_FRAME_VOICE && inf->subclass.codec == AST_FORMAT_SLINEAR) {
526                         if (fax_rx(&fax, inf->data.ptr, inf->samples) < 0) {
527                                 /* I know fax_rx never returns errors. The check here is for good style only */
528                                 ast_log(LOG_WARNING, "fax_rx returned error\n");
529                                 res = -1;
530                                 break;
531                         }
532                         if (last_state != t30state->state) {
533                                 state_change = ast_tvnow();
534                                 last_state = t30state->state;
535                         }
536                 } else if ((inf->frametype == AST_FRAME_CONTROL) &&
537                            (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS)) {
538                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
539
540                         if (parameters->request_response == AST_T38_NEGOTIATED) {
541                                 /* T38 switchover completed */
542                                 s->t38parameters = *parameters;
543                                 ast_debug(1, "T38 negotiated, finishing audio loop\n");
544                                 res = 1;
545                                 break;
546                         } else if (parameters->request_response == AST_T38_REQUEST_NEGOTIATE) {
547                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
548                                 ast_debug(1, "T38 request received, accepting\n");
549                                 /* Complete T38 switchover */
550                                 ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
551                                 /* Do not break audio loop, wait until channel driver finally acks switchover
552                                  * with AST_T38_NEGOTIATED
553                                  */
554                         }
555                 }
556
557                 ast_frfree(inf);
558         }
559
560         ast_debug(1, "Loop finished, res=%d\n", res);
561
562         if (inf)
563                 ast_frfree(inf);
564
565         ast_deactivate_generator(s->chan);
566
567         /* If we are switching to T38, remove phase E handler. Otherwise it will be executed
568            by t30_terminate, display diagnostics and set status variables although no transmittion
569            has taken place yet. */
570         if (res > 0) {
571                 t30_set_phase_e_handler(t30state, NULL, NULL);
572         }
573
574         t30_terminate(t30state);
575         fax_release(&fax);
576
577 done:
578         if (original_write_fmt != AST_FORMAT_SLINEAR) {
579                 if (ast_set_write_format(s->chan, original_write_fmt) < 0)
580                         ast_log(LOG_WARNING, "Unable to restore write format on '%s'\n", s->chan->name);
581         }
582
583         if (original_read_fmt != AST_FORMAT_SLINEAR) {
584                 if (ast_set_read_format(s->chan, original_read_fmt) < 0)
585                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", s->chan->name);
586         }
587
588         return res;
589
590 }
591
592 static int transmit_t38(fax_session *s)
593 {
594         int res = 0;
595         t38_terminal_state_t t38;
596         struct ast_frame *inf = NULL;
597         int last_state = 0;
598         struct timeval now, start, state_change, last_frame;
599         t30_state_t *t30state;
600         t38_core_state_t *t38state;
601         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
602
603 #if SPANDSP_RELEASE_DATE >= 20080725
604         /* for spandsp shaphots 0.0.6 and higher */
605         t30state = &t38.t30;
606         t38state = &t38.t38_fe.t38;
607 #else
608         /* for spandsp releases 0.0.5 */
609         t30state = &t38.t30_state;
610         t38state = &t38.t38;
611 #endif
612
613         /* Initialize terminal */
614         memset(&t38, 0, sizeof(t38));
615         if (t38_terminal_init(&t38, s->caller_mode, t38_tx_packet_handler, s->chan) == NULL) {
616                 ast_log(LOG_WARNING, "Unable to start T.38 termination.\n");
617                 res = -1;
618                 goto disable_t38;
619         }
620
621         t38_set_max_datagram_size(t38state, s->t38parameters.max_ifp);
622
623         if (s->t38parameters.fill_bit_removal) {
624                 t38_set_fill_bit_removal(t38state, TRUE);
625         }
626         if (s->t38parameters.transcoding_mmr) {
627                 t38_set_mmr_transcoding(t38state, TRUE);
628         }
629         if (s->t38parameters.transcoding_jbig) {
630                 t38_set_jbig_transcoding(t38state, TRUE);
631         }
632
633         /* Setup logging */
634         set_logging(&t38.logging);
635         set_logging(&t30state->logging);
636         set_logging(&t38state->logging);
637
638         /* Configure terminal */
639         set_local_info(t30state, s);
640         set_file(t30state, s);
641         set_ecm(t30state, TRUE);
642
643         t30_set_phase_e_handler(t30state, phase_e_handler, s);
644
645         now = start = state_change = ast_tvnow();
646
647         while (!s->finished) {
648                 inf = NULL;
649
650                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
651                         ast_debug(1, "Error waiting for a frame\n");
652                         break;
653                 }
654
655                 last_frame = now;
656
657                 /* Watchdog */
658                 now = ast_tvnow();
659                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
660                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
661                         res = -1;
662                         break;
663                 }
664                 
665                 t38_terminal_send_timeout(&t38, ast_tvdiff_us(now, last_frame) / (1000000 / 8000));
666
667                 if (!res) {
668                         /* There was timeout waiting for a frame. Loop around and wait again */
669                         continue;
670                 }
671
672                 /* There is a frame available. Get it */
673                 res = 0;
674
675                 if (!(inf = ast_read(s->chan))) {
676                         ast_debug(1, "Channel hangup\n");
677                         res = -1;
678                         break;
679                 }
680
681                 ast_debug(10, "frame %d/%d, len=%d\n", inf->frametype, inf->subclass.integer, inf->datalen);
682
683                 if (inf->frametype == AST_FRAME_MODEM && inf->subclass.integer == AST_MODEM_T38) {
684                         t38_core_rx_ifp_packet(t38state, inf->data.ptr, inf->datalen, inf->seqno);
685                         if (last_state != t30state->state) {
686                                 state_change = ast_tvnow();
687                                 last_state = t30state->state;
688                         }
689                 } else if (inf->frametype == AST_FRAME_CONTROL && inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
690                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
691                         if (parameters->request_response == AST_T38_TERMINATED) {
692                                 ast_debug(1, "T38 down, finishing\n");
693                                 break;
694                         }
695                 }
696
697                 ast_frfree(inf);
698         }
699
700         ast_debug(1, "Loop finished, res=%d\n", res);
701
702         if (inf)
703                 ast_frfree(inf);
704
705         t30_terminate(t30state);
706         t38_terminal_release(&t38);
707
708 disable_t38:
709         /* if we are not the caller, it's our job to shut down the T.38
710          * session when the FAX transmisson is complete.
711          */
712         if ((s->caller_mode == FALSE) &&
713             (ast_channel_get_t38_state(s->chan) == T38_STATE_NEGOTIATED)) {
714                 if (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0) {
715                         /* wait up to five seconds for negotiation to complete */
716                         unsigned int timeout = 5000;
717                         int ms;
718                         
719                         ast_debug(1, "Shutting down T.38 on %s\n", s->chan->name);
720                         while (timeout > 0) {
721                                 ms = ast_waitfor(s->chan, 1000);
722                                 if (ms < 0) {
723                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", s->chan->name);
724                                         return -1;
725                                 }
726                                 if (!ms) {
727                                         /* nothing happened */
728                                         if (timeout > 0) {
729                                                 timeout -= 1000;
730                                                 continue;
731                                         } else {
732                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 shutdown.\n", s->chan->name);
733                                                 break;
734                                         }
735                                 }
736                                 if (!(inf = ast_read(s->chan))) {
737                                         return -1;
738                                 }
739                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
740                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
741                                     (inf->datalen == sizeof(t38_parameters))) {
742                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
743                                         
744                                         switch (parameters->request_response) {
745                                         case AST_T38_NEGOTIATED:
746                                                 ast_debug(1, "Shut down T.38 on %s\n", s->chan->name);
747                                                 break;
748                                         case AST_T38_REFUSED:
749                                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", s->chan->name);
750                                                 break;
751                                         default:
752                                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", s->chan->name);
753                                                 break;
754                                         }
755                                         ast_frfree(inf);
756                                         break;
757                                 }
758                                 ast_frfree(inf);
759                         }
760                 }
761         }
762
763         return res;
764 }
765
766 static int transmit(fax_session *s)
767 {
768         int res = 0;
769
770         /* Clear all channel variables which to be set by the application.
771            Pre-set status to error so in case of any problems we can just leave */
772         pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "FAILED"); 
773         pbx_builtin_setvar_helper(s->chan, "FAXERROR", "Channel problems"); 
774
775         pbx_builtin_setvar_helper(s->chan, "FAXMODE", NULL);
776         pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", NULL);
777         pbx_builtin_setvar_helper(s->chan, "FAXPAGES", "0");
778         pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", NULL);
779         pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", NULL); 
780
781         if (s->chan->_state != AST_STATE_UP) {
782                 /* Shouldn't need this, but checking to see if channel is already answered
783                  * Theoretically asterisk should already have answered before running the app */
784                 res = ast_answer(s->chan);
785                 if (res) {
786                         ast_log(LOG_WARNING, "Could not answer channel '%s'\n", s->chan->name);
787                         return res;
788                 }
789         }
790
791         s->t38state = ast_channel_get_t38_state(s->chan);
792         if (s->t38state != T38_STATE_NEGOTIATED) {
793                 /* T38 is not negotiated on the channel yet. First start regular transmission. If it switches to T38, follow */ 
794                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "audio"); 
795                 res = transmit_audio(s);
796                 if (res > 0) {
797                         /* transmit_audio reports switchover to T38. Update t38state */
798                         s->t38state = ast_channel_get_t38_state(s->chan);
799                         if (s->t38state != T38_STATE_NEGOTIATED) {
800                                 ast_log(LOG_ERROR, "Audio loop reports T38 switchover but t38state != T38_STATE_NEGOTIATED\n");
801                         }
802                 }
803         }
804
805         if (s->t38state == T38_STATE_NEGOTIATED) {
806                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "T38"); 
807                 res = transmit_t38(s);
808         }
809
810         if (res) {
811                 ast_log(LOG_WARNING, "Transmission error\n");
812                 res = -1;
813         } else if (s->finished < 0) {
814                 ast_log(LOG_WARNING, "Transmission failed\n");
815         } else if (s->finished > 0) {
816                 ast_debug(1, "Transmission finished Ok\n");
817         }
818
819         return res;
820 }
821
822 /* === Application functions === */
823
824 static int sndfax_exec(struct ast_channel *chan, const char *data)
825 {
826         int res = 0;
827         char *parse;
828         fax_session session = { 0, };
829         char restore_digit_detect = 0;
830
831         AST_DECLARE_APP_ARGS(args,
832                 AST_APP_ARG(file_name);
833                 AST_APP_ARG(options);
834         );
835
836         if (chan == NULL) {
837                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
838                 return -1;
839         }
840
841         /* The next few lines of code parse out the filename and header from the input string */
842         if (ast_strlen_zero(data)) {
843                 /* No data implies no filename or anything is present */
844                 ast_log(LOG_ERROR, "SendFAX requires an argument (filename)\n");
845                 return -1;
846         }
847
848         parse = ast_strdupa(data);
849         AST_STANDARD_APP_ARGS(args, parse);
850         
851         session.caller_mode = TRUE;
852
853         if (args.options) {
854                 if (strchr(args.options, 'a'))
855                         session.caller_mode = FALSE;
856         }
857
858         /* Done parsing */
859         session.direction = 1;
860         session.file_name = args.file_name;
861         session.chan = chan;
862         session.finished = 0;
863
864         /* get current digit detection mode, then disable digit detection if enabled */
865         {
866                 int dummy = sizeof(restore_digit_detect);
867
868                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
869         }
870
871         if (restore_digit_detect) {
872                 char new_digit_detect = 0;
873
874                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
875         }
876
877         /* disable FAX tone detection if enabled */
878         {
879                 char new_fax_detect = 0;
880
881                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
882         }
883
884         res = transmit(&session);
885
886         if (restore_digit_detect) {
887                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
888         }
889
890         return res;
891 }
892
893 static int rcvfax_exec(struct ast_channel *chan, const char *data)
894 {
895         int res = 0;
896         char *parse;
897         fax_session session;
898         char restore_digit_detect = 0;
899
900         AST_DECLARE_APP_ARGS(args,
901                 AST_APP_ARG(file_name);
902                 AST_APP_ARG(options);
903         );
904
905         if (chan == NULL) {
906                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
907                 return -1;
908         }
909
910         /* The next few lines of code parse out the filename and header from the input string */
911         if (ast_strlen_zero(data)) {
912                 /* No data implies no filename or anything is present */
913                 ast_log(LOG_ERROR, "ReceiveFAX requires an argument (filename)\n");
914                 return -1;
915         }
916
917         parse = ast_strdupa(data);
918         AST_STANDARD_APP_ARGS(args, parse);
919         
920         session.caller_mode = FALSE;
921
922         if (args.options) {
923                 if (strchr(args.options, 'c'))
924                         session.caller_mode = TRUE;
925         }
926
927         /* Done parsing */
928         session.direction = 0;
929         session.file_name = args.file_name;
930         session.chan = chan;
931         session.finished = 0;
932
933         /* get current digit detection mode, then disable digit detection if enabled */
934         {
935                 int dummy = sizeof(restore_digit_detect);
936
937                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
938         }
939
940         if (restore_digit_detect) {
941                 char new_digit_detect = 0;
942
943                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
944         }
945
946         /* disable FAX tone detection if enabled */
947         {
948                 char new_fax_detect = 0;
949
950                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
951         }
952
953         res = transmit(&session);
954
955         if (restore_digit_detect) {
956                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
957         }
958
959         return res;
960 }
961
962 static int unload_module(void)
963 {
964         int res;
965
966         res = ast_unregister_application(app_sndfax_name);      
967         res |= ast_unregister_application(app_rcvfax_name);     
968
969         return res;
970 }
971
972 static int load_module(void)
973 {
974         int res ;
975
976         res = ast_register_application_xml(app_sndfax_name, sndfax_exec);
977         res |= ast_register_application_xml(app_rcvfax_name, rcvfax_exec);
978
979         /* The default SPAN message handler prints to stderr. It is something we do not want */
980         span_set_message_handler(NULL);
981
982         return res;
983 }
984
985
986 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Simple FAX Application",
987                 .load = load_module,
988                 .unload = unload_module,
989                 );
990
991