diff -u libwavesync-orig/chunk_player.py libwavesync/chunk_player.py
--- libwavesync-orig/chunk_player.py	2020-09-04 02:54:37.103466272 +0200
+++ libwavesync/chunk_player.py	2020-09-11 16:11:45.312535851 +0200
@@ -2,13 +2,60 @@
 import random
 from time import time
 from libwavesync import time_machine
+import pyaudio
+
+from collections import deque
+from time import sleep
+
+
+#PLAY_CALLBACK=True
+
+QUEUE_MAX=12
+q=deque(maxlen=QUEUE_MAX)
+
+# critical for callback variety; recived packet size must be the same as in initialization call
+glob_chunk_size=367*4
+
+glob_stream_break=0
+
+
+def snd_callback(in_data, frame_count, time_info, status):
+#        print("callback called",status,buf_chunk_wait,pyaudio.paContinue, pyaudio.paComplete,len(buf_chunk))
+        # if queue is empty, return artificial silence
+
+        if glob_stream_break > 0:
+            return (b'\x00'*glob_chunk_size,pyaudio.paComplete)
+        urun=0
+        while len(q)==0:
+                if glob_stream_break > 0:
+                    return (b'\x00'*glob_chunk_size, pyaudio.paComplete)
+                sleep(0.010)
+                urun+=1
+                if urun == 3 and len(q)==0: print('queue underrun')
+
+        #if len(q)==0: return (b'\x00'*glob_chunk_size,pyaudio.paContinue)
+        # dirty hack: help empty overly long queue by dropping extra data
+        if len(q)>12:
+            print('qdrop')
+            _=q.popleft()
+        return (q.popleft(), pyaudio.paContinue)
+
 
 
 class ChunkPlayer:
     "Play received audio and keep sync"
 
+
+
+
+
     def __init__(self, chunk_queue, receiver, tolerance_ms,
-                 buffer_size, device_index):
+                 buffer_size, device_index, use_callback):
+
+        # playback mode
+        #global PLAY_CALLBACK
+        self.PLAY_CALLBACK=use_callback
+
         # Our data source
         self.chunk_queue = chunk_queue
 
@@ -45,6 +92,7 @@
         self.frame_size = None
         self.chunk_frames = None
 
+
     def clear_state(self):
         "Clear player queue"
         self.silence_to_insert = 0
@@ -78,8 +126,15 @@
 
         # Open stream
         cfg = self.audio_config
+        global glob_chunk_size
+        glob_chunk_size=cfg.chunk_size
 
-        frames_per_buffer = self.buffer_size
+#       for callback: MUST BE ACTUALLY WORKING NUMBER - otherwise the stream will fail with both stream.is_active() and stream.is_stopped() as false
+        if self.PLAY_CALLBACK:
+            frames_per_buffer = int(cfg.chunk_size/cfg.frame_size)
+        else:
+            frames_per_buffer = self.buffer_size
+            #AudioConfig 44100Hz 16bits 2ch latency=4000ms sink=-250ms size chunk=1468 frame=4
 
         if self.device_index == -1:
             # We are tested. Don't open stream, but calculate chunk_frames.
@@ -90,6 +145,7 @@
             if self.device_index is None:
                 config = self.pyaudio.get_host_api_info_by_index(0)
                 device_index = config['defaultOutputDevice']
+                print('CONFIG:',config)
                 print("Using default output device index", device_index)
             else:
                 device_index = self.device_index
@@ -99,13 +155,24 @@
                 if cfg.sample == 24
                 else pyaudio.paInt16
             )
-            stream = self.pyaudio.open(output=True,
-                                       channels=cfg.channels,
-                                       rate=cfg.rate,
-                                       format=audio_format,
-                                       frames_per_buffer=frames_per_buffer,
-                                       output_device_index=device_index)
+
+            if self.PLAY_CALLBACK:
+                stream = self.pyaudio.open(output=True,
+                                           channels=cfg.channels,
+                                           rate=cfg.rate,
+                                           format=audio_format,
+                                           frames_per_buffer=frames_per_buffer,
+                                           output_device_index=device_index,
+                                           stream_callback=snd_callback)
+            else:
+                stream = self.pyaudio.open(output=True,
+                                           channels=cfg.channels,
+                                           rate=cfg.rate,
+                                           format=audio_format,
+                                           frames_per_buffer=frames_per_buffer,
+                                           output_device_index=device_index)
             self.stream = stream
+            print('audio config:',self.audio_config)
 
         self.chunk_frames = self.audio_config.chunk_size / cfg.frame_size
 
@@ -116,6 +183,7 @@
         self.stream = None
 
 
+
     async def chunk_player(self):
         "Reads asynchronously chunks from the list and plays them"
 
@@ -124,17 +192,51 @@
         # Chunk/s stat
         recent_start = time()
         recent = 0
+        mark=0
 
         mid_tolerance_s = self.tolerance_ms / 2 / 1000
         one_ms = 1/1000.0
+        if self.PLAY_CALLBACK:
+            wait_if_greater=one_ms*10
+        else:
+            wait_if_greater=one_ms
 
-        max_delay = 5
+#        max_delay = 5
+        max_delay = 85
 
-        while not self.stop:
+        global glob_stream_break
+        # get initial NTP sync, thrice to be more accurate
+        time_machine.ntp_getoffset()
+        time_machine.ntp_getoffset()
+        time_machine.ntp_runtimer()
+
+        try:
+          while not self.stop:
             if not self.chunk_queue.chunk_list:
 
                 if self.audio_config is not None:
                     print("Queue empty - waiting")
+                    # reopen stream - cheat for resyncing the audio queue on termux/android; will it work?
+                    if self.PLAY_CALLBACK:
+                        q.clear()
+                        print('RESYNC - stream reopen');
+                        glob_stream_break=1
+                        await asyncio.sleep(0.030)
+                        self.stream.stop_stream()
+                        print('RESYNC - stream wait');
+                        await asyncio.sleep(0.005)
+                        print('RESYNC - stream restarting');
+                        glob_stream_break=0
+                        self.stream.start_stream()
+                        print('RESYNC - stream restarted');
+
+#                    if self.stream:
+#                        print('closing audio device')
+#                        self._close_stream()
+#                        print('closed audio device')
+#                        await asyncio.sleep(10)
+#                    print('opening audio device')
+#                    self._open_stream()
 
                 self.chunk_queue.chunk_available.clear()
                 await self.chunk_queue.chunk_available.wait()
@@ -146,6 +248,10 @@
                     print("Got stream flowing. q_len=%d" % len(self.chunk_queue.chunk_list))
                 continue
 
+
+#            for i in self.chunk_queue.chunk_list:
+#                if i[0]==1: print(i[1][0])
+
             cmd, item = self.chunk_queue.chunk_list.popleft()
 
             if cmd == self.chunk_queue.CMD_CFG:
@@ -155,9 +261,12 @@
                 if self.stream:
                     self._close_stream()
                 self._open_stream()
-                # Calculate maximum sensible delay in given configuration
+                # Calculate maximum sensible delay in given configuration, in seconds
                 max_delay = (2000 + self.audio_config.sink_latency_ms +
                              self.audio_config.latency_ms) / 1000
+                #print("max_delay calculated:",max_delay) # Shad's mod
+                #max_delay=60 # Shad's mod for testing on lousy-sync android
+                #max_delay=15 # Shad's mod for testing on lousy-sync android
                 print("Assuming maximum chunk delay of %.2fms in this setup" % (max_delay * 1000))
                 continue
             elif cmd == self.chunk_queue.CMD_DROPS:
@@ -175,8 +284,20 @@
                 # No output, no playing.
                 continue
 
+            # for packet time difference
+            oldmark=mark
             mark, chunk = item
-            desired_time = mark - self.audio_config.sink_latency_ms
+
+            # check to make packets with wrong timing visible; times valid for 44kHz/16bit/2ch
+            if mark-oldmark < 0.0075 or mark-oldmark > 0.0095:
+                print('out-of-spec td: {:.4f}'.format(mark-oldmark))
+
+            # throw out misordered packet
+            if mark < oldmark:
+                print('bad timing ordering, packet skipped')
+                continue
+
+            desired_time = mark - (self.audio_config.sink_latency_ms/1000.0)
 
             # 0) We got the next chunk to be played
             now = time_machine.now()
@@ -212,28 +333,56 @@
                 continue
 
             # If chunk is in the future - wait until it's within the tolerance
-            elif delay > one_ms:
-                to_wait = max(one_ms, delay - one_ms)
-                await asyncio.sleep(to_wait)
+            else:
+                desired_time=desired_time-0.003*len(q)
+                delay = desired_time - now
+                if delay > one_ms:
+                    to_wait = max(one_ms, delay - one_ms)
+                    await asyncio.sleep(to_wait)
 
 
             # Wait until we can write chunk into output buffer. This might
             # delay us too much - the probabilistic dropping mechanism will kick
             # in.
             times = 0
-            while True:
-                buffer_space = self.stream.get_write_available()
-                if buffer_space < self.chunk_frames:
-                    self.stat_output_delays += 1
-                    await asyncio.sleep(one_ms)
-                    times += 1
-                    if times > 200:
-                        print("Hey, the output is STUCK!")
-                        await asyncio.sleep(1)
-                        break
-                    continue
-                self.stream.write(chunk)
-                break
+            buffer_space = 0
+            if not self.PLAY_CALLBACK:
+              while True:
+                # this is for some reason always zero on android/termux!!!
+                    buffer_space = self.stream.get_write_available()
+                    if buffer_space < self.chunk_frames:
+                        self.stat_output_delays += 1
+                        await asyncio.sleep(one_ms)
+                        times += 1
+                        if times > 200:
+                            print("Hey, the output is STUCK! try --callback if persistent")
+                            await asyncio.sleep(1)
+                            break
+                        continue
+                    self.stream.write(chunk)
+                    break
+
+            # callback play, probabilistic dropping of excess chunks to not overload the queue
+            else:
+                ql=len(q)
+                if ql>2:
+                    await asyncio.sleep(0.002)
+                if ql>6:
+                    prob = ql/10+0.2
+                    if random.random() > prob:
+                        s = "DropQ chunk: q_len=%2d delay=%.1fms < 0. tolerance=%.1fms: P=%.2f"
+                        s = s % (len(self.chunk_queue.chunk_list),
+                                 delay * 1000, self.tolerance_ms, prob)
+                        print(s)
+                        self.stat_time_drops += 1
+                        continue
+                q.append(chunk)
+                # guard against stream stops; doesn't seem to be really necessary but better be sure
+                if not self.stream.is_active():
+                   self.stream.stop_stream()
+                   self.stream.start_stream()
+                   print('restarting stream')
+
 
             # Main status line
             if recent > 200:
@@ -252,7 +401,7 @@
                 s = ("STAT: chunks: q_len=%-3d bs=%4.1f "
                      "ch/s=%5.1f "
                      "net lat: %-5.1fms "
-                     "avg_delay=%-5.2f drops: time=%d net=%d out_delay=%d")
+                     "avg_delay=%-5.2f drops: time=%d net=%d out_delay=%d cqlen=%d")
                 s = s % (
                     len(self.chunk_queue.chunk_list),
                     buffer_space / frames_in_chunk,
@@ -262,6 +411,7 @@
                     self.stat_time_drops,
                     network_drops,
                     self.stat_output_delays,
+                    len(q)
                 )
                 print(s)
 
@@ -277,4 +427,9 @@
                         print("WARNING: You either exceeded the speed of "
                               "light or have unsynchronised clocks")
 
-        print("- Finishing chunk player")
+        finally:
+             print("- Finishing chunk player")
+             glob_stream_break=1
+             await asyncio.sleep(0.05)
+             if self.stream: self._close_stream()
+
diff -u libwavesync-orig/cli_args.py libwavesync/cli_args.py
--- libwavesync-orig/cli_args.py	2020-09-04 02:54:37.107466220 +0200
+++ libwavesync/cli_args.py	2020-09-10 22:27:36.089815983 +0200
@@ -126,14 +126,50 @@
                      help="multicast group or a unicast address, "
                           "may be given multiple times with --tx")
 
+    opt.add_argument("--ntp",
+                     action="store",
+                     metavar="ADDRESS",
+                     default="",
+                     help="NTP server to sync against")
+
+    opt.add_argument("--ntpint",
+                     action="store",
+                     metavar="SECONDS",
+                     type=int,
+                     default=10,
+                     help="NTP server syncing interval")
+
+    opt.add_argument("--ntptol",
+                     action="store",
+                     metavar="MILLISECONDS",
+                     type=int,
+                     default=8,
+                     help="NTP jitter tolerance (below smooths, above jump-adjusts)")
+
+    opt.add_argument("--callback",
+                     action="store_true",
+                     default=False,
+                     help="play via callback instead of blocking write (for android/termux)")
+
     opt.add_argument("--debug",
                      action="store_true",
                      help="enable debugging code")
 
+    opt.add_argument("--list",
+                     action="store_true",
+                     help="list indexes of available audio devices")
+
+    opt.add_argument("--listv",
+                     action="store_true",
+                     help="list indexes of available audio devices, verbosely")
+
+
+
 
 def parse():
     "Parse program arguments"
     version = ".".join(str(p) for p in VERSION)
+    version = version+"-shad"
 
     dst = (
         "WaveSync %s - a multi-room sound synchronisation. "
@@ -154,8 +190,8 @@
 
     args = parser.parse_args()
 
-    if (args.tx is None) == (args.rx is False):
-        parser.error('Exactly one action: --tx or --rx must be specified')
+    if (args.tx is None) == (args.rx is False) == (args.list is False) == (args.listv is False):
+        parser.error('Exactly one action: --tx or --rx or --list or --listv must be specified')
 
     if args.tx is not None:
         if not os.path.exists(args.tx):
diff -u libwavesync-orig/cli.py libwavesync/cli.py
--- libwavesync-orig/cli.py	2020-09-04 02:54:37.107466220 +0200
+++ libwavesync/cli.py	2020-09-10 22:21:20.409116772 +0200
@@ -14,6 +14,7 @@
 
 import asyncio
 import socket
+import sys
 
 from . import (
     AudioConfig,
@@ -21,6 +22,7 @@
     ChunkPlayer,
     ChunkQueue,
     SampleReader,
+    time_machine,
     Receiver
 )
 
@@ -47,7 +49,8 @@
                              receiver=None,
                              tolerance_ms=args.tolerance_ms,
                              buffer_size=args.buffer_size,
-                             device_index=args.device_index)
+                             device_index=args.device_index,
+                             use_callback=args.callback)
         play = player.chunk_player()
         asyncio.ensure_future(play)
     else:
@@ -90,7 +93,8 @@
     player = ChunkPlayer(chunk_queue, receiver,
                          tolerance_ms=args.tolerance_ms,
                          buffer_size=args.buffer_size,
-                         device_index=args.device_index)
+                         device_index=args.device_index,
+                         use_callback=args.callback)
 
     play = player.chunk_player()
 
@@ -98,15 +102,60 @@
     loop.run_until_complete(tasks)
 
 
+def print_dev(p,d,verb):
+    print('Index:',d['index'])
+    if verb:
+      for k,v in d.items():
+        print('    ',k,'=',v)
+    else:
+      for i in ['name','hostApi','maxInputChannels','maxOutputChannels','defaultSampleRate']:
+        if i=='maxInputChannels' and d[i]==0:continue
+        if i=='maxOutputChannels' and d[i]==0:continue
+        if i=='hostApi':
+          desc=''
+          if d['index']==p.get_host_api_info_by_index(d[i])['defaultInputDevice']: desc=desc+' [defaultInput]'
+          if d['index']==p.get_host_api_info_by_index(d[i])['defaultOutputDevice']: desc=desc+' [defaultOutput]'
+          print('    ',i,'=',d[i],'('+p.get_host_api_info_by_index(d[i])['name']+')'+desc)
+        else:
+          print('    ',i,'=',d[i])
+      try:
+        ll=d['defaultLowOutputLatency']
+        lh=d['defaultHighOutputLatency']
+        if not ll==-1 and not lh==-1:
+          print('    ','output latency low/high: {:.1f} / {:.1f} ms'.format(ll*1000,lh*1000))
+      except:
+        pass
+
+
+def list_devs(verb):
+    import pyaudio
+    p=pyaudio.PyAudio()
+    print()
+    print(p.get_device_count(),'devices found:')
+    for i in range(p.get_device_count()):
+        d=p.get_device_info_by_index(i)
+        print()
+        print_dev(p,d,verb)
+
+
 def main():
     "Parse arguments and start the event loop"
     args = parse()
 
+    if args.list:
+        list_devs(False)
+        sys.exit()
+    elif args.listv:
+        list_devs(True)
+        sys.exit()
+
     loop = asyncio.get_event_loop()
 
     if args.debug:
         loop.set_debug(True)
 
+    if not args.ntp == '':
+        time_machine.ntp_init(args.ntp,args.ntpint,args.ntptol)
 
     try:
         if args.tx is not None:
@@ -115,3 +164,5 @@
             start_rx(args, loop)
     finally:
         loop.close()
+        if time_machine.ntptimer: time_machine.ntp_stoptimer()
+
diff -u libwavesync-orig/time_machine.py libwavesync/time_machine.py
--- libwavesync-orig/time_machine.py	2020-09-04 02:54:37.107466220 +0200
+++ libwavesync/time_machine.py	2020-09-11 16:14:54.950915827 +0200
@@ -10,6 +10,12 @@
 # Max latency which can be recorded. Can be limited by cli.
 RANGE = 60
 
+OFFSET=0.0
+NTP_SERVER=''
+# asking interval, seconds
+NTP_INTERVAL=10
+# difference where averaging is reset
+NTP_MAXDIFF=0.008
 
 def get_timemark(relative_ts, latency_s):
     """
@@ -53,4 +59,58 @@
 
 def now():
     "Current UTC timestamp"
-    return datetime.utcnow().timestamp()
+    return datetime.utcnow().timestamp()+OFFSET
+
+
+NTPclient=0;
+def ntp_init(server,interval,maxdiff):
+    global NTPclient
+    global NTP_SERVER
+    global NTP_INTERVAL
+    global NTP_MAXDIFF
+    import ntplib
+    NTPclient = ntplib.NTPClient()
+    NTP_SERVER=server
+    NTP_INTERVAL=interval
+    NTP_MAXDIFF=maxdiff/1000
+    print("NTP:server="+NTP_SERVER+", interval="+str(NTP_INTERVAL)+" sec, max diff="+str(maxdiff)+" ms")
+
+
+from collections import deque
+ntpdq=deque(maxlen=10)
+ntptimer=0
+
+def ntpdq_getavg():
+    return sum(ntpdq)/len(ntpdq)
+
+
+def ntp_getoffset():
+    global OFFSET,ntpdq
+    if NTP_SERVER == '': return
+    try:
+      res=NTPclient.request(NTP_SERVER, version=3)
+    except:
+      print("NTP: query failed")
+      return
+    diff=res.offset-OFFSET
+    if abs(diff) > NTP_MAXDIFF:
+      print('NTP: OVERLY LARGE NTP DIFFERENCE - ntp daemon acted?, smoothing buffer is reset')
+      ntpdq.clear()
+    ntpdq.append(res.offset)
+    OFFSET=ntpdq_getavg()
+    print('NTP: OFFSET set to {:.4f},   diff {:+5.1f} ms,   precision {:.1f}'.format(OFFSET,diff*1000,res.precision))
+
+
+import threading
+
+def ntp_runtimer():
+    if NTP_SERVER == '': return
+    global ntptimer
+    ntp_getoffset()
+    ntptimer=threading.Timer(NTP_INTERVAL,ntp_runtimer)
+    ntptimer.start()
+
+def ntp_stoptimer():
+    if NTP_SERVER == '': return
+    ntptimer.cancel()
+
