From 01f48a3296c292f50adc4e00a36f164c0581547d Mon Sep 17 00:00:00 2001
From: rogerdpack <rogerpack2005@gmail.com>
Date: Wed, 24 Jun 2015 23:26:22 -0600
Subject: [PATCH 1/2] windows: respond to logoff and ctrl+break messages

Signed-off-by: rogerdpack <rogerpack2005@gmail.com>
---
 configure |  2 ++
 ffmpeg.c  | 37 ++++++++++++++++++++++++++++++++++++-
 2 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/configure b/configure
index 0620936..2dc6df8 100755
--- a/configure
+++ b/configure
@@ -1787,6 +1787,7 @@ SYSTEM_FUNCS="
     pthread_cancel
     sched_getaffinity
     SetConsoleTextAttribute
+    SetConsoleCtrlHandler
     setmode
     setrlimit
     Sleep
@@ -4987,6 +4988,7 @@ check_func_headers windows.h GetSystemTimeAsFileTime
 check_func_headers windows.h MapViewOfFile
 check_func_headers windows.h PeekNamedPipe
 check_func_headers windows.h SetConsoleTextAttribute
+check_func_headers windows.h SetConsoleCtrlHandler
 check_func_headers windows.h Sleep
 check_func_headers windows.h VirtualAlloc
 check_struct windows.h "CONDITION_VARIABLE" Ptr
diff --git a/ffmpeg.c b/ffmpeg.c
index f502998..9858bb8 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -22,7 +22,6 @@
  * @file
  * multimedia converter based on the FFmpeg libraries
  */
-
 #include "config.h"
 #include <ctype.h>
 #include <string.h>
@@ -79,6 +78,10 @@
 #include <windows.h>
 #include <psapi.h>
 #endif
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+#include <windows.h>
+#endif
+
 
 #if HAVE_SYS_SELECT_H
 #include <sys/select.h>
@@ -325,6 +328,35 @@ sigterm_handler(int sig)
         exit(123);
 }
 
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
+{
+    av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
+
+    switch (fdwCtrlType)
+    {
+    case CTRL_C_EVENT:
+    case CTRL_BREAK_EVENT:
+        sigterm_handler(SIGINT);
+        return TRUE;
+
+    case CTRL_CLOSE_EVENT:
+    case CTRL_LOGOFF_EVENT:
+    case CTRL_SHUTDOWN_EVENT:
+        sigterm_handler(SIGTERM);
+        /* Basically, with these events, when we return from this method this
+           process is hard terminated, so stall as long as we can [we have up to 5 seconds]
+           to try and let the main thread cleanup and gracefully terminate. */
+        Sleep(1000000);
+        return TRUE;
+
+    default:
+        av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
+        return FALSE;
+    }
+}
+#endif
+
 void term_init(void)
 {
 #if HAVE_TERMIOS_H
@@ -358,6 +390,9 @@ void term_init(void)
 #ifdef SIGXCPU
     signal(SIGXCPU, sigterm_handler);
 #endif
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+    SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
+#endif
 }
 
 /* read a key without blocking */
-- 
1.9.5.msysgit.0

