aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore4
-rw-r--r--CMakeLists.txt21
-rw-r--r--README23
-rw-r--r--README-gr3.8.patch10
-rw-r--r--README-gr3.932
-rwxr-xr-xadd_gr3.9.py231
-rw-r--r--cmake/Modules/GrMiscUtils.cmake210
-rw-r--r--cmake/Modules/GrPlatform.cmake46
-rw-r--r--cmake/Modules/GrPython.cmake227
-rw-r--r--cmake/Modules/GrSwig.cmake229
-rw-r--r--cmake/Modules/GrTest.cmake133
-rw-r--r--gr3.8.patch367
-rwxr-xr-xinstall-gr3.9.sh72
-rwxr-xr-xinstall.sh25
-rw-r--r--op25/gr-op25/CMakeLists.txt51
-rw-r--r--op25/gr-op25/grc/op25_decoder_ff.xml12
-rw-r--r--op25/gr-op25/grc/op25_fsk4_demod_ff.xml13
-rw-r--r--op25/gr-op25/include/op25/decoder_bf.h13
-rw-r--r--op25/gr-op25/include/op25/message.h82
-rw-r--r--op25/gr-op25/include/op25/msg_handler.h39
-rw-r--r--op25/gr-op25/include/op25/msg_queue.h85
-rw-r--r--op25/gr-op25/lib/CMakeLists.txt9
-rw-r--r--op25/gr-op25/lib/abstract_data_unit.cc21
-rw-r--r--op25/gr-op25/lib/abstract_data_unit.h24
-rw-r--r--op25/gr-op25/lib/bch.cc162
-rw-r--r--op25/gr-op25/lib/bch.h4
-rw-r--r--op25/gr-op25/lib/crypto.cc286
-rw-r--r--op25/gr-op25/lib/crypto.h73
-rw-r--r--op25/gr-op25/lib/crypto_module_du_handler.cc64
-rw-r--r--op25/gr-op25/lib/crypto_module_du_handler.h21
-rw-r--r--op25/gr-op25/lib/data_unit.h6
-rw-r--r--op25/gr-op25/lib/decoder_bf_impl.cc110
-rw-r--r--op25/gr-op25/lib/decoder_bf_impl.h26
-rw-r--r--op25/gr-op25/lib/decoder_ff_impl.cc8
-rw-r--r--op25/gr-op25/lib/des.h15
-rw-r--r--op25/gr-op25/lib/deskey.c124
-rw-r--r--op25/gr-op25/lib/desport.c236
-rw-r--r--op25/gr-op25/lib/dessp.c131
-rw-r--r--op25/gr-op25/lib/fsk4_demod_ff_impl.cc15
-rw-r--r--op25/gr-op25/lib/fsk4_demod_ff_impl.h2
-rw-r--r--op25/gr-op25/lib/hdu.cc75
-rw-r--r--op25/gr-op25/lib/hdu.h15
-rw-r--r--op25/gr-op25/lib/ldu.cc102
-rw-r--r--op25/gr-op25/lib/ldu.h28
-rw-r--r--op25/gr-op25/lib/ldu1.cc69
-rw-r--r--op25/gr-op25/lib/ldu1.h40
-rw-r--r--op25/gr-op25/lib/ldu2.cc50
-rw-r--r--op25/gr-op25/lib/ldu2.h17
-rw-r--r--op25/gr-op25/lib/message.cc63
-rw-r--r--op25/gr-op25/lib/msg_handler.cc23
-rw-r--r--op25/gr-op25/lib/msg_queue.cc113
-rw-r--r--op25/gr-op25/lib/op25.i113
-rw-r--r--op25/gr-op25/lib/op25_hamming.h15
-rw-r--r--op25/gr-op25/lib/op25_imbe_frame.h74
-rw-r--r--op25/gr-op25/lib/value_string.cc39
-rw-r--r--op25/gr-op25/lib/voice_data_unit.cc301
-rw-r--r--op25/gr-op25/lib/voice_data_unit.h17
-rw-r--r--op25/gr-op25/lib/voice_du_handler.cc7
-rw-r--r--op25/gr-op25/lib/voice_du_handler.h5
-rw-r--r--op25/gr-op25/python/CMakeLists.txt2
-rw-r--r--op25/gr-op25/python/__init__.py6
-rw-r--r--op25/gr-op25/python/op25/bindings/message_python.cc134
-rw-r--r--op25/gr-op25/python/op25/bindings/msg_handler_python.cc64
-rw-r--r--op25/gr-op25/python/op25/bindings/msg_queue_python.cc116
-rw-r--r--op25/gr-op25/swig/CMakeLists.txt8
-rw-r--r--op25/gr-op25/swig/op25_swig.i7
-rw-r--r--op25/gr-op25_repeater/CMakeLists.txt50
-rw-r--r--op25/gr-op25_repeater/apps/900.tsv2
-rw-r--r--op25/gr-op25_repeater/apps/README80
-rw-r--r--op25/gr-op25_repeater/apps/README-July-2021291
-rw-r--r--op25/gr-op25_repeater/apps/README-example-udp38
-rw-r--r--op25/gr-op25_repeater/apps/README-hls268
-rw-r--r--op25/gr-op25_repeater/apps/alt-colors.json7
-rwxr-xr-xop25/gr-op25_repeater/apps/audio.py55
-rw-r--r--op25/gr-op25_repeater/apps/cfg-900.json40
-rw-r--r--op25/gr-op25_repeater/apps/cfg-trunk.json40
-rw-r--r--op25/gr-op25_repeater/apps/cfg-trunk2.json50
-rw-r--r--op25/gr-op25_repeater/apps/cfg-trunkx.json98
-rw-r--r--op25/gr-op25_repeater/apps/cfg-udp.json76
-rw-r--r--op25/gr-op25_repeater/apps/cfg.json49
-rw-r--r--op25/gr-op25_repeater/apps/color-map.json602
-rw-r--r--op25/gr-op25_repeater/apps/correlation.json27
-rw-r--r--op25/gr-op25_repeater/apps/create_image.py57
-rw-r--r--op25/gr-op25_repeater/apps/emap.py383
-rw-r--r--op25/gr-op25_repeater/apps/example_liquidsoap.liq73
-rwxr-xr-xop25/gr-op25_repeater/apps/ffmpeg.liq15
-rwxr-xr-xop25/gr-op25_repeater/apps/ffmpeg.sh42
-rw-r--r--op25/gr-op25_repeater/apps/gr_gnuplot.py683
-rw-r--r--op25/gr-op25_repeater/apps/h_cpm.m350
-rwxr-xr-xop25/gr-op25_repeater/apps/http_server.py589
-rwxr-xr-xop25/gr-op25_repeater/apps/install-sql.sh31
-rwxr-xr-xop25/gr-op25_repeater/apps/log_ts.py42
-rwxr-xr-xop25/gr-op25_repeater/apps/multi_rx.py864
-rw-r--r--op25/gr-op25_repeater/apps/nxdn_trunking.py316
-rw-r--r--op25/gr-op25_repeater/apps/op25-liq.service15
-rwxr-xr-xop25/gr-op25_repeater/apps/op25.liq54
-rw-r--r--op25/gr-op25_repeater/apps/oplog/app.cfg4
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/__init__.py844
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap-darkly.css11038
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap.css6763
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables-dark.css461
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables.css453
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc.pngbin0 -> 160 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc_disabled.pngbin0 -> 148 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_both.pngbin0 -> 201 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc.pngbin0 -> 158 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc_disabled.pngbin0 -> 146 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/css/op25.css237
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/dtpick2.js2930
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.css568
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.js2718
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/favicon.icobin0 -> 1150 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-1.11.3.min.js5
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-2.2.4.min.js4
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.bundle.min.js7
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.min.js7
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/js/datatables/jquery.dataTables.js15212
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/js/op25.js227
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/loading.gifbin0 -> 54553 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark-h.pngbin0 -> 3953 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark.pngbin0 -> 3984 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/static/op25.pngbin0 -> 2031 bytes
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/about.html144
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/base.html167
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/dbstats.html53
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/edit_tags.html293
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/editsys.html151
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/error.html191
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/footer-links.html17
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/home.html129
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/inspect.html18
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/logs.html212
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/purge.html123
-rw-r--r--op25/gr-op25_repeater/apps/oplog/op25/templates/switch_db.html129
-rwxr-xr-xop25/gr-op25_repeater/apps/oplog/oplog.sh4
-rw-r--r--op25/gr-op25_repeater/apps/oplog/setup.py30
-rw-r--r--op25/gr-op25_repeater/apps/p25_decoder.py23
-rw-r--r--op25/gr-op25_repeater/apps/p25_demodulator.py276
-rw-r--r--op25/gr-op25_repeater/apps/plot-colors.json7
-rw-r--r--op25/gr-op25_repeater/apps/runudp.sh7
-rwxr-xr-xop25/gr-op25_repeater/apps/rx.py632
-rw-r--r--op25/gr-op25_repeater/apps/site-alias.json12
-rwxr-xr-xop25/gr-op25_repeater/apps/sockaudio.py669
-rwxr-xr-xop25/gr-op25_repeater/apps/sql_dbi.py338
-rw-r--r--op25/gr-op25_repeater/apps/tdma/bit_utils.py14
-rw-r--r--op25/gr-op25_repeater/apps/tdma/lfsr.py83
-rwxr-xr-xop25/gr-op25_repeater/apps/tdma/tdma_audio.py2
-rwxr-xr-x[-rw-r--r--]op25/gr-op25_repeater/apps/terminal.py372
-rw-r--r--op25/gr-op25_repeater/apps/trunk.tsv3
-rw-r--r--op25/gr-op25_repeater/apps/trunking.py1543
-rwxr-xr-xop25/gr-op25_repeater/apps/tsvfile.py191
-rw-r--r--op25/gr-op25_repeater/apps/tx/README-fakecc.txt31
-rw-r--r--op25/gr-op25_repeater/apps/tx/dstar-cfg.dat41
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/dv_tx.py97
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/generate-tsbks.py12
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/multi_tx.py348
-rw-r--r--op25/gr-op25_repeater/apps/tx/nxdn-cfg.dat42
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py97
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/op25_tx.py4
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/p25craft.py175
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/1011.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/afc1011.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/bercalhex.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/busyhex.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/idlehex.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/silencehex.patternbin0 -> 1728 bytes
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/1011hex.dat24
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/afc1011hex.dat24
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/bercalhex.dat24
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/busyhex.dat24
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/idlehex.dat24
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/testpatterns/sources/make-bin.py25
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/sources/silencehex.dat24
-rw-r--r--op25/gr-op25_repeater/apps/tx/testpatterns/test.wavbin0 -> 136932 bytes
-rwxr-xr-xop25/gr-op25_repeater/apps/tx/unpack.py4
-rw-r--r--op25/gr-op25_repeater/apps/tx/ysf-cfg.dat2
-rw-r--r--op25/gr-op25_repeater/apps/ui-settings.json34
-rwxr-xr-xop25/gr-op25_repeater/apps/util/arb-resample.py4
-rwxr-xr-xop25/gr-op25_repeater/apps/util/cqpsk-demod-file.py6
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/CMakeLists.txt4
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/ambe_encoder_sb.h2
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/dstar_tx_sb.h2
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/frame_assembler.h62
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/gardner_costas_cc.h9
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/nxdn_tx_sb.h58
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/p25_frame_assembler.h7
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/vocoder.h2
-rw-r--r--op25/gr-op25_repeater/include/op25_repeater/ysf_tx_sb.h2
-rw-r--r--op25/gr-op25_repeater/lib/CCITTChecksumReverse.cpp93
-rw-r--r--op25/gr-op25_repeater/lib/CCITTChecksumReverse.h39
-rw-r--r--op25/gr-op25_repeater/lib/CMakeLists.txt26
-rw-r--r--op25/gr-op25_repeater/lib/ambe.c14
-rw-r--r--op25/gr-op25_repeater/lib/ambe_encoder.cc3
-rw-r--r--op25/gr-op25_repeater/lib/ambe_encoder.h4
-rw-r--r--op25/gr-op25_repeater/lib/bch.cc2
-rw-r--r--op25/gr-op25_repeater/lib/bit_utils.h59
-rw-r--r--op25/gr-op25_repeater/lib/check_frame_sync.h2
-rw-r--r--op25/gr-op25_repeater/lib/crc16.h35
-rw-r--r--op25/gr-op25_repeater/lib/d2460.cc362
-rw-r--r--op25/gr-op25_repeater/lib/dmr_bs_tx_bb_impl.cc4
-rw-r--r--op25/gr-op25_repeater/lib/dmr_const.h68
-rw-r--r--op25/gr-op25_repeater/lib/dstar_header.h130
-rw-r--r--op25/gr-op25_repeater/lib/dstar_tx_sb_impl.cc44
-rw-r--r--op25/gr-op25_repeater/lib/dstar_tx_sb_impl.h1
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/asserter128
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/bch485
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/bch_base219
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/corrector506
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/definitions9
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/ezcod725
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/output344
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/rs168
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/rs_base1344
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/serialize1188
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/serialize_definitions57
-rw-r--r--op25/gr-op25_repeater/lib/ezpwd/timeofday73
-rw-r--r--op25/gr-op25_repeater/lib/frame_assembler_impl.cc107
-rw-r--r--op25/gr-op25_repeater/lib/frame_assembler_impl.h74
-rw-r--r--op25/gr-op25_repeater/lib/gardner_costas_cc_impl.cc288
-rw-r--r--op25/gr-op25_repeater/lib/gardner_costas_cc_impl.h38
-rw-r--r--op25/gr-op25_repeater/lib/log_ts.h44
-rw-r--r--op25/gr-op25_repeater/lib/mbelib.c12
-rw-r--r--op25/gr-op25_repeater/lib/nxdn.cc354
-rw-r--r--op25/gr-op25_repeater/lib/nxdn.h31
-rw-r--r--op25/gr-op25_repeater/lib/nxdn_const.h98
-rw-r--r--op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.cc373
-rw-r--r--op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.h80
-rw-r--r--op25/gr-op25_repeater/lib/op25_audio.cc247
-rw-r--r--op25/gr-op25_repeater/lib/op25_audio.h70
-rw-r--r--op25/gr-op25_repeater/lib/p25_frame.h6
-rw-r--r--op25/gr-op25_repeater/lib/p25_frame_assembler_impl.cc44
-rw-r--r--op25/gr-op25_repeater/lib/p25_frame_assembler_impl.h8
-rw-r--r--op25/gr-op25_repeater/lib/p25_framer.cc65
-rw-r--r--op25/gr-op25_repeater/lib/p25_framer.h9
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_fdma.cc644
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_fdma.h53
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_voice_decode.cc34
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_voice_decode.h9
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_voice_encode.cc40
-rw-r--r--op25/gr-op25_repeater/lib/p25p1_voice_encode.h9
-rw-r--r--op25/gr-op25_repeater/lib/p25p2_framer.cc2
-rw-r--r--op25/gr-op25_repeater/lib/p25p2_tdma.cc384
-rw-r--r--op25/gr-op25_repeater/lib/p25p2_tdma.h53
-rw-r--r--op25/gr-op25_repeater/lib/p25p2_vf.cc17
-rw-r--r--op25/gr-op25_repeater/lib/p25p2_vf.h4
-rw-r--r--op25/gr-op25_repeater/lib/rs.cc932
-rw-r--r--op25/gr-op25_repeater/lib/rs.h6
-rw-r--r--op25/gr-op25_repeater/lib/rx_sync.cc823
-rw-r--r--op25/gr-op25_repeater/lib/rx_sync.h146
-rw-r--r--op25/gr-op25_repeater/lib/software_imbe_decoder.cc2
-rw-r--r--op25/gr-op25_repeater/lib/software_imbe_decoder.h2
l---------op25/gr-op25_repeater/lib/value_string.cc1
l---------op25/gr-op25_repeater/lib/value_string.h1
-rw-r--r--op25/gr-op25_repeater/lib/vocoder_impl.cc24
-rw-r--r--op25/gr-op25_repeater/lib/vocoder_impl.h2
-rw-r--r--op25/gr-op25_repeater/lib/ysf_const.h71
-rw-r--r--op25/gr-op25_repeater/lib/ysf_tx_sb_impl.cc18
-rw-r--r--op25/gr-op25_repeater/python/CMakeLists.txt2
-rw-r--r--op25/gr-op25_repeater/python/__init__.py6
-rw-r--r--op25/gr-op25_repeater/swig/CMakeLists.txt8
-rw-r--r--op25/gr-op25_repeater/swig/op25_repeater_swig.i9
-rw-r--r--op25/gr-op25_repeater/www/config/README1
-rw-r--r--op25/gr-op25_repeater/www/config/default.json66
-rw-r--r--op25/gr-op25_repeater/www/images/1x1.pngbin0 -> 290 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/csv.pngbin0 -> 5503 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/cx-lite.pngbin0 -> 16384 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/cx.pngbin0 -> 4343 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/da.pngbin0 -> 18213 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/da2.pngbin0 -> 22576 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/favicon.icobin0 -> 1150 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/loading.gifbin0 -> 54553 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/op25-dark.pngbin0 -> 3984 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/op25.pngbin0 -> 2031 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/search.pngbin0 -> 2192 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/sort_asc.pngbin0 -> 160 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/sort_asc_disabled.pngbin0 -> 148 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/sort_both.pngbin0 -> 201 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/sort_desc.pngbin0 -> 158 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/sort_desc_disabled.pngbin0 -> 146 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/status.pngbin0 -> 2321 bytes
-rw-r--r--op25/gr-op25_repeater/www/images/temp.pngbin0 -> 75597 bytes
-rw-r--r--op25/gr-op25_repeater/www/www-static/alias-edit.html116
-rw-r--r--op25/gr-op25_repeater/www/www-static/config.js616
-rw-r--r--op25/gr-op25_repeater/www/www-static/editor.js1247
-rw-r--r--op25/gr-op25_repeater/www/www-static/help.html125
-rw-r--r--op25/gr-op25_repeater/www/www-static/hls.js21550
-rw-r--r--op25/gr-op25_repeater/www/www-static/index.html897
-rw-r--r--op25/gr-op25_repeater/www/www-static/jquery.alerts.css70
-rw-r--r--op25/gr-op25_repeater/www/www-static/jquery.alerts.js268
-rw-r--r--op25/gr-op25_repeater/www/www-static/jquery.js10881
-rw-r--r--op25/gr-op25_repeater/www/www-static/live.html61
-rw-r--r--op25/gr-op25_repeater/www/www-static/live.m3u83
-rw-r--r--op25/gr-op25_repeater/www/www-static/main.css1413
-rw-r--r--op25/gr-op25_repeater/www/www-static/main.js2851
-rw-r--r--op25/gr-op25_repeater/www/www-static/spectrum.css507
-rw-r--r--op25/gr-op25_repeater/www/www-static/spectrum.js2341
-rw-r--r--op25/gr-op25_repeater/www/www-static/tsv-edit.html112
-rw-r--r--op25/gr-op25_repeater/www/www-static/tsv-help.html66
-rw-r--r--scripts/blacklist-rtl.conf4
-rwxr-xr-xscripts/do_sed.sh12
-rwxr-xr-xscripts/do_sedb.sh32
-rwxr-xr-xscripts/do_sedc.sh6
-rwxr-xr-xscripts/do_sedm.sh19
-rwxr-xr-xscripts/do_sedp.sh27
-rwxr-xr-xscripts/do_sedp2.sh13
-rwxr-xr-xscripts/do_sedpy.sh23
-rwxr-xr-xscripts/udev_rules.sh20
307 files changed, 110115 insertions, 3191 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2dd3286
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+# Ignore build artifacts
+build/
+# Ignore .pyc compiled python bytecode files
+*.pyc \ No newline at end of file
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c4f45da..c43483a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,6 +1,27 @@
cmake_minimum_required(VERSION 2.6)
project(gr-op25 CXX C)
+set(CMAKE_BUILD_TYPE Debug)
+set(CMAKE_CXX_FLAGS "-std=c++11")
+
+execute_process(COMMAND python3 -c "
+import os
+import sys
+from distutils import sysconfig
+pfx = '/usr/local'
+m1 = os.path.join('lib', 'python' + sys.version[:3], 'dist-packages')
+m2 = sysconfig.get_python_lib(plat_specific=True, prefix='')
+f1 = os.path.join(pfx, m1)
+f2 = os.path.join(pfx, m2)
+ok2 = f2 in sys.path
+if ok2:
+ print(m2)
+else:
+ print(m1)
+" OUTPUT_VARIABLE OP25_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE
+)
+MESSAGE(STATUS "OP25_PYTHON_DIR has been set to \"${OP25_PYTHON_DIR}\".")
+
add_subdirectory(op25/gr-op25)
add_subdirectory(op25/gr-op25_repeater)
diff --git a/README b/README
new file mode 100644
index 0000000..335b2a1
--- /dev/null
+++ b/README
@@ -0,0 +1,23 @@
+
+As of this writing (Sept. 2022) OP25 builds for python3 and GNU Radio 3.8.
+
+The full list of supported versions is as follows:
+
+PYTHON 2 AND GNU RADIO 3.7
+==========================
+It should still be possible to use the file gr3.8.patch (in reverse) to
+downgrade the source tree to build against Python 2 and GNU Radio 3.7,
+although this has not been tested.
+ $ cat gr3.8.patch | patch -p1 -R
+Once this has been done, proceed by running the install.sh script.
+
+PYTHON 3 AND GNU RADIO 3.8
+==========================
+It is no longer necessary to apply the gr3.8 patch to the op25 source tree,
+as Python3/GNU Radio 3.8 is now the default. You can proceed directly to
+running the install.sh script.
+
+PYTHON 3 AND GNU RADIO 3.9 / 3.10
+=================================
+It is no longer necessary to apply the gr3.8 patch to the op25 source tree,
+See the file README-gr3.9 for procedures for both GNU Radio 3.9 and 3.10.
diff --git a/README-gr3.8.patch b/README-gr3.8.patch
new file mode 100644
index 0000000..5efdca7
--- /dev/null
+++ b/README-gr3.8.patch
@@ -0,0 +1,10 @@
+
+Updated Sept. 2022
+
+By default, OP25 now builds for Python3 and GNU Radio3.8.
+Accordingly, it is no longer necessary to apply the op25 patch
+for gr3.8.
+
+It should be possible to use the gr3.8.patch in reverse to downgrade
+the source tree to build for Python 2 and GNU Radio 3.7. See the
+file README in this directory for details.
diff --git a/README-gr3.9 b/README-gr3.9
new file mode 100644
index 0000000..0991be4
--- /dev/null
+++ b/README-gr3.9
@@ -0,0 +1,32 @@
+
+Running OP25 in Gnuradio 3.9 and 3.10 Date: May 31, 2022
+==============================================================
+
+Installation
+------------
+
+0. First remove any existing OP25 installation
+ cd ...path-to-existing/op25/build
+ sudo make uninstall
+
+1. Step 1 is removed.
+
+2. Run the command
+ ./install-gr3.9.sh
+ (Note, do not use the standard install.sh script for gr3.9 and/or gr3.10).
+
+Bugs
+----
+
+1. The location for WIN_HANN, WIN_HAMMING, and so forth has moved to
+ fft.window (formerly filter.firdes). The python has not yet been
+ updated to reflect.
+
+2. A strange hang condition has been observed in rx.py - the bug is not
+ fully understood. The strace output shows many futex calls ending
+ with a "timeout" - not clear if some missing event might be causing this
+ stall condition... User feedback is requested...
+
+3. Currently the cmake process is not centralized; 'make uninstall' must
+ therefore be run once from each of the 'build' and 'build_repeater'
+ directories under 'src/'.
diff --git a/add_gr3.9.py b/add_gr3.9.py
new file mode 100755
index 0000000..e68a80e
--- /dev/null
+++ b/add_gr3.9.py
@@ -0,0 +1,231 @@
+#! /usr/bin/python3
+
+# Copyright 2022, Max H. Parke KA1RBI
+#
+# This file is part of GNU Radio and part of OP25
+#
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+
+import sys
+import os
+import glob
+import shutil
+from gnuradio.modtool.core.newmod import ModToolNewModule
+from gnuradio.modtool.core.add import ModToolAdd
+from gnuradio.modtool.core.bind import ModToolGenBindings
+
+msg = """
+This is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+"""
+
+print('\n%s Copyright 2022, Max H. Parke KA1RBI\nhttps://osmocom.org/projects/op25\n%s' % (sys.argv[0], msg))
+
+TLD = 'op25'
+
+MODS={
+ 'op25': 'decoder_bf decoder_ff fsk4_demod_ff fsk4_slicer_fb pcap_source_b message msg_queue msg_handler'.split(),
+ 'op25_repeater': 'ambe_encoder_sb dmr_bs_tx_bb dstar_tx_sb frame_assembler fsk4_slicer_fb gardner_costas_cc nxdn_tx_sb p25_frame_assembler vocoder ysf_tx_sb'.split()
+}
+
+SKIP_CC = 'd2460.cc qa_op25.cc test_op25.cc qa_op25_repeater.cc test_op25_repeater.cc message.cc msg_queue.cc msg_handler.cc'.split()
+
+SRC_DIR = sys.argv[1]
+DEST_DIR = sys.argv[2]
+
+if '..' in SRC_DIR or not SRC_DIR.startswith('/'):
+ sys.stderr.write('error, %s must be an absolute path\n' % SRC_DIR)
+ sys.exit(1)
+
+if not os.access(SRC_DIR, os.R_OK):
+ sys.stderr.write('error, unable to access %s\n' % SRC_DIR)
+ sys.exit(1)
+
+if not os.path.isdir(SRC_DIR + '/op25/gr-op25_repeater'):
+ sys.stderr.write('error, op25 package not found in %s\n' % SRC_DIR)
+ sys.exit(3)
+
+if os.access(DEST_DIR, os.F_OK) or os.path.isdir(DEST_DIR):
+ sys.stderr.write('error, destination path %s must not exist\n' % DEST_DIR)
+ sys.exit(4)
+
+os.mkdir(DEST_DIR)
+op25_dir = DEST_DIR + '/op25'
+os.mkdir(op25_dir)
+os.chdir(op25_dir)
+
+SCRIPTS = SRC_DIR + '/scripts'
+
+TXT = """add_library(op25-message SHARED message.cc msg_queue.cc msg_handler.cc)
+install(TARGETS op25-message EXPORT op25-message-export DESTINATION lib)
+install(EXPORT op25-message-export DESTINATION ${GR_CMAKE_DIR})
+target_include_directories(op25-message
+ PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../include>
+ PUBLIC $<INSTALL_INTERFACE:include>
+ )
+"""
+
+def edit_cmake(filename, mod, srcfiles):
+ lines = open(filename).read().rstrip().split('\n')
+ srcdefs = []
+ state = 0
+ end_mark = 0
+ add_library = 0
+ tll = 0 # target_link_library
+ srcfiles = [s.split('/')[-1] for s in srcfiles if s.endswith('.cc') or s.endswith('.c') or s.endswith('.cpp')]
+ lines = [l for l in lines if l.strip() not in SKIP_CC]
+ for i in range(len(lines)):
+ if 'add_library' in lines[i] and 'gnuradio-op25' in lines[i]:
+ add_library = i
+ if lines[i].startswith('list(APPEND op25_') and ('_sources' in lines[i] or '_python_files' in lines[i]):
+ state = 1
+ continue
+ elif ')' in lines[i] and state:
+ state = 0
+ end_mark = i
+ continue
+ elif lines[i].startswith('target_link_libraries(gnuradio-op25'):
+ assert lines[i].endswith(')')
+ tll = i
+ continue
+ if state:
+ srcdefs.append(lines[i].strip())
+ srcfiles = [" %s" % s for s in srcfiles if s not in srcdefs and s not in SKIP_CC]
+ tlls = {
+ 'op25': 'target_link_libraries(gnuradio-op25 gnuradio::gnuradio-runtime Boost::system Boost::program_options Boost::filesystem Boost::thread itpp pcap op25-message)',
+ 'op25_repeater': 'target_link_libraries(gnuradio-op25_repeater PUBLIC gnuradio::gnuradio-runtime gnuradio::gnuradio-filter op25-message PRIVATE imbe_vocoder)'
+ }
+ assert tll # fail if target_link_libraries line not found
+ lines[tll] = tlls[mod]
+ if mod == 'op25_repeater':
+ lines = lines[:tll] + ['\n' + 'add_subdirectory(imbe_vocoder)\n'] + lines[tll:]
+ elif mod == 'op25':
+ assert add_library > 0
+ lines = lines[:add_library] + [s for s in TXT.split('\n')] + lines[add_library:]
+
+ new_lines = lines[:end_mark] + srcfiles + lines[end_mark:]
+ s = '\n'.join(new_lines)
+ s += '\n'
+ with open(filename, 'w') as fp:
+ fp.write(s)
+
+def get_args_from_h(mod):
+ lines = open(mod).read().rstrip().split('\n')
+
+ lines = [line for line in lines if 'make' in line]
+
+ answer = []
+ for s in lines:
+ s = s.rstrip()
+ if s[-1] != ';':
+ continue
+ s = s[:-1]
+ s = s.rstrip()
+ if s[-1] != ')':
+ continue
+ s = s[:-1]
+ lp = s.find('(')
+ if lp > 0:
+ s =s[lp+1:]
+ else:
+ continue
+ for arg in s.split(','):
+ eq = arg.find('=')
+ if eq > 0:
+ arg = arg[:eq]
+ answer.append(arg)
+ return ','.join(answer)
+ return ''
+
+for mod in sorted(MODS.keys()):
+ m = ModToolNewModule(module_name=mod, srcdir=None)
+ m.run()
+ print('gr_modtool newmod %s getcwd now %s' % (mod, os.getcwd()))
+ pfx = '%s/op25/gr-%s' % (SRC_DIR, mod)
+ lib = '%s/lib' % pfx
+ s_py = '%s/python/op25/bindings' % pfx
+ incl = '%s/include/%s' % (pfx, mod)
+ d_pfx = '%s/op25/gr-%s' % (DEST_DIR, mod)
+ d_lib = '%s/lib' % d_pfx
+ d_py = '%s/python/op25/bindings' % d_pfx
+ d_incl_alt1 = '%s/include/%s' % (d_pfx, mod)
+ d_incl_alt2 = '%s/include/gnuradio/%s' % (d_pfx, mod)
+ if os.path.isdir(d_incl_alt1):
+ d_incl = d_incl_alt1
+ elif os.path.isdir(d_incl_alt2):
+ d_incl = d_incl_alt2
+ sl = 'gnuradio/%s' % mod
+ os.symlink(sl, '%s/include/%s' % (d_pfx, mod))
+ if mod == 'op25_repeater':
+ p_pfx = '%s/op25/gr-%s' % (DEST_DIR, 'op25')
+ p_incl = '%s/include/%s' % (p_pfx, 'op25')
+ d = '/'.join(d_incl.split('/')[:-1])
+ os.symlink(p_incl, '%s/include/%s' % (d_pfx, 'op25'))
+
+ else:
+ sys.stderr.write('neither %s nor %s found, aborting\n' % (d_incl_alt1, d_incl_alt2))
+ sys.exit(1)
+
+ for block in MODS[mod]:
+ include = '%s/%s.h' % (incl, block)
+ args = get_args_from_h(include)
+ t = 'sync' if block == 'fsk4_slicer_fb' or block == 'pcap_source_b' else 'general'
+ if block == 'message' or block == 'msg_queue' or block == 'msg_handler':
+ t = 'noblock'
+ print ('add %s %s type %s directory %s args %s' % (mod, block, t, os.getcwd(), args))
+ m = ModToolAdd(blockname=block,block_type=t,lang='cpp',copyright='Steve Glass, OP25 Group', argument_list=args)
+ m.run()
+
+ srcfiles = []
+ srcfiles += glob.glob('%s/lib/*.cc' % pfx)
+ srcfiles += glob.glob('%s/lib/*.cpp' % pfx)
+ srcfiles += glob.glob('%s/lib/*.c' % pfx)
+ srcfiles += glob.glob('%s/lib/*.h' % pfx)
+ hfiles = glob.glob('%s/*.h' % incl)
+
+ assert os.path.isdir(d_lib)
+ assert os.path.isdir(d_incl)
+
+ for f in srcfiles:
+ shutil.copy(f, d_lib)
+
+ for f in hfiles:
+ shutil.copy(f, d_incl)
+
+ os.system('/bin/bash %s/%s %s' % (SCRIPTS, 'do_sedm.sh', d_incl))
+
+ if mod == 'op25_repeater':
+ for d in 'imbe_vocoder ezpwd'.split():
+ os.mkdir('%s/%s' % (d_lib, d))
+ imbefiles = []
+ imbefiles += glob.glob('%s/%s/*' % (lib, d))
+ dest = '%s/%s' % (d_lib, d)
+ for f in imbefiles:
+ shutil.copy(f, dest)
+
+ edit_cmake('%s/CMakeLists.txt' % d_lib, mod, srcfiles)
+
+ os.system('/bin/bash %s/do_sed.sh' % (SCRIPTS))
+ f = '%s/CMakeLists.txt' % (d_pfx)
+ if mod == 'op25':
+ exe = '%s/do_sedb.sh %s' % (SCRIPTS, f)
+ elif mod == 'op25_repeater':
+ exe = '%s/do_sedc.sh %s' % (SCRIPTS, f)
+ os.system('/bin/bash %s %s' % (exe, f))
+ os.system('/bin/bash %s/do_sedp.sh %s' % (SCRIPTS, f))
+ os.system('/bin/bash %s/do_sedp2.sh %s' % (SCRIPTS, d_pfx))
+
+ for block in MODS[mod]:
+ print ('bind %s %s' % (mod, block))
+ m = ModToolGenBindings(block, addl_includes='', define_symbols='', update_hash_only=False)
+ m.run()
+
+ if mod == 'op25':
+ py_cc_srcfiles = 'message_python.cc msg_handler_python.cc msg_queue_python.cc'.split()
+ for f in py_cc_srcfiles:
+ shutil.copy('%s/%s' % (s_py, f), d_py)
+
+ os.chdir(op25_dir)
diff --git a/cmake/Modules/GrMiscUtils.cmake b/cmake/Modules/GrMiscUtils.cmake
deleted file mode 100644
index 9331d5d..0000000
--- a/cmake/Modules/GrMiscUtils.cmake
+++ /dev/null
@@ -1,210 +0,0 @@
-# Copyright 2010-2011 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-
-if(DEFINED __INCLUDED_GR_MISC_UTILS_CMAKE)
- return()
-endif()
-set(__INCLUDED_GR_MISC_UTILS_CMAKE TRUE)
-
-########################################################################
-# Set global variable macro.
-# Used for subdirectories to export settings.
-# Example: include and library paths.
-########################################################################
-function(GR_SET_GLOBAL var)
- set(${var} ${ARGN} CACHE INTERNAL "" FORCE)
-endfunction(GR_SET_GLOBAL)
-
-########################################################################
-# Set the pre-processor definition if the condition is true.
-# - def the pre-processor definition to set and condition name
-########################################################################
-function(GR_ADD_COND_DEF def)
- if(${def})
- add_definitions(-D${def})
- endif(${def})
-endfunction(GR_ADD_COND_DEF)
-
-########################################################################
-# Check for a header and conditionally set a compile define.
-# - hdr the relative path to the header file
-# - def the pre-processor definition to set
-########################################################################
-function(GR_CHECK_HDR_N_DEF hdr def)
- include(CheckIncludeFileCXX)
- CHECK_INCLUDE_FILE_CXX(${hdr} ${def})
- GR_ADD_COND_DEF(${def})
-endfunction(GR_CHECK_HDR_N_DEF)
-
-########################################################################
-# Include subdirectory macro.
-# Sets the CMake directory variables,
-# includes the subdirectory CMakeLists.txt,
-# resets the CMake directory variables.
-#
-# This macro includes subdirectories rather than adding them
-# so that the subdirectory can affect variables in the level above.
-# This provides a work-around for the lack of convenience libraries.
-# This way a subdirectory can append to the list of library sources.
-########################################################################
-macro(GR_INCLUDE_SUBDIRECTORY subdir)
- #insert the current directories on the front of the list
- list(INSERT _cmake_source_dirs 0 ${CMAKE_CURRENT_SOURCE_DIR})
- list(INSERT _cmake_binary_dirs 0 ${CMAKE_CURRENT_BINARY_DIR})
-
- #set the current directories to the names of the subdirs
- set(CMAKE_CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/${subdir})
- set(CMAKE_CURRENT_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/${subdir})
-
- #include the subdirectory CMakeLists to run it
- file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
- include(${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt)
-
- #reset the value of the current directories
- list(GET _cmake_source_dirs 0 CMAKE_CURRENT_SOURCE_DIR)
- list(GET _cmake_binary_dirs 0 CMAKE_CURRENT_BINARY_DIR)
-
- #pop the subdir names of the front of the list
- list(REMOVE_AT _cmake_source_dirs 0)
- list(REMOVE_AT _cmake_binary_dirs 0)
-endmacro(GR_INCLUDE_SUBDIRECTORY)
-
-########################################################################
-# Check if a compiler flag works and conditionally set a compile define.
-# - flag the compiler flag to check for
-# - have the variable to set with result
-########################################################################
-macro(GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE flag have)
- include(CheckCXXCompilerFlag)
- CHECK_CXX_COMPILER_FLAG(${flag} ${have})
- if(${have})
- add_definitions(${flag})
- endif(${have})
-endmacro(GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE)
-
-########################################################################
-# Generates the .la libtool file
-# This appears to generate libtool files that cannot be used by auto*.
-# Usage GR_LIBTOOL(TARGET [target] DESTINATION [dest])
-# Notice: there is not COMPONENT option, these will not get distributed.
-########################################################################
-function(GR_LIBTOOL)
- if(NOT DEFINED GENERATE_LIBTOOL)
- set(GENERATE_LIBTOOL OFF) #disabled by default
- endif()
-
- if(GENERATE_LIBTOOL)
- include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_LIBTOOL "" "TARGET;DESTINATION" "" ${ARGN})
-
- find_program(LIBTOOL libtool)
- if(LIBTOOL)
- include(CMakeMacroLibtoolFile)
- CREATE_LIBTOOL_FILE(${GR_LIBTOOL_TARGET} /${GR_LIBTOOL_DESTINATION})
- endif(LIBTOOL)
- endif(GENERATE_LIBTOOL)
-
-endfunction(GR_LIBTOOL)
-
-########################################################################
-# Do standard things to the library target
-# - set target properties
-# - make install rules
-# Also handle gnuradio custom naming conventions w/ extras mode.
-########################################################################
-function(GR_LIBRARY_FOO target)
- #parse the arguments for component names
- include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_LIBRARY "" "RUNTIME_COMPONENT;DEVEL_COMPONENT" "" ${ARGN})
-
- #set additional target properties
- set_target_properties(${target} PROPERTIES SOVERSION ${LIBVER})
-
- #install the generated files like so...
- install(TARGETS ${target}
- LIBRARY DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT} # .so/.dylib file
- ARCHIVE DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_DEVEL_COMPONENT} # .lib file
- RUNTIME DESTINATION ${GR_RUNTIME_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT} # .dll file
- )
-
- #extras mode enabled automatically on linux
- if(NOT DEFINED LIBRARY_EXTRAS)
- set(LIBRARY_EXTRAS ${LINUX})
- endif()
-
- #special extras mode to enable alternative naming conventions
- if(LIBRARY_EXTRAS)
-
- #create .la file before changing props
- GR_LIBTOOL(TARGET ${target} DESTINATION ${GR_LIBRARY_DIR})
-
- #give the library a special name with ultra-zero soversion
- set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_NAME ${target}-${LIBVER} SOVERSION "0.0.0")
- set(target_name lib${target}-${LIBVER}.so.0.0.0)
-
- #custom command to generate symlinks
- add_custom_command(
- TARGET ${target}
- POST_BUILD
- COMMAND ${CMAKE_COMMAND} -E create_symlink ${target_name} ${CMAKE_CURRENT_BINARY_DIR}/lib${target}.so
- COMMAND ${CMAKE_COMMAND} -E create_symlink ${target_name} ${CMAKE_CURRENT_BINARY_DIR}/lib${target}-${LIBVER}.so.0
- COMMAND ${CMAKE_COMMAND} -E touch ${target_name} #so the symlinks point to something valid so cmake 2.6 will install
- )
-
- #and install the extra symlinks
- install(
- FILES
- ${CMAKE_CURRENT_BINARY_DIR}/lib${target}.so
- ${CMAKE_CURRENT_BINARY_DIR}/lib${target}-${LIBVER}.so.0
- DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT}
- )
-
- endif(LIBRARY_EXTRAS)
-endfunction(GR_LIBRARY_FOO)
-
-########################################################################
-# Create a dummy custom command that depends on other targets.
-# Usage:
-# GR_GEN_TARGET_DEPS(unique_name target_deps <target1> <target2> ...)
-# ADD_CUSTOM_COMMAND(<the usual args> ${target_deps})
-#
-# Custom command cant depend on targets, but can depend on executables,
-# and executables can depend on targets. So this is the process:
-########################################################################
-function(GR_GEN_TARGET_DEPS name var)
- file(
- WRITE ${CMAKE_CURRENT_BINARY_DIR}/${name}.cpp.in
- "int main(void){return 0;}\n"
- )
- execute_process(
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- ${CMAKE_CURRENT_BINARY_DIR}/${name}.cpp.in
- ${CMAKE_CURRENT_BINARY_DIR}/${name}.cpp
- )
- add_executable(${name} ${CMAKE_CURRENT_BINARY_DIR}/${name}.cpp)
- if(ARGN)
- add_dependencies(${name} ${ARGN})
- endif(ARGN)
-
- if(CMAKE_CROSSCOMPILING)
- set(${var} "DEPENDS;${name}" PARENT_SCOPE) #cant call command when cross
- else()
- set(${var} "DEPENDS;${name};COMMAND;${name}" PARENT_SCOPE)
- endif()
-endfunction(GR_GEN_TARGET_DEPS)
diff --git a/cmake/Modules/GrPlatform.cmake b/cmake/Modules/GrPlatform.cmake
deleted file mode 100644
index a2e4f3b..0000000
--- a/cmake/Modules/GrPlatform.cmake
+++ /dev/null
@@ -1,46 +0,0 @@
-# Copyright 2011 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-
-if(DEFINED __INCLUDED_GR_PLATFORM_CMAKE)
- return()
-endif()
-set(__INCLUDED_GR_PLATFORM_CMAKE TRUE)
-
-########################################################################
-# Setup additional defines for OS types
-########################################################################
-if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
- set(LINUX TRUE)
-endif()
-
-if(LINUX AND EXISTS "/etc/debian_version")
- set(DEBIAN TRUE)
-endif()
-
-if(LINUX AND EXISTS "/etc/redhat-release")
- set(REDHAT TRUE)
-endif()
-
-########################################################################
-# when the library suffix should be 64 (applies to redhat linux family)
-########################################################################
-if(NOT DEFINED LIB_SUFFIX AND REDHAT AND CMAKE_SYSTEM_PROCESSOR MATCHES "64$")
- set(LIB_SUFFIX 64)
-endif()
-set(LIB_SUFFIX ${LIB_SUFFIX} CACHE STRING "lib directory suffix")
diff --git a/cmake/Modules/GrPython.cmake b/cmake/Modules/GrPython.cmake
deleted file mode 100644
index 68ca58e..0000000
--- a/cmake/Modules/GrPython.cmake
+++ /dev/null
@@ -1,227 +0,0 @@
-# Copyright 2010-2011 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-
-if(DEFINED __INCLUDED_GR_PYTHON_CMAKE)
- return()
-endif()
-set(__INCLUDED_GR_PYTHON_CMAKE TRUE)
-
-########################################################################
-# Setup the python interpreter:
-# This allows the user to specify a specific interpreter,
-# or finds the interpreter via the built-in cmake module.
-########################################################################
-#this allows the user to override PYTHON_EXECUTABLE
-if(PYTHON_EXECUTABLE)
-
- set(PYTHONINTERP_FOUND TRUE)
-
-#otherwise if not set, try to automatically find it
-else(PYTHON_EXECUTABLE)
-
- #use the built-in find script
- find_package(PythonInterp 2)
-
- #and if that fails use the find program routine
- if(NOT PYTHONINTERP_FOUND)
- find_program(PYTHON_EXECUTABLE NAMES python python2 python2.7 python2.6 python2.5)
- if(PYTHON_EXECUTABLE)
- set(PYTHONINTERP_FOUND TRUE)
- endif(PYTHON_EXECUTABLE)
- endif(NOT PYTHONINTERP_FOUND)
-
-endif(PYTHON_EXECUTABLE)
-
-#make the path to the executable appear in the cmake gui
-set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE} CACHE FILEPATH "python interpreter")
-
-#make sure we can use -B with python (introduced in 2.6)
-if(PYTHON_EXECUTABLE)
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -B -c ""
- OUTPUT_QUIET ERROR_QUIET
- RESULT_VARIABLE PYTHON_HAS_DASH_B_RESULT
- )
- if(PYTHON_HAS_DASH_B_RESULT EQUAL 0)
- set(PYTHON_DASH_B "-B")
- endif()
-endif(PYTHON_EXECUTABLE)
-
-########################################################################
-# Check for the existence of a python module:
-# - desc a string description of the check
-# - mod the name of the module to import
-# - cmd an additional command to run
-# - have the result variable to set
-########################################################################
-macro(GR_PYTHON_CHECK_MODULE desc mod cmd have)
- message(STATUS "")
- message(STATUS "Python checking for ${desc}")
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "
-#########################################
-try: import ${mod}
-except: exit(-1)
-try: assert ${cmd}
-except: exit(-1)
-#########################################"
- RESULT_VARIABLE ${have}
- )
- if(${have} EQUAL 0)
- message(STATUS "Python checking for ${desc} - found")
- set(${have} TRUE)
- else(${have} EQUAL 0)
- message(STATUS "Python checking for ${desc} - not found")
- set(${have} FALSE)
- endif(${have} EQUAL 0)
-endmacro(GR_PYTHON_CHECK_MODULE)
-
-########################################################################
-# Sets the python installation directory GR_PYTHON_DIR
-########################################################################
-execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "
-from distutils import sysconfig
-print sysconfig.get_python_lib(plat_specific=True, prefix='')
-" OUTPUT_VARIABLE GR_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE
-)
-file(TO_CMAKE_PATH ${GR_PYTHON_DIR} GR_PYTHON_DIR)
-
-########################################################################
-# Create an always-built target with a unique name
-# Usage: GR_UNIQUE_TARGET(<description> <dependencies list>)
-########################################################################
-function(GR_UNIQUE_TARGET desc)
- file(RELATIVE_PATH reldir ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR})
- execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import re, hashlib
-unique = hashlib.md5('${reldir}${ARGN}').hexdigest()[:5]
-print(re.sub('\\W', '_', '${desc} ${reldir} ' + unique))"
- OUTPUT_VARIABLE _target OUTPUT_STRIP_TRAILING_WHITESPACE)
- add_custom_target(${_target} ALL DEPENDS ${ARGN})
-endfunction(GR_UNIQUE_TARGET)
-
-########################################################################
-# Install python sources (also builds and installs byte-compiled python)
-########################################################################
-function(GR_PYTHON_INSTALL)
- include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_PYTHON_INSTALL "" "DESTINATION;COMPONENT" "FILES;PROGRAMS" ${ARGN})
-
- ####################################################################
- if(GR_PYTHON_INSTALL_FILES)
- ####################################################################
- install(${ARGN}) #installs regular python files
-
- #create a list of all generated files
- unset(pysrcfiles)
- unset(pycfiles)
- unset(pyofiles)
- foreach(pyfile ${GR_PYTHON_INSTALL_FILES})
- get_filename_component(pyfile ${pyfile} ABSOLUTE)
- list(APPEND pysrcfiles ${pyfile})
-
- #determine if this file is in the source or binary directory
- file(RELATIVE_PATH source_rel_path ${CMAKE_CURRENT_SOURCE_DIR} ${pyfile})
- string(LENGTH "${source_rel_path}" source_rel_path_len)
- file(RELATIVE_PATH binary_rel_path ${CMAKE_CURRENT_BINARY_DIR} ${pyfile})
- string(LENGTH "${binary_rel_path}" binary_rel_path_len)
-
- #and set the generated path appropriately
- if(${source_rel_path_len} GREATER ${binary_rel_path_len})
- set(pygenfile ${CMAKE_CURRENT_BINARY_DIR}/${binary_rel_path})
- else()
- set(pygenfile ${CMAKE_CURRENT_BINARY_DIR}/${source_rel_path})
- endif()
- list(APPEND pycfiles ${pygenfile}c)
- list(APPEND pyofiles ${pygenfile}o)
-
- #ensure generation path exists
- get_filename_component(pygen_path ${pygenfile} PATH)
- file(MAKE_DIRECTORY ${pygen_path})
-
- endforeach(pyfile)
-
- #the command to generate the pyc files
- add_custom_command(
- DEPENDS ${pysrcfiles} OUTPUT ${pycfiles}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_BINARY_DIR}/python_compile_helper.py ${pysrcfiles} ${pycfiles}
- )
-
- #the command to generate the pyo files
- add_custom_command(
- DEPENDS ${pysrcfiles} OUTPUT ${pyofiles}
- COMMAND ${PYTHON_EXECUTABLE} -O ${CMAKE_BINARY_DIR}/python_compile_helper.py ${pysrcfiles} ${pyofiles}
- )
-
- #create install rule and add generated files to target list
- set(python_install_gen_targets ${pycfiles} ${pyofiles})
- install(FILES ${python_install_gen_targets}
- DESTINATION ${GR_PYTHON_INSTALL_DESTINATION}
- COMPONENT ${GR_PYTHON_INSTALL_COMPONENT}
- )
-
-
- ####################################################################
- elseif(GR_PYTHON_INSTALL_PROGRAMS)
- ####################################################################
- file(TO_NATIVE_PATH ${PYTHON_EXECUTABLE} pyexe_native)
-
- foreach(pyfile ${GR_PYTHON_INSTALL_PROGRAMS})
- get_filename_component(pyfile_name ${pyfile} NAME)
- get_filename_component(pyfile ${pyfile} ABSOLUTE)
- string(REPLACE "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}" pyexefile "${pyfile}.exe")
- list(APPEND python_install_gen_targets ${pyexefile})
-
- get_filename_component(pyexefile_path ${pyexefile} PATH)
- file(MAKE_DIRECTORY ${pyexefile_path})
-
- add_custom_command(
- OUTPUT ${pyexefile} DEPENDS ${pyfile}
- COMMAND ${PYTHON_EXECUTABLE} -c
- \"open('${pyexefile}', 'w').write('\#!${pyexe_native}\\n'+open('${pyfile}').read())\"
- COMMENT "Shebangin ${pyfile_name}"
- )
-
- #on windows, python files need an extension to execute
- get_filename_component(pyfile_ext ${pyfile} EXT)
- if(WIN32 AND NOT pyfile_ext)
- set(pyfile_name "${pyfile_name}.py")
- endif()
-
- install(PROGRAMS ${pyexefile} RENAME ${pyfile_name}
- DESTINATION ${GR_PYTHON_INSTALL_DESTINATION}
- COMPONENT ${GR_PYTHON_INSTALL_COMPONENT}
- )
- endforeach(pyfile)
-
- endif()
-
- GR_UNIQUE_TARGET("pygen" ${python_install_gen_targets})
-
-endfunction(GR_PYTHON_INSTALL)
-
-########################################################################
-# Write the python helper script that generates byte code files
-########################################################################
-file(WRITE ${CMAKE_BINARY_DIR}/python_compile_helper.py "
-import sys, py_compile
-files = sys.argv[1:]
-srcs, gens = files[:len(files)/2], files[len(files)/2:]
-for src, gen in zip(srcs, gens):
- py_compile.compile(file=src, cfile=gen, doraise=True)
-")
diff --git a/cmake/Modules/GrSwig.cmake b/cmake/Modules/GrSwig.cmake
deleted file mode 100644
index 569667b..0000000
--- a/cmake/Modules/GrSwig.cmake
+++ /dev/null
@@ -1,229 +0,0 @@
-# Copyright 2010-2011 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-
-if(DEFINED __INCLUDED_GR_SWIG_CMAKE)
- return()
-endif()
-set(__INCLUDED_GR_SWIG_CMAKE TRUE)
-
-include(GrPython)
-
-########################################################################
-# Builds a swig documentation file to be generated into python docstrings
-# Usage: GR_SWIG_MAKE_DOCS(output_file input_path input_path....)
-#
-# Set the following variable to specify extra dependent targets:
-# - GR_SWIG_DOCS_SOURCE_DEPS
-# - GR_SWIG_DOCS_TARGET_DEPS
-########################################################################
-function(GR_SWIG_MAKE_DOCS output_file)
- find_package(Doxygen)
- if(DOXYGEN_FOUND)
-
- #setup the input files variable list, quote formated
- set(input_files)
- unset(INPUT_PATHS)
- foreach(input_path ${ARGN})
- if (IS_DIRECTORY ${input_path}) #when input path is a directory
- file(GLOB input_path_h_files ${input_path}/*.h)
- else() #otherwise its just a file, no glob
- set(input_path_h_files ${input_path})
- endif()
- list(APPEND input_files ${input_path_h_files})
- set(INPUT_PATHS "${INPUT_PATHS} \"${input_path}\"")
- endforeach(input_path)
-
- #determine the output directory
- get_filename_component(name ${output_file} NAME_WE)
- get_filename_component(OUTPUT_DIRECTORY ${output_file} PATH)
- set(OUTPUT_DIRECTORY ${OUTPUT_DIRECTORY}/${name}_swig_docs)
- make_directory(${OUTPUT_DIRECTORY})
-
- #generate the Doxyfile used by doxygen
- configure_file(
- ${CMAKE_SOURCE_DIR}/docs/doxygen/Doxyfile.swig_doc.in
- ${OUTPUT_DIRECTORY}/Doxyfile
- @ONLY)
-
- #Create a dummy custom command that depends on other targets
- include(GrMiscUtils)
- GR_GEN_TARGET_DEPS(_${name}_tag tag_deps ${GR_SWIG_DOCS_TARGET_DEPS})
-
- #call doxygen on the Doxyfile + input headers
- add_custom_command(
- OUTPUT ${OUTPUT_DIRECTORY}/xml/index.xml
- DEPENDS ${input_files} ${GR_SWIG_DOCS_SOURCE_DEPS} ${tag_deps}
- COMMAND ${DOXYGEN_EXECUTABLE} ${OUTPUT_DIRECTORY}/Doxyfile
- COMMENT "Generating doxygen xml for ${name} docs"
- )
-
- #call the swig_doc script on the xml files
- add_custom_command(
- OUTPUT ${output_file}
- DEPENDS ${input_files} ${OUTPUT_DIRECTORY}/xml/index.xml
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_SOURCE_DIR}/docs/doxygen/swig_doc.py
- ${OUTPUT_DIRECTORY}/xml
- ${output_file}
- WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/docs/doxygen
- )
-
- else(DOXYGEN_FOUND)
- file(WRITE ${output_file} "\n") #no doxygen -> empty file
- endif(DOXYGEN_FOUND)
-endfunction(GR_SWIG_MAKE_DOCS)
-
-########################################################################
-# Build a swig target for the common gnuradio use case. Usage:
-# GR_SWIG_MAKE(target ifile ifile ifile...)
-#
-# Set the following variables before calling:
-# - GR_SWIG_FLAGS
-# - GR_SWIG_INCLUDE_DIRS
-# - GR_SWIG_LIBRARIES
-# - GR_SWIG_SOURCE_DEPS
-# - GR_SWIG_TARGET_DEPS
-# - GR_SWIG_DOC_FILE
-# - GR_SWIG_DOC_DIRS
-########################################################################
-macro(GR_SWIG_MAKE name)
- set(ifiles ${ARGN})
-
- #do swig doc generation if specified
- if (GR_SWIG_DOC_FILE)
- set(GR_SWIG_DOCS_SOURCE_DEPS ${GR_SWIG_SOURCE_DEPS})
- set(GR_SWIG_DOCS_TAREGT_DEPS ${GR_SWIG_TARGET_DEPS})
- GR_SWIG_MAKE_DOCS(${GR_SWIG_DOC_FILE} ${GR_SWIG_DOC_DIRS})
- list(APPEND GR_SWIG_SOURCE_DEPS ${GR_SWIG_DOC_FILE})
- endif()
-
- #append additional include directories
- find_package(PythonLibs 2)
- list(APPEND GR_SWIG_INCLUDE_DIRS ${PYTHON_INCLUDE_PATH}) #deprecated name (now dirs)
- list(APPEND GR_SWIG_INCLUDE_DIRS ${PYTHON_INCLUDE_DIRS})
- list(APPEND GR_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR})
- list(APPEND GR_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR})
-
- #determine include dependencies for swig file
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE}
- ${CMAKE_BINARY_DIR}/get_swig_deps.py
- "${ifiles}" "${GR_SWIG_INCLUDE_DIRS}"
- OUTPUT_STRIP_TRAILING_WHITESPACE
- OUTPUT_VARIABLE SWIG_MODULE_${name}_EXTRA_DEPS
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- )
-
- #Create a dummy custom command that depends on other targets
- include(GrMiscUtils)
- GR_GEN_TARGET_DEPS(_${name}_swig_tag tag_deps ${GR_SWIG_TARGET_DEPS})
- set(tag_file ${CMAKE_CURRENT_BINARY_DIR}/${name}.tag)
- add_custom_command(
- OUTPUT ${tag_file}
- DEPENDS ${GR_SWIG_SOURCE_DEPS} ${tag_deps}
- COMMAND ${CMAKE_COMMAND} -E touch ${tag_file}
- )
-
- #append the specified include directories
- include_directories(${GR_SWIG_INCLUDE_DIRS})
- list(APPEND SWIG_MODULE_${name}_EXTRA_DEPS ${tag_file})
-
- #setup the swig flags with flags and include directories
- set(CMAKE_SWIG_FLAGS -fvirtual -modern -keyword -w511 -module ${name} ${GR_SWIG_FLAGS})
- foreach(dir ${GR_SWIG_INCLUDE_DIRS})
- list(APPEND CMAKE_SWIG_FLAGS "-I${dir}")
- endforeach(dir)
-
- #set the C++ property on the swig .i file so it builds
- set_source_files_properties(${ifiles} PROPERTIES CPLUSPLUS ON)
-
- #setup the actual swig library target to be built
- include(UseSWIG)
- SWIG_ADD_MODULE(${name} python ${ifiles})
- SWIG_LINK_LIBRARIES(${name} ${PYTHON_LIBRARIES} ${GR_SWIG_LIBRARIES})
-
-endmacro(GR_SWIG_MAKE)
-
-########################################################################
-# Install swig targets generated by GR_SWIG_MAKE. Usage:
-# GR_SWIG_INSTALL(
-# TARGETS target target target...
-# [DESTINATION destination]
-# [COMPONENT component]
-# )
-########################################################################
-macro(GR_SWIG_INSTALL)
-
- include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_SWIG_INSTALL "" "DESTINATION;COMPONENT" "TARGETS" ${ARGN})
-
- foreach(name ${GR_SWIG_INSTALL_TARGETS})
- install(TARGETS ${SWIG_MODULE_${name}_REAL_NAME}
- DESTINATION ${GR_SWIG_INSTALL_DESTINATION}
- COMPONENT ${GR_SWIG_INSTALL_COMPONENT}
- )
-
- include(GrPython)
- GR_PYTHON_INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${name}.py
- DESTINATION ${GR_SWIG_INSTALL_DESTINATION}
- COMPONENT ${GR_SWIG_INSTALL_COMPONENT}
- )
-
- GR_LIBTOOL(
- TARGET ${SWIG_MODULE_${name}_REAL_NAME}
- DESTINATION ${GR_SWIG_INSTALL_DESTINATION}
- )
-
- endforeach(name)
-
-endmacro(GR_SWIG_INSTALL)
-
-########################################################################
-# Generate a python file that can determine swig dependencies.
-# Used by the make macro above to determine extra dependencies.
-# When you build C++, CMake figures out the header dependencies.
-# This code essentially performs that logic for swig includes.
-########################################################################
-file(WRITE ${CMAKE_BINARY_DIR}/get_swig_deps.py "
-
-import os, sys, re
-
-include_matcher = re.compile('[#|%]include\\s*[<|\"](.*)[>|\"]')
-include_dirs = sys.argv[2].split(';')
-
-def get_swig_incs(file_path):
- file_contents = open(file_path, 'r').read()
- return include_matcher.findall(file_contents, re.MULTILINE)
-
-def get_swig_deps(file_path, level):
- deps = [file_path]
- if level == 0: return deps
- for inc_file in get_swig_incs(file_path):
- for inc_dir in include_dirs:
- inc_path = os.path.join(inc_dir, inc_file)
- if not os.path.exists(inc_path): continue
- deps.extend(get_swig_deps(inc_path, level-1))
- return deps
-
-if __name__ == '__main__':
- ifiles = sys.argv[1].split(';')
- deps = sum([get_swig_deps(ifile, 3) for ifile in ifiles], [])
- #sys.stderr.write(';'.join(set(deps)) + '\\n\\n')
- print(';'.join(set(deps)))
-")
diff --git a/cmake/Modules/GrTest.cmake b/cmake/Modules/GrTest.cmake
deleted file mode 100644
index 6174c03..0000000
--- a/cmake/Modules/GrTest.cmake
+++ /dev/null
@@ -1,133 +0,0 @@
-# Copyright 2010-2011 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-
-if(DEFINED __INCLUDED_GR_TEST_CMAKE)
- return()
-endif()
-set(__INCLUDED_GR_TEST_CMAKE TRUE)
-
-########################################################################
-# Add a unit test and setup the environment for a unit test.
-# Takes the same arguments as the ADD_TEST function.
-#
-# Before calling set the following variables:
-# GR_TEST_TARGET_DEPS - built targets for the library path
-# GR_TEST_LIBRARY_DIRS - directories for the library path
-# GR_TEST_PYTHON_DIRS - directories for the python path
-########################################################################
-function(GR_ADD_TEST test_name)
-
- if(WIN32)
- #Ensure that the build exe also appears in the PATH.
- list(APPEND GR_TEST_TARGET_DEPS ${ARGN})
-
- #In the land of windows, all libraries must be in the PATH.
- #Since the dependent libraries are not yet installed,
- #we must manually set them in the PATH to run tests.
- #The following appends the path of a target dependency.
- foreach(target ${GR_TEST_TARGET_DEPS})
- get_target_property(location ${target} LOCATION)
- if(location)
- get_filename_component(path ${location} PATH)
- string(REGEX REPLACE "\\$\\(.*\\)" ${CMAKE_BUILD_TYPE} path ${path})
- list(APPEND GR_TEST_LIBRARY_DIRS ${path})
- endif(location)
- endforeach(target)
-
- #SWIG generates the python library files into a subdirectory.
- #Therefore, we must append this subdirectory into PYTHONPATH.
- #Only do this for the python directories matching the following:
- foreach(pydir ${GR_TEST_PYTHON_DIRS})
- get_filename_component(name ${pydir} NAME)
- if(name MATCHES "^(swig|lib|src)$")
- list(APPEND GR_TEST_PYTHON_DIRS ${pydir}/${CMAKE_BUILD_TYPE})
- endif()
- endforeach(pydir)
- endif(WIN32)
-
- file(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR} srcdir)
- file(TO_NATIVE_PATH "${GR_TEST_LIBRARY_DIRS}" libpath) #ok to use on dir list?
- file(TO_NATIVE_PATH "${GR_TEST_PYTHON_DIRS}" pypath) #ok to use on dir list?
-
- set(environs "GR_DONT_LOAD_PREFS=1" "srcdir=${srcdir}")
-
- #http://www.cmake.org/pipermail/cmake/2009-May/029464.html
- #Replaced this add test + set environs code with the shell script generation.
- #Its nicer to be able to manually run the shell script to diagnose problems.
- #ADD_TEST(${ARGV})
- #SET_TESTS_PROPERTIES(${test_name} PROPERTIES ENVIRONMENT "${environs}")
-
- if(UNIX)
- set(binpath "${CMAKE_CURRENT_BINARY_DIR}:$PATH")
- #set both LD and DYLD paths to cover multiple UNIX OS library paths
- list(APPEND libpath "$LD_LIBRARY_PATH" "$DYLD_LIBRARY_PATH")
- list(APPEND pypath "$PYTHONPATH")
-
- #replace list separator with the path separator
- string(REPLACE ";" ":" libpath "${libpath}")
- string(REPLACE ";" ":" pypath "${pypath}")
- list(APPEND environs "PATH=${binpath}" "LD_LIBRARY_PATH=${libpath}" "DYLD_LIBRARY_PATH=${libpath}" "PYTHONPATH=${pypath}")
-
- #generate a bat file that sets the environment and runs the test
- find_program(SHELL sh)
- set(sh_file ${CMAKE_CURRENT_BINARY_DIR}/${test_name}_test.sh)
- file(WRITE ${sh_file} "#!${SHELL}\n")
- #each line sets an environment variable
- foreach(environ ${environs})
- file(APPEND ${sh_file} "export ${environ}\n")
- endforeach(environ)
- #load the command to run with its arguments
- foreach(arg ${ARGN})
- file(APPEND ${sh_file} "${arg} ")
- endforeach(arg)
- file(APPEND ${sh_file} "\n")
-
- #make the shell file executable
- execute_process(COMMAND chmod +x ${sh_file})
-
- add_test(${test_name} ${SHELL} ${sh_file})
-
- endif(UNIX)
-
- if(WIN32)
- list(APPEND libpath ${DLL_PATHS} "%PATH%")
- list(APPEND pypath "%PYTHONPATH%")
-
- #replace list separator with the path separator (escaped)
- string(REPLACE ";" "\\;" libpath "${libpath}")
- string(REPLACE ";" "\\;" pypath "${pypath}")
- list(APPEND environs "PATH=${libpath}" "PYTHONPATH=${pypath}")
-
- #generate a bat file that sets the environment and runs the test
- set(bat_file ${CMAKE_CURRENT_BINARY_DIR}/${test_name}_test.bat)
- file(WRITE ${bat_file} "@echo off\n")
- #each line sets an environment variable
- foreach(environ ${environs})
- file(APPEND ${bat_file} "SET ${environ}\n")
- endforeach(environ)
- #load the command to run with its arguments
- foreach(arg ${ARGN})
- file(APPEND ${bat_file} "${arg} ")
- endforeach(arg)
- file(APPEND ${bat_file} "\n")
-
- add_test(${test_name} ${bat_file})
- endif(WIN32)
-
-endfunction(GR_ADD_TEST)
diff --git a/gr3.8.patch b/gr3.8.patch
new file mode 100644
index 0000000..5aaaa84
--- /dev/null
+++ b/gr3.8.patch
@@ -0,0 +1,367 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 56f95f4..c43483a 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -4,6 +4,24 @@ project(gr-op25 CXX C)
+ set(CMAKE_BUILD_TYPE Debug)
+ set(CMAKE_CXX_FLAGS "-std=c++11")
+
++execute_process(COMMAND python3 -c "
++import os
++import sys
++from distutils import sysconfig
++pfx = '/usr/local'
++m1 = os.path.join('lib', 'python' + sys.version[:3], 'dist-packages')
++m2 = sysconfig.get_python_lib(plat_specific=True, prefix='')
++f1 = os.path.join(pfx, m1)
++f2 = os.path.join(pfx, m2)
++ok2 = f2 in sys.path
++if ok2:
++ print(m2)
++else:
++ print(m1)
++" OUTPUT_VARIABLE OP25_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE
++)
++MESSAGE(STATUS "OP25_PYTHON_DIR has been set to \"${OP25_PYTHON_DIR}\".")
++
+ add_subdirectory(op25/gr-op25)
+ add_subdirectory(op25/gr-op25_repeater)
+
+diff --git a/install.sh b/install.sh
+index 10fbeb5..4246447 100755
+--- a/install.sh
++++ b/install.sh
+@@ -10,9 +10,12 @@ if [ ! -d op25/gr-op25 ]; then
+ exit
+ fi
+
++sudo sed -i -- 's/^# *deb-src/deb-src/' /etc/apt/sources.list
++
+ sudo apt-get update
+ sudo apt-get build-dep gnuradio
+-sudo apt-get install gnuradio gnuradio-dev gr-osmosdr librtlsdr-dev libuhd-dev libhackrf-dev libitpp-dev libpcap-dev cmake git swig build-essential pkg-config doxygen python-numpy python-waitress python-requests
++sudo apt-get install gnuradio gnuradio-dev gr-osmosdr librtlsdr-dev libuhd-dev libhackrf-dev libitpp-dev libpcap-dev cmake git swig build-essential pkg-config doxygen python3-numpy python3-waitress python3-requests
++sudo apt-get install liborc-dev
+
+ mkdir build
+ cd build
+diff --git a/op25/gr-op25/CMakeLists.txt b/op25/gr-op25/CMakeLists.txt
+index 6c05df5..1c6fa23 100644
+--- a/op25/gr-op25/CMakeLists.txt
++++ b/op25/gr-op25/CMakeLists.txt
+@@ -68,6 +68,9 @@ endif()
+ ########################################################################
+ find_package(CppUnit)
+
++set(ENABLE_PYTHON "TRUE" CACHE BOOL "enable python")
++cmake_policy(SET CMP0012 NEW)
++
+ # To run a more advanced search for GNU Radio and it's components and
+ # versions, use the following. Add any components required to the list
+ # of GR_REQUIRED_COMPONENTS (in all caps) and change "version" to the
+@@ -76,11 +79,12 @@ find_package(CppUnit)
+ # set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER ...)
+ # find_package(Gnuradio "version")
+ set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
+-find_package(Gnuradio)
+-
+-if(NOT GNURADIO_RUNTIME_FOUND)
+- message(FATAL_ERROR "GnuRadio Runtime required to compile op25")
++SET(MIN_GR_VERSION "3.8.0")
++find_package(Gnuradio REQUIRED)
++if("${Gnuradio_VERSION}" VERSION_LESS MIN_GR_VERSION)
++ MESSAGE(FATAL_ERROR "GnuRadio version required: >=\"" ${MIN_GR_VERSION} "\" found: \"" ${Gnuradio_VERSION} "\"")
+ endif()
++
+ if(NOT CPPUNIT_FOUND)
+ message(FATAL_ERROR "CppUnit required to compile op25")
+ endif()
+diff --git a/op25/gr-op25/lib/CMakeLists.txt b/op25/gr-op25/lib/CMakeLists.txt
+index 1befdd9..609fa84 100644
+--- a/op25/gr-op25/lib/CMakeLists.txt
++++ b/op25/gr-op25/lib/CMakeLists.txt
+@@ -63,7 +63,7 @@ list(APPEND op25_sources
+ )
+
+ add_library(gnuradio-op25 SHARED ${op25_sources})
+-target_link_libraries(gnuradio-op25 ${Boost_LIBRARIES} ${GNURADIO_RUNTIME_LIBRARIES} itpp pcap)
++target_link_libraries(gnuradio-op25 ${Boost_LIBRARIES} gnuradio::gnuradio-runtime itpp pcap)
+ set_target_properties(gnuradio-op25 PROPERTIES DEFINE_SYMBOL "gnuradio_op25_EXPORTS")
+
+ ########################################################################
+diff --git a/op25/gr-op25/python/CMakeLists.txt b/op25/gr-op25/python/CMakeLists.txt
+index 03361a2..e497faa 100644
+--- a/op25/gr-op25/python/CMakeLists.txt
++++ b/op25/gr-op25/python/CMakeLists.txt
+@@ -31,7 +31,7 @@ endif()
+ GR_PYTHON_INSTALL(
+ FILES
+ __init__.py
+- DESTINATION ${GR_PYTHON_DIR}/op25
++ DESTINATION ${OP25_PYTHON_DIR}/op25
+ )
+
+ ########################################################################
+diff --git a/op25/gr-op25/swig/CMakeLists.txt b/op25/gr-op25/swig/CMakeLists.txt
+index e99226f..fd7bd85 100644
+--- a/op25/gr-op25/swig/CMakeLists.txt
++++ b/op25/gr-op25/swig/CMakeLists.txt
+@@ -21,7 +21,7 @@
+ # Include swig generation macros
+ ########################################################################
+ find_package(SWIG)
+-find_package(PythonLibs 2)
++find_package(PythonLibs 3)
+ if(NOT SWIG_FOUND OR NOT PYTHONLIBS_FOUND)
+ return()
+ endif()
+@@ -31,9 +31,7 @@ include(GrPython)
+ ########################################################################
+ # Setup swig generation
+ ########################################################################
+-foreach(incdir ${GNURADIO_RUNTIME_INCLUDE_DIRS})
+- list(APPEND GR_SWIG_INCLUDE_DIRS ${incdir}/gnuradio/swig)
+-endforeach(incdir)
++set(GR_SWIG_INCLUDE_DIRS $<TARGET_PROPERTY:gnuradio::runtime_swig,INTERFACE_INCLUDE_DIRECTORIES>)
+
+ set(GR_SWIG_LIBRARIES gnuradio-op25)
+ set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/op25_swig_doc.i)
+@@ -44,7 +42,7 @@ GR_SWIG_MAKE(op25_swig op25_swig.i)
+ ########################################################################
+ # Install the build swig module
+ ########################################################################
+-GR_SWIG_INSTALL(TARGETS op25_swig DESTINATION ${GR_PYTHON_DIR}/op25)
++GR_SWIG_INSTALL(TARGETS op25_swig DESTINATION ${OP25_PYTHON_DIR}/op25)
+
+ ########################################################################
+ # Install swig .i files for development
+diff --git a/op25/gr-op25_repeater/CMakeLists.txt b/op25/gr-op25_repeater/CMakeLists.txt
+index fa29b9e..dc1d8e7 100644
+--- a/op25/gr-op25_repeater/CMakeLists.txt
++++ b/op25/gr-op25_repeater/CMakeLists.txt
+@@ -68,6 +68,9 @@ endif()
+ ########################################################################
+ find_package(CppUnit)
+
++set(ENABLE_PYTHON "TRUE" CACHE BOOL "enable python")
++cmake_policy(SET CMP0012 NEW)
++
+ # To run a more advanced search for GNU Radio and it's components and
+ # versions, use the following. Add any components required to the list
+ # of GR_REQUIRED_COMPONENTS (in all caps) and change "version" to the
+@@ -75,11 +78,12 @@ find_package(CppUnit)
+ #
+ set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
+ # find_package(Gnuradio "version")
+-find_package(Gnuradio)
+-
+-if(NOT GNURADIO_RUNTIME_FOUND)
+- message(FATAL_ERROR "GnuRadio Runtime required to compile op25_repeater")
++set(MIN_GR_VERSION "3.8.0")
++find_package(Gnuradio REQUIRED)
++if("${Gnuradio_VERSION}" VERSION_LESS MIN_GR_VERSION)
++ MESSAGE(FATAL_ERROR "GnuRadio version required: >=\"" ${MIN_GR_VERSION} "\" found: \"" ${Gnuradio_VERSION} "\"")
+ endif()
++
+ if(NOT CPPUNIT_FOUND)
+ message(FATAL_ERROR "CppUnit required to compile op25_repeater")
+ endif()
+diff --git a/op25/gr-op25_repeater/apps/audio.py b/op25/gr-op25_repeater/apps/audio.py
+index 26cbe4f..255812f 100755
+--- a/op25/gr-op25_repeater/apps/audio.py
++++ b/op25/gr-op25_repeater/apps/audio.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2017, 2018 Graham Norbury
+ #
+diff --git a/op25/gr-op25_repeater/apps/http_server.py b/op25/gr-op25_repeater/apps/http_server.py
+index f402353..f4b047f 100755
+--- a/op25/gr-op25_repeater/apps/http_server.py
++++ b/op25/gr-op25_repeater/apps/http_server.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
+ #
+diff --git a/op25/gr-op25_repeater/apps/multi_rx.py b/op25/gr-op25_repeater/apps/multi_rx.py
+index e4c71ca..42625f5 100755
+--- a/op25/gr-op25_repeater/apps/multi_rx.py
++++ b/op25/gr-op25_repeater/apps/multi_rx.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
+ #
+diff --git a/op25/gr-op25_repeater/apps/rx.py b/op25/gr-op25_repeater/apps/rx.py
+index c671120..b226f8a 100755
+--- a/op25/gr-op25_repeater/apps/rx.py
++++ b/op25/gr-op25_repeater/apps/rx.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2008-2011 Steve Glass
+ #
+diff --git a/op25/gr-op25_repeater/apps/sockaudio.py b/op25/gr-op25_repeater/apps/sockaudio.py
+index 76282ac..68c6adb 100755
+--- a/op25/gr-op25_repeater/apps/sockaudio.py
++++ b/op25/gr-op25_repeater/apps/sockaudio.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2017, 2018 Graham Norbury
+ #
+diff --git a/op25/gr-op25_repeater/apps/terminal.py b/op25/gr-op25_repeater/apps/terminal.py
+index c732a3a..fa73af4 100755
+--- a/op25/gr-op25_repeater/apps/terminal.py
++++ b/op25/gr-op25_repeater/apps/terminal.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ # Copyright 2008-2011 Steve Glass
+ #
+diff --git a/op25/gr-op25_repeater/apps/tx/dv_tx.py b/op25/gr-op25_repeater/apps/tx/dv_tx.py
+index 342ba3f..fba399f 100755
+--- a/op25/gr-op25_repeater/apps/tx/dv_tx.py
++++ b/op25/gr-op25_repeater/apps/tx/dv_tx.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ #################################################################################
+ #
+diff --git a/op25/gr-op25_repeater/apps/tx/generate-tsbks.py b/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
+index f4b06d9..de3eb28 100755
+--- a/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
++++ b/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
+@@ -1,4 +1,4 @@
+-#! /usr/bin/python
++#! /usr/bin/python3
+
+ from p25craft import make_fakecc_tsdu
+
+diff --git a/op25/gr-op25_repeater/apps/tx/multi_tx.py b/op25/gr-op25_repeater/apps/tx/multi_tx.py
+index a54bc01..1707502 100755
+--- a/op25/gr-op25_repeater/apps/tx/multi_tx.py
++++ b/op25/gr-op25_repeater/apps/tx/multi_tx.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ #################################################################################
+ #
+diff --git a/op25/gr-op25_repeater/apps/tx/op25_tx.py b/op25/gr-op25_repeater/apps/tx/op25_tx.py
+index 3e7afe4..7baa6ae 100755
+--- a/op25/gr-op25_repeater/apps/tx/op25_tx.py
++++ b/op25/gr-op25_repeater/apps/tx/op25_tx.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+ #
+ # Copyright 2005,2006,2007 Free Software Foundation, Inc.
+ #
+diff --git a/op25/gr-op25_repeater/apps/tx/p25craft.py b/op25/gr-op25_repeater/apps/tx/p25craft.py
+index 7fae739..b6e3999 100755
+--- a/op25/gr-op25_repeater/apps/tx/p25craft.py
++++ b/op25/gr-op25_repeater/apps/tx/p25craft.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/python
++#!/usr/bin/python3
+ #
+ # p25craft.py - utility for crafting APCO P25 packets
+ #
+diff --git a/op25/gr-op25_repeater/apps/tx/unpack.py b/op25/gr-op25_repeater/apps/tx/unpack.py
+index 7cbf05b..73a861a 100755
+--- a/op25/gr-op25_repeater/apps/tx/unpack.py
++++ b/op25/gr-op25_repeater/apps/tx/unpack.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+ from gnuradio import gr, audio, eng_notation, blocks
+ from gnuradio.eng_option import eng_option
+ from optparse import OptionParser
+diff --git a/op25/gr-op25_repeater/apps/util/arb-resample.py b/op25/gr-op25_repeater/apps/util/arb-resample.py
+index 56a762f..2bf75af 100755
+--- a/op25/gr-op25_repeater/apps/util/arb-resample.py
++++ b/op25/gr-op25_repeater/apps/util/arb-resample.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ import sys
+ import math
+diff --git a/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py b/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
+index 051ddf0..171878d 100755
+--- a/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
++++ b/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/env python3
+
+ #
+ # (C) Copyright 2010, 2014 Max H. Parke, KA1RBI
+diff --git a/op25/gr-op25_repeater/lib/CMakeLists.txt b/op25/gr-op25_repeater/lib/CMakeLists.txt
+index da84e14..1464230 100644
+--- a/op25/gr-op25_repeater/lib/CMakeLists.txt
++++ b/op25/gr-op25_repeater/lib/CMakeLists.txt
+@@ -68,7 +68,7 @@ else(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ find_library(GR_FILTER_LIBRARY libgnuradio-filter.so )
+ endif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ set(GR_FILTER_LIBRARIES ${GR_FILTER_LIBRARY})
+-target_link_libraries(gnuradio-op25_repeater ${Boost_LIBRARIES} ${GNURADIO_RUNTIME_LIBRARIES} ${GR_FILTER_LIBRARIES} imbe_vocoder)
++target_link_libraries(gnuradio-op25_repeater ${Boost_LIBRARIES} gnuradio::gnuradio-runtime ${GR_FILTER_LIBRARIES} imbe_vocoder)
+ set_target_properties(gnuradio-op25_repeater PROPERTIES DEFINE_SYMBOL "gnuradio_op25_repeater_EXPORTS")
+
+ ########################################################################
+diff --git a/op25/gr-op25_repeater/python/CMakeLists.txt b/op25/gr-op25_repeater/python/CMakeLists.txt
+index 9958577..bb117a0 100644
+--- a/op25/gr-op25_repeater/python/CMakeLists.txt
++++ b/op25/gr-op25_repeater/python/CMakeLists.txt
+@@ -31,7 +31,7 @@ endif()
+ GR_PYTHON_INSTALL(
+ FILES
+ __init__.py
+- DESTINATION ${GR_PYTHON_DIR}/op25_repeater
++ DESTINATION ${OP25_PYTHON_DIR}/op25_repeater
+ )
+
+ ########################################################################
+diff --git a/op25/gr-op25_repeater/swig/CMakeLists.txt b/op25/gr-op25_repeater/swig/CMakeLists.txt
+index 1d88bbd..50819d7 100644
+--- a/op25/gr-op25_repeater/swig/CMakeLists.txt
++++ b/op25/gr-op25_repeater/swig/CMakeLists.txt
+@@ -21,7 +21,7 @@
+ # Include swig generation macros
+ ########################################################################
+ find_package(SWIG)
+-find_package(PythonLibs 2)
++find_package(PythonLibs 3)
+ if(NOT SWIG_FOUND OR NOT PYTHONLIBS_FOUND)
+ return()
+ endif()
+@@ -31,9 +31,7 @@ include(GrPython)
+ ########################################################################
+ # Setup swig generation
+ ########################################################################
+-foreach(incdir ${GNURADIO_RUNTIME_INCLUDE_DIRS})
+- list(APPEND GR_SWIG_INCLUDE_DIRS ${incdir}/gnuradio/swig)
+-endforeach(incdir)
++set(GR_SWIG_INCLUDE_DIRS $<TARGET_PROPERTY:gnuradio::runtime_swig,INTERFACE_INCLUDE_DIRECTORIES>)
+
+ set(GR_SWIG_LIBRARIES gnuradio-op25_repeater)
+ set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/op25_repeater_swig_doc.i)
+@@ -44,7 +42,7 @@ GR_SWIG_MAKE(op25_repeater_swig op25_repeater_swig.i)
+ ########################################################################
+ # Install the build swig module
+ ########################################################################
+-GR_SWIG_INSTALL(TARGETS op25_repeater_swig DESTINATION ${GR_PYTHON_DIR}/op25_repeater)
++GR_SWIG_INSTALL(TARGETS op25_repeater_swig DESTINATION ${OP25_PYTHON_DIR}/op25_repeater)
+
+ ########################################################################
+ # Install swig .i files for development
diff --git a/install-gr3.9.sh b/install-gr3.9.sh
new file mode 100755
index 0000000..70eadd5
--- /dev/null
+++ b/install-gr3.9.sh
@@ -0,0 +1,72 @@
+#! /bin/bash
+
+# op25 install script for debian based systems
+# including ubuntu 14/16 and raspbian
+#
+# *** this script for gnuradio 3.9 and 3.10 ***
+
+TREE_DIR="$PWD/src" # directory in which our gr3.9 tree will be built
+
+if [ ! -d op25/gr-op25 ]; then
+ echo ====== error, op25 top level directories not found
+ echo ====== you must change to the op25 top level directory
+ echo ====== before running this script
+ exit
+fi
+
+TOP_DIR=$PWD
+
+sudo apt-get update
+sudo apt-get build-dep gnuradio
+sudo apt-get install gnuradio gnuradio-dev gr-osmosdr librtlsdr-dev libuhd-dev libhackrf-dev libitpp-dev libpcap-dev cmake git swig build-essential pkg-config doxygen python3-numpy python3-waitress python3-requests python3-pip pybind11-dev clang-format libsndfile1-dev
+
+# setup and populate gr3.9 src tree
+echo
+echo " = = = = = = = generating source tree for gr3.9, this could take a while = = = = = = ="
+echo
+python3 add_gr3.9.py $PWD $TREE_DIR
+if [ ! -d $TREE_DIR ]; then
+ echo ==== Error, directory $TREE_DIR creation failed, exiting
+ exit 1
+fi
+
+cd $TREE_DIR
+
+mkdir build
+cd build
+cmake ../op25/gr-op25
+make
+sudo make install
+sudo ldconfig
+cd ../
+
+mkdir build_repeater
+cd build_repeater
+cmake ../op25/gr-op25_repeater
+make
+sudo make install
+sudo ldconfig
+cd ../
+
+cd $TOP_DIR/op25
+sh ../scripts/do_sedpy.sh
+
+echo ======
+echo ====== NOTICE
+echo ======
+echo ====== The gnuplot package is not installed by default here,
+echo ====== as its installation requires numerous prerequisite packages
+echo ====== that you may not want to install.
+echo ======
+echo ====== In order to do plotting in rx.py using the \-P option
+echo ====== you must install gnuplot, e.g., manually as follows:
+echo ======
+echo ====== sudo apt-get install gnuplot-x11
+echo ======
+echo ======
+echo ====== Separately, we suggest you set device and driver permissions:
+echo ====== \$ cd scripts
+echo ====== \$ ./udev_rules.sh
+echo ====== It is only necessary to do this once. Currently this script
+echo ====== handles the rtl-sdr and airspy only.
+echo ======
diff --git a/install.sh b/install.sh
index 042d07e..771de20 100755
--- a/install.sh
+++ b/install.sh
@@ -10,9 +10,12 @@ if [ ! -d op25/gr-op25 ]; then
exit
fi
+sudo sed -i -- 's/^# *deb-src/deb-src/' /etc/apt/sources.list
+
sudo apt-get update
sudo apt-get build-dep gnuradio
-sudo apt-get install gnuradio gnuradio-dev gr-osmosdr librtlsdr-dev libuhd-dev libhackrf-dev libitpp-dev libpcap-dev git
+sudo apt-get install gnuradio gnuradio-dev gr-osmosdr librtlsdr-dev libuhd-dev libhackrf-dev libitpp-dev libpcap-dev cmake git swig build-essential pkg-config doxygen python3-numpy python3-waitress python3-requests
+sudo apt-get install liborc-dev
mkdir build
cd build
@@ -20,3 +23,23 @@ cmake ../
make
sudo make install
sudo ldconfig
+
+echo ======
+echo ====== NOTICE
+echo ======
+echo ====== The gnuplot package is not installed by default here,
+echo ====== as its installation requires numerous prerequisite packages
+echo ====== that you may not want to install.
+echo ======
+echo ====== In order to do plotting in rx.py using the \-P option
+echo ====== you must install gnuplot, e.g., manually as follows:
+echo ======
+echo ====== sudo apt-get install gnuplot-x11
+echo ======
+echo ======
+echo ====== Separately, we suggest you set device and driver permissions:
+echo ====== \$ cd scripts
+echo ====== \$ ./udev_rules.sh
+echo ====== It is only necessary to do this once. Currently this script
+echo ====== handles the rtl-sdr and airspy only.
+echo ======
diff --git a/op25/gr-op25/CMakeLists.txt b/op25/gr-op25/CMakeLists.txt
index f5edd4f..1c6fa23 100644
--- a/op25/gr-op25/CMakeLists.txt
+++ b/op25/gr-op25/CMakeLists.txt
@@ -64,28 +64,13 @@ if(NOT Boost_FOUND)
endif()
########################################################################
-# Install directories
-########################################################################
-include(GrPlatform) #define LIB_SUFFIX
-set(GR_RUNTIME_DIR bin)
-set(GR_LIBRARY_DIR lib${LIB_SUFFIX})
-set(GR_INCLUDE_DIR include/op25)
-set(GR_DATA_DIR share)
-set(GR_PKG_DATA_DIR ${GR_DATA_DIR}/${CMAKE_PROJECT_NAME})
-set(GR_DOC_DIR ${GR_DATA_DIR}/doc)
-set(GR_PKG_DOC_DIR ${GR_DOC_DIR}/${CMAKE_PROJECT_NAME})
-set(GR_CONF_DIR etc)
-set(GR_PKG_CONF_DIR ${GR_CONF_DIR}/${CMAKE_PROJECT_NAME}/conf.d)
-set(GR_LIBEXEC_DIR libexec)
-set(GR_PKG_LIBEXEC_DIR ${GR_LIBEXEC_DIR}/${CMAKE_PROJECT_NAME})
-set(GRC_BLOCKS_DIR ${GR_PKG_DATA_DIR}/grc/blocks)
-
-########################################################################
# Find gnuradio build dependencies
########################################################################
-find_package(GnuradioRuntime)
find_package(CppUnit)
+set(ENABLE_PYTHON "TRUE" CACHE BOOL "enable python")
+cmake_policy(SET CMP0012 NEW)
+
# To run a more advanced search for GNU Radio and it's components and
# versions, use the following. Add any components required to the list
# of GR_REQUIRED_COMPONENTS (in all caps) and change "version" to the
@@ -93,19 +78,35 @@ find_package(CppUnit)
#
# set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER ...)
# find_package(Gnuradio "version")
-if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
- set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
- find_package(Gnuradio)
-endif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
-
-if(NOT GNURADIO_RUNTIME_FOUND)
- message(FATAL_ERROR "GnuRadio Runtime required to compile op25")
+set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
+SET(MIN_GR_VERSION "3.8.0")
+find_package(Gnuradio REQUIRED)
+if("${Gnuradio_VERSION}" VERSION_LESS MIN_GR_VERSION)
+ MESSAGE(FATAL_ERROR "GnuRadio version required: >=\"" ${MIN_GR_VERSION} "\" found: \"" ${Gnuradio_VERSION} "\"")
endif()
+
if(NOT CPPUNIT_FOUND)
message(FATAL_ERROR "CppUnit required to compile op25")
endif()
########################################################################
+# Install directories
+########################################################################
+include(GrPlatform) #define LIB_SUFFIX
+set(GR_RUNTIME_DIR bin)
+set(GR_LIBRARY_DIR lib${LIB_SUFFIX})
+set(GR_INCLUDE_DIR include/op25)
+set(GR_DATA_DIR share)
+set(GR_PKG_DATA_DIR ${GR_DATA_DIR}/${CMAKE_PROJECT_NAME})
+set(GR_DOC_DIR ${GR_DATA_DIR}/doc)
+set(GR_PKG_DOC_DIR ${GR_DOC_DIR}/${CMAKE_PROJECT_NAME})
+set(GR_CONF_DIR etc)
+set(GR_PKG_CONF_DIR ${GR_CONF_DIR}/${CMAKE_PROJECT_NAME}/conf.d)
+set(GR_LIBEXEC_DIR libexec)
+set(GR_PKG_LIBEXEC_DIR ${GR_LIBEXEC_DIR}/${CMAKE_PROJECT_NAME})
+set(GRC_BLOCKS_DIR ${GR_PKG_DATA_DIR}/grc/blocks)
+
+########################################################################
# Setup the include and linker paths
########################################################################
include_directories(
diff --git a/op25/gr-op25/grc/op25_decoder_ff.xml b/op25/gr-op25/grc/op25_decoder_ff.xml
index c503081..2b3ef88 100644
--- a/op25/gr-op25/grc/op25_decoder_ff.xml
+++ b/op25/gr-op25/grc/op25_decoder_ff.xml
@@ -4,17 +4,17 @@
<key>op25_decoder_ff</key>
<category>op25</category>
<import>import op25</import>
- <make>op25.decoder_ff($)</make>
+ <make>op25.decoder_ff()</make>
<!-- Make one 'param' node for every Parameter you want settable from the GUI.
Sub-nodes:
* name
* key (makes the value accessible as $keyname, e.g. in the make node)
* type -->
- <param>
+ <!--<param>
<name>...</name>
<key>...</key>
<type>...</type>
- </param>
+ </param>-->
<!-- Make one 'sink' node per input. Sub-nodes:
* name (an identifier for the GUI)
@@ -23,7 +23,7 @@
* optional (set to 1 for optional inputs) -->
<sink>
<name>in</name>
- <type><!-- e.g. int, float, complex, byte, short, xxx_vector, ...--></type>
+ <type>float</type>
</sink>
<!-- Make one 'source' node per output. Sub-nodes:
@@ -32,7 +32,7 @@
* vlen
* optional (set to 1 for optional inputs) -->
<source>
- <name>out</name>
- <type><!-- e.g. int, float, complex, byte, short, xxx_vector, ...--></type>
+ <name>audio</name>
+ <type>float</type>
</source>
</block>
diff --git a/op25/gr-op25/grc/op25_fsk4_demod_ff.xml b/op25/gr-op25/grc/op25_fsk4_demod_ff.xml
index 5c970dc..7354502 100644
--- a/op25/gr-op25/grc/op25_fsk4_demod_ff.xml
+++ b/op25/gr-op25/grc/op25_fsk4_demod_ff.xml
@@ -4,7 +4,7 @@
<key>op25_fsk4_demod_ff</key>
<category>op25</category>
<import>import op25</import>
- <make>op25.fsk4_demod_ff(self.auto_tune_msgq, $sample_rate, $symbol_rate)</make>
+ <make>op25.fsk4_demod_ff($(id)_msgq_out, $sample_rate, $symbol_rate)</make>
<param>
<name>Sample Rate</name>
@@ -20,7 +20,8 @@
<type>real</type>
</param>
- <param>
+ <!-- Must connect tune message queue as the block expects a queue as first argument! -->
+ <!--<param>
<name>Output Auto Tune</name>
<key>tune_out</key>
<value>True</value>
@@ -34,7 +35,7 @@
<name>No</name>
<key>False</key>
</option>
- </param>
+ </param>-->
<sink>
<name>in</name>
@@ -45,4 +46,10 @@
<name>dibits</name>
<type>float</type>
</source>
+
+ <source>
+ <name>tune</name>
+ <type>msg</type>
+ <!--<optional>1</optional>-->
+ </source>
</block>
diff --git a/op25/gr-op25/include/op25/decoder_bf.h b/op25/gr-op25/include/op25/decoder_bf.h
index ca74ad3..a964244 100644
--- a/op25/gr-op25/include/op25/decoder_bf.h
+++ b/op25/gr-op25/include/op25/decoder_bf.h
@@ -51,7 +51,7 @@ namespace gr {
* class. op25::decoder_bf::make is the public interface for
* creating new instances.
*/
- static sptr make();
+ static sptr make(bool idle_silence = true, bool verbose = false);
/**
* Return a pointer to a string identifying the destination of
@@ -78,6 +78,17 @@ namespace gr {
* message queue.
*/
virtual void set_msgq(gr::msg_queue::sptr msgq) = 0;
+
+ virtual void set_idle_silence(bool idle_silence = true) = 0;
+
+ virtual void set_logging(bool verbose = true) = 0;
+
+ typedef std::vector<uint8_t> key_type;
+ typedef std::map<uint16_t, key_type> key_map_type;
+
+ virtual void set_key(const key_type& key) = 0;
+
+ virtual void set_key_map(const key_map_type& keys) = 0;
};
} // namespace op25
diff --git a/op25/gr-op25/include/op25/message.h b/op25/gr-op25/include/op25/message.h
new file mode 100644
index 0000000..6805963
--- /dev/null
+++ b/op25/gr-op25/include/op25/message.h
@@ -0,0 +1,82 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005,2013 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifndef INCLUDED_OP25_MESSAGE_H
+#define INCLUDED_OP25_MESSAGE_H
+
+#include <op25/api.h>
+#include <gnuradio/types.h>
+#include <string>
+
+namespace gr {
+namespace op25 {
+
+/*!
+ * \brief Message class.
+ *
+ * \ingroup misc
+ * The ideas and method names for adjustable message length were
+ * lifted from the click modular router "Packet" class.
+ */
+class OP25_API message
+{
+public:
+ typedef std::shared_ptr<message> sptr;
+
+private:
+ sptr d_next; // link field for msg queue
+ long d_type; // type of the message
+ double d_arg1; // optional arg1
+ double d_arg2; // optional arg2
+
+ std::vector<unsigned char> d_buf;
+ unsigned char* d_msg_start; // where the msg starts
+ unsigned char* d_msg_end; // one beyond end of msg
+
+ message(long type, double arg1, double arg2, size_t length);
+
+ friend class msg_queue;
+
+ unsigned char* buf_data() { return d_buf.data(); }
+ size_t buf_len() const { return d_buf.size(); }
+
+public:
+ /*!
+ * \brief public constructor for message
+ */
+ static sptr make(long type = 0, double arg1 = 0, double arg2 = 0, size_t length = 0);
+
+ static sptr make_from_string(const std::string s,
+ long type = 0,
+ double arg1 = 0,
+ double arg2 = 0);
+
+
+ ~message();
+
+ long type() const { return d_type; }
+ double arg1() const { return d_arg1; }
+ double arg2() const { return d_arg2; }
+
+ void set_type(long type) { d_type = type; }
+ void set_arg1(double arg1) { d_arg1 = arg1; }
+ void set_arg2(double arg2) { d_arg2 = arg2; }
+
+ unsigned char* msg() const { return d_msg_start; }
+ size_t length() const { return d_msg_end - d_msg_start; }
+ std::string to_string() const;
+};
+
+OP25_API long message_ncurrently_allocated();
+
+} /* namespace op25 */
+} /* namespace gr */
+
+#endif /* INCLUDED_OP25_MESSAGE_H */
diff --git a/op25/gr-op25/include/op25/msg_handler.h b/op25/gr-op25/include/op25/msg_handler.h
new file mode 100644
index 0000000..329860c
--- /dev/null
+++ b/op25/gr-op25/include/op25/msg_handler.h
@@ -0,0 +1,39 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005,2013 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifndef INCLUDED_OP25_MSG_HANDLER_H
+#define INCLUDED_OP25_MSG_HANDLER_H
+
+#include <op25/api.h>
+#include <op25/message.h>
+
+namespace gr {
+namespace op25 {
+
+class msg_handler;
+typedef std::shared_ptr<msg_handler> msg_handler_sptr;
+
+/*!
+ * \brief abstract class of message handlers
+ * \ingroup base
+ */
+class OP25_API msg_handler
+{
+public:
+ virtual ~msg_handler();
+
+ //! handle \p msg
+ virtual void handle(message::sptr msg) = 0;
+};
+
+} /* namespace op25 */
+} /* namespace gr */
+
+#endif /* INCLUDED_OP25_MSG_HANDLER_H */
diff --git a/op25/gr-op25/include/op25/msg_queue.h b/op25/gr-op25/include/op25/msg_queue.h
new file mode 100644
index 0000000..d4ed002
--- /dev/null
+++ b/op25/gr-op25/include/op25/msg_queue.h
@@ -0,0 +1,85 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005,2009 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifndef INCLUDED_OP25_MSG_QUEUE_H
+#define INCLUDED_OP25_MSG_QUEUE_H
+
+#include <op25/api.h>
+#include <op25/msg_handler.h>
+#include <gnuradio/thread/thread.h>
+
+namespace gr {
+namespace op25 {
+
+/*!
+ * \brief thread-safe message queue
+ * \ingroup misc
+ */
+class OP25_API msg_queue : public msg_handler
+{
+ gr::thread::mutex d_mutex;
+ gr::thread::condition_variable d_not_empty;
+ gr::thread::condition_variable d_not_full;
+ message::sptr d_head;
+ message::sptr d_tail;
+ unsigned int d_count; // # of messages in queue.
+ unsigned int d_limit; // max # of messages in queue. 0 -> unbounded
+
+public:
+ typedef std::shared_ptr<msg_queue> sptr;
+
+ static sptr make(unsigned int limit = 0);
+
+ msg_queue(unsigned int limit);
+ ~msg_queue() override;
+
+ //! Generic msg_handler method: insert the message.
+ void handle(message::sptr msg) override { insert_tail(msg); }
+
+ /*!
+ * \brief Insert message at tail of queue.
+ * \param msg message
+ *
+ * Block if queue if full.
+ */
+ void insert_tail(message::sptr msg);
+
+ /*!
+ * \brief Delete message from head of queue and return it.
+ * Block if no message is available.
+ */
+ message::sptr delete_head();
+
+ /*!
+ * \brief If there's a message in the q, delete it and return it.
+ * If no message is available, return 0.
+ */
+ message::sptr delete_head_nowait();
+
+ //! Delete all messages from the queue
+ void flush();
+
+ //! is the queue empty?
+ bool empty_p() const { return d_count == 0; }
+
+ //! is the queue full?
+ bool full_p() const { return d_limit != 0 && d_count >= d_limit; }
+
+ //! return number of messages in queue
+ unsigned int count() const { return d_count; }
+
+ //! return limit on number of message in queue. 0 -> unbounded
+ unsigned int limit() const { return d_limit; }
+};
+
+} /* namespace op25 */
+} /* namespace gr */
+
+#endif /* INCLUDED_OP25_MSG_QUEUE_H */
diff --git a/op25/gr-op25/lib/CMakeLists.txt b/op25/gr-op25/lib/CMakeLists.txt
index 255ef93..609fa84 100644
--- a/op25/gr-op25/lib/CMakeLists.txt
+++ b/op25/gr-op25/lib/CMakeLists.txt
@@ -53,10 +53,17 @@ list(APPEND op25_sources
value_string.cc
pickle.cc
pcap_source_b_impl.cc
+ bch.cc
+ ldu.cc
+ crypto.cc
+ crypto_module_du_handler.cc
+ deskey.c
+ desport.c
+ dessp.c
)
add_library(gnuradio-op25 SHARED ${op25_sources})
-target_link_libraries(gnuradio-op25 ${Boost_LIBRARIES} ${GNURADIO_RUNTIME_LIBRARIES} itpp pcap)
+target_link_libraries(gnuradio-op25 ${Boost_LIBRARIES} gnuradio::gnuradio-runtime itpp pcap)
set_target_properties(gnuradio-op25 PROPERTIES DEFINE_SYMBOL "gnuradio_op25_EXPORTS")
########################################################################
diff --git a/op25/gr-op25/lib/abstract_data_unit.cc b/op25/gr-op25/lib/abstract_data_unit.cc
index 74bbfad..3b03efb 100644
--- a/op25/gr-op25/lib/abstract_data_unit.cc
+++ b/op25/gr-op25/lib/abstract_data_unit.cc
@@ -55,10 +55,10 @@ abstract_data_unit::correct_errors()
}
void
-abstract_data_unit::decode_audio(imbe_decoder& imbe)
+abstract_data_unit::decode_audio(imbe_decoder& imbe, crypto_module::sptr crypto_mod)
{
if(is_complete()) {
- do_decode_audio(d_frame_body, imbe);
+ do_decode_audio(d_frame_body, imbe, crypto_mod);
} else {
ostringstream msg;
msg << "cannot decode audio - frame is not complete" << endl;
@@ -153,7 +153,8 @@ abstract_data_unit::dump(ostream& os) const
}
abstract_data_unit::abstract_data_unit(const_bit_queue& frame_body) :
- d_frame_body(frame_body.size())
+ d_frame_body(frame_body.size()),
+ d_logging_enabled(false)
{
copy(frame_body.begin(), frame_body.end(), d_frame_body.begin());
}
@@ -164,7 +165,7 @@ abstract_data_unit::do_correct_errors(bit_vector& frame_body)
}
void
-abstract_data_unit::do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe)
+abstract_data_unit::do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe, crypto_module::sptr crypto_mod)
{
}
@@ -179,3 +180,15 @@ abstract_data_unit::frame_size() const
{
return d_frame_body.size();
}
+
+void
+abstract_data_unit::set_logging(bool on)
+{
+ d_logging_enabled = on;
+}
+
+bool
+abstract_data_unit::logging_enabled() const
+{
+ return d_logging_enabled;
+}
diff --git a/op25/gr-op25/lib/abstract_data_unit.h b/op25/gr-op25/lib/abstract_data_unit.h
index d4fb7f2..1f4ae27 100644
--- a/op25/gr-op25/lib/abstract_data_unit.h
+++ b/op25/gr-op25/lib/abstract_data_unit.h
@@ -26,6 +26,7 @@
#include "data_unit.h"
#include "op25_yank.h"
+#include "crypto.h"
#include <string>
#include <vector>
@@ -62,7 +63,7 @@ public:
* \precondition is_complete() == true.
* \param imbe The imbe_decoder to use to generate the audio.
*/
- virtual void decode_audio(imbe_decoder& imbe);
+ virtual void decode_audio(imbe_decoder& imbe, crypto_module::sptr crypto_mod);
/**
* Decode the frame into an octet vector.
@@ -117,6 +118,15 @@ public:
*/
virtual std::string snapshot() const;
+ /**
+ * Returns a string describing the Data Unit ID (DUID).
+ *
+ * \return A string identifying the DUID.
+ */
+ virtual std::string duid_str() const = 0;
+
+ virtual void set_logging(bool on);
+
protected:
/**
@@ -140,7 +150,7 @@ protected:
* \param frame_body The const_bit_vector to decode.
* \param imbe The imbe_decoder to use.
*/
- virtual void do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe);
+ virtual void do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe, crypto_module::sptr crypto_mod);
/**
* Decode frame_body and write the decoded frame contents to msg.
@@ -153,13 +163,6 @@ protected:
virtual size_t decode_frame(const_bit_vector& frame_body, size_t msg_sz, uint8_t *msg);
/**
- * Returns a string describing the Data Unit ID (DUID).
- *
- * \return A string identifying the DUID.
- */
- virtual std::string duid_str() const = 0;
-
- /**
* Return a reference to the frame body.
*/
const_bit_vector& frame_body() const;
@@ -180,6 +183,8 @@ protected:
*/
virtual uint16_t frame_size() const;
+ virtual bool logging_enabled() const;
+
private:
/**
@@ -187,6 +192,7 @@ private:
*/
bit_vector d_frame_body;
+ bool d_logging_enabled;
};
#endif /* INCLUDED_ABSTRACT_DATA_UNIT_H */
diff --git a/op25/gr-op25/lib/bch.cc b/op25/gr-op25/lib/bch.cc
new file mode 100644
index 0000000..e2e58a7
--- /dev/null
+++ b/op25/gr-op25/lib/bch.cc
@@ -0,0 +1,162 @@
+
+#include <stdio.h>
+#include <vector>
+#include "bch.h"
+/*
+ * Copyright 2010, KA1RBI
+ */
+static const int bchGFexp[64] = {
+ 1, 2, 4, 8, 16, 32, 3, 6, 12, 24, 48, 35, 5, 10, 20, 40,
+ 19, 38, 15, 30, 60, 59, 53, 41, 17, 34, 7, 14, 28, 56, 51, 37,
+ 9, 18, 36, 11, 22, 44, 27, 54, 47, 29, 58, 55, 45, 25, 50, 39,
+ 13, 26, 52, 43, 21, 42, 23, 46, 31, 62, 63, 61, 57, 49, 33, 0
+};
+
+static const int bchGFlog[64] = {
+ -1, 0, 1, 6, 2, 12, 7, 26, 3, 32, 13, 35, 8, 48, 27, 18,
+ 4, 24, 33, 16, 14, 52, 36, 54, 9, 45, 49, 38, 28, 41, 19, 56,
+ 5, 62, 25, 11, 34, 31, 17, 47, 15, 23, 53, 51, 37, 44, 55, 40,
+ 10, 61, 46, 30, 50, 22, 39, 43, 29, 60, 42, 21, 20, 59, 57, 58
+};
+
+static const int bchG[48] = {
+ 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0,
+ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,
+ 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1
+};
+
+int bchDec(bit_vector& Codeword)
+{
+
+ int elp[24][ 22], S[23];
+ int D[23], L[24], uLu[24];
+ int root[11], locn[11], reg[12];
+ int i,j,U,q,count;
+ int SynError, CantDecode;
+
+ SynError = 0; CantDecode = 0;
+
+ for(i = 1; i <= 22; i++) {
+ S[i] = 0;
+ // FOR j = 0 TO 62
+ for(j = 0; j <= 62; j++) {
+ if( Codeword[j]) { S[i] = S[i] ^ bchGFexp[(i * j) % 63]; }
+ }
+ if( S[i]) { SynError = 1; }
+ S[i] = bchGFlog[S[i]];
+ // printf("S[%d] %d\n", i, S[i]);
+ }
+
+ if( SynError) { //if there are errors, try to correct them
+ L[0] = 0; uLu[0] = -1; D[0] = 0; elp[0][ 0] = 0;
+ L[1] = 0; uLu[1] = 0; D[1] = S[1]; elp[1][ 0] = 1;
+ //FOR i = 1 TO 21
+ for(i = 1; i <= 21; i++) {
+ elp[0][ i] = -1; elp[1][ i] = 0;
+ }
+ U = 0;
+
+ do {
+ U = U + 1;
+ if( D[U] == -1) {
+ L[U + 1] = L[U];
+ // FOR i = 0 TO L[U]
+ for(i = 0; i <= L[U]; i++) {
+ elp[U + 1][ i] = elp[U][ i]; elp[U][ i] = bchGFlog[elp[U][ i]];
+ }
+ } else {
+ //search for words with greatest uLu(q) for which d(q)!=0
+ q = U - 1;
+ while((D[q] == -1) &&(q > 0)) { q = q - 1; }
+ //have found first non-zero d(q)
+ if( q > 0) {
+ j = q;
+ do { j = j - 1; if((D[j] != -1) &&(uLu[q] < uLu[j])) { q = j; }
+ } while( j > 0) ;
+ }
+
+ //store degree of new elp polynomial
+ if( L[U] > L[q] + U - q) {
+ L[U + 1] = L[U] ;
+ } else {
+ L[U + 1] = L[q] + U - q;
+ }
+
+ ///* form new elp(x) */
+ // FOR i = 0 TO 21
+ for(i = 0; i <= 21; i++) {
+ elp[U + 1][ i] = 0;
+ }
+ // FOR i = 0 TO L(q)
+ for(i = 0; i <= L[q]; i++) {
+ if( elp[q][ i] != -1) {
+ elp[U + 1][ i + U - q] = bchGFexp[(D[U] + 63 - D[q] + elp[q][ i]) % 63];
+ }
+ }
+ // FOR i = 0 TO L(U)
+ for(i = 0; i <= L[U]; i++) {
+ elp[U + 1][ i] = elp[U + 1][ i] ^ elp[U][ i];
+ elp[U][ i] = bchGFlog[elp[U][ i]];
+ }
+ }
+ uLu[U + 1] = U - L[U + 1];
+
+ //form(u+1)th discrepancy
+ if( U < 22) {
+ //no discrepancy computed on last iteration
+ if( S[U + 1] != -1) { D[U + 1] = bchGFexp[S[U + 1]]; } else { D[U + 1] = 0; }
+ // FOR i = 1 TO L(U + 1)
+ for(i = 1; i <= L[U + 1]; i++) {
+ if((S[U + 1 - i] != -1) &&(elp[U + 1][ i] != 0)) {
+ D[U + 1] = D[U + 1] ^ bchGFexp[(S[U + 1 - i] + bchGFlog[elp[U + 1][ i]]) % 63];
+ }
+ }
+ //put d(u+1) into index form */
+ D[U + 1] = bchGFlog[D[U + 1]];
+ }
+ } while((U < 22) &&(L[U + 1] <= 11));
+
+ U = U + 1;
+ if( L[U] <= 11) { // /* Can correct errors */
+ //put elp into index form
+ // FOR i = 0 TO L[U]
+ for(i = 0; i <= L[U]; i++) {
+ elp[U][ i] = bchGFlog[elp[U][ i]];
+ }
+
+ //Chien search: find roots of the error location polynomial
+ // FOR i = 1 TO L(U)
+ for(i = 1; i <= L[U]; i++) {
+ reg[i] = elp[U][ i];
+ }
+ count = 0;
+ // FOR i = 1 TO 63
+ for(i = 1; i <= 63; i++) {
+ q = 1;
+ //FOR j = 1 TO L(U)
+ for(j = 1; j <= L[U]; j++) {
+ if( reg[j] != -1) {
+ reg[j] =(reg[j] + j) % 63; q = q ^ bchGFexp[reg[j]];
+ }
+ }
+ if( q == 0) { //store root and error location number indices
+ root[count] = i; locn[count] = 63 - i; count = count + 1;
+ }
+ }
+ if( count == L[U]) {
+ //no. roots = degree of elp hence <= t errors
+ //FOR i = 0 TO L[U] - 1
+ for(i = 0; i <= L[U]-1; i++) {
+ Codeword[locn[i]] = Codeword[locn[i]] ^ 1;
+ }
+ CantDecode = count;
+ } else { //elp has degree >t hence cannot solve
+ CantDecode = -1;
+ }
+ } else {
+ CantDecode = -2;
+ }
+ }
+ return CantDecode;
+}
+
diff --git a/op25/gr-op25/lib/bch.h b/op25/gr-op25/lib/bch.h
new file mode 100644
index 0000000..d151405
--- /dev/null
+++ b/op25/gr-op25/lib/bch.h
@@ -0,0 +1,4 @@
+#include <vector>
+typedef std::vector<bool> bit_vector;
+int bchDec(bit_vector& Codeword);
+
diff --git a/op25/gr-op25/lib/crypto.cc b/op25/gr-op25/lib/crypto.cc
new file mode 100644
index 0000000..c67770c
--- /dev/null
+++ b/op25/gr-op25/lib/crypto.cc
@@ -0,0 +1,286 @@
+#include "crypto.h"
+
+#include <sstream>
+#include <boost/format.hpp>
+#include <iostream>
+#include <stdio.h>
+#include <memory.h>
+
+extern "C" {
+#include "des.h"
+}
+
+static unsigned long long swap_bytes(uint64_t l)
+{
+ unsigned long long r;
+ unsigned char* pL = (unsigned char*)&l;
+ unsigned char* pR = (unsigned char*)&r;
+ for (int i = 0; i < sizeof(l); ++i)
+ pR[i] = pL[(sizeof(l) - 1) - i];
+ return r;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+/*
+class null_algorithm : public crypto_algorithm // This is an algorithm skeleton (can be used for no encryption as pass-through)
+{
+private:
+ size_t m_generated_bits;
+public:
+ null_algorithm()
+ : m_generated_bits(0)
+ {
+ }
+ const type_id id() const
+ {
+ return crypto_algorithm::NONE;
+ }
+ bool update(const struct CryptoState& state)
+ {
+ fprintf(stderr, "NULL:\t%d bits generated\n", m_generated_bits);
+
+ m_generated_bits = 0;
+
+ return true;
+ }
+ bool set_key(const crypto_algorithm::key_type& key)
+ {
+ return true;
+ }
+ uint64_t generate(size_t n)
+ {
+ m_generated_bits += n;
+ return 0;
+ }
+};
+*/
+///////////////////////////////////////////////////////////////////////////////
+
+class des_ofb : public crypto_algorithm
+{
+public:
+ unsigned long long m_key_des, m_next_iv, m_ks;
+ int m_ks_idx;
+ DES_KS m_ksDES;
+ int m_iterations;
+ uint16_t m_current_kid;
+ key_type m_default_key;
+ key_map_type m_key_map;
+ bool m_verbose;
+public:
+ des_ofb()
+ : m_current_kid(-1)
+ {
+ memset(&m_ksDES, 0, sizeof(m_ksDES));
+ m_key_des = 0;
+ m_next_iv = 0;
+ m_ks_idx = 0;
+ m_ks = 0;
+ m_iterations = 0;
+ }
+
+ void set_logging(bool on)
+ {
+ m_verbose = on;
+ }
+
+ const type_id id() const
+ {
+ return crypto_algorithm::DES_OFB;
+ }
+
+ bool update(const struct CryptoState& state)
+ {
+ if (m_current_kid != state.kid)
+ {
+ if (m_key_map.empty())
+ {
+ // Nothing to do
+ }
+ else
+ {
+ key_map_type::iterator it = m_key_map.find(state.kid);
+ if (it != m_key_map.end())
+ {
+ set_key(it->second);
+ }
+ else if (!m_default_key.empty())
+ {
+ /*if (m_verbose) */fprintf(stderr, "Key 0x%04x not found in key map - using default key\n", state.kid);
+
+ set_key(m_default_key);
+ }
+ else
+ {
+ /*if (m_verbose) */fprintf(stderr, "Key 0x%04x not found in key map and no default key\n", state.kid);
+ }
+ }
+
+ m_current_kid = state.kid;
+ }
+
+ uint64_t iv = 0;
+ size_t n = std::min(sizeof(iv), state.mi.size());
+ memcpy(&iv, &state.mi[0], n);
+ set_iv(iv);
+
+ return (n == 8);
+ }
+
+ void set_key_map(const key_map_type& key_map)
+ {
+ m_key_map = key_map;
+
+ m_current_kid = -1; // To refresh on next update if it has changed
+ }
+
+ bool set_key(const crypto_algorithm::key_type& key)
+ {
+ const size_t valid_key_length = 8;
+
+ if (key.size() != valid_key_length)
+ {
+ if (m_verbose) fprintf(stderr, "DES:\tIncorrect key length of %lu (should be %lu)\n", key.size(), valid_key_length);
+ return false;
+ }
+
+ m_default_key = key;
+
+ memcpy(&m_key_des, &key[0], std::min(key.size(), sizeof(m_key_des)));
+
+ if (m_verbose)
+ {
+ std::stringstream ss;
+ for (int i = 0; i < valid_key_length; ++i)
+ ss << boost::format("%02X") % (int)key[i];
+ std::cerr << "DES:\tKey: " << ss.str() << std::endl;
+ }
+
+ deskey(m_ksDES, (unsigned char*)&m_key_des, 0); // 0: encrypt (for OFB mode)
+
+ return true;
+ }
+
+ void set_iv(uint64_t iv)
+ {
+ if (m_iterations > 0)
+ {
+ if (m_verbose) fprintf(stderr, "DES:\t%i bits used from %i iterations\n", m_ks_idx, m_iterations);
+ }
+
+ m_next_iv = iv;
+
+ m_ks_idx = 0;
+ m_iterations = 0;
+
+ m_ks = m_next_iv;
+ des(m_ksDES, (unsigned char*)&m_ks); // First initialisation
+ ++m_iterations;
+
+ des(m_ksDES, (unsigned char*)&m_ks); // Throw out first iteration & prepare for second
+ ++m_iterations;
+
+ generate(64); // Reserved 3 + first 5 of LC (3 left)
+ generate(3 * 8); // Use remaining 3 bytes for LC
+ }
+
+ uint64_t generate(size_t count) // 1..64
+ {
+ unsigned long long ullCurrent = swap_bytes(m_ks);
+ const int max_len = 64;
+ int pos = m_ks_idx % max_len;
+
+ m_ks_idx += count;
+
+ if ((pos + count) <= max_len) // Up to 64
+ {
+ if ((m_ks_idx % max_len) == 0)
+ {
+ des(m_ksDES, (unsigned char*)&m_ks); // Prepare for next iteration
+ ++m_iterations;
+ }
+
+ unsigned long long result = (ullCurrent >> (((max_len - 1) - pos) - (count-1))) & ((count == max_len) ? (unsigned long long)-1 : ((1ULL << count) - 1));
+
+ return result;
+ }
+
+ // Over-flow 64-bit boundary (so all of rest of current will be used)
+
+ des(m_ksDES, (unsigned char*)&m_ks); // Compute second part
+ ++m_iterations;
+
+ unsigned long long first = ullCurrent << pos; // RHS will be zeros
+
+ ullCurrent = swap_bytes(m_ks);
+ int remainder = count - (max_len - pos);
+ first >>= (((max_len - 1) - remainder) - ((max_len - 1) - pos));
+ unsigned long long next = (ullCurrent >> (((max_len - 1) - 0) - (remainder-1))) & ((1ULL << remainder) - 1);
+
+ return (first | next);
+ }
+
+};
+
+///////////////////////////////////////////////////////////////////////////////
+
+crypto_module::crypto_module(bool verbose/* = true*/)
+ : d_verbose(verbose)
+{
+}
+
+crypto_algorithm::sptr crypto_module::algorithm(crypto_algorithm::type_id algid)
+{
+ if ((!d_current_algorithm && (algid == crypto_algorithm::NONE)) || // This line should be commented out if 'null_algorithm' is to be tested
+ (d_current_algorithm && (algid == d_current_algorithm->id())))
+ return d_current_algorithm;
+
+ switch (algid)
+ {
+ case crypto_algorithm::DES_OFB:
+ d_current_algorithm = crypto_algorithm::sptr(new des_ofb());
+ break;
+ //case crypto_algorithm::NONE:
+ // d_current_algorithm = crypto_algorithm::sptr(new null_algorithm());
+ // break;
+ default:
+ d_current_algorithm = crypto_algorithm::sptr();
+ };
+
+ if (d_current_algorithm)
+ {
+ d_current_algorithm->set_logging(logging_enabled());
+
+ if (!d_persistent_key_map.empty())
+ d_current_algorithm->set_key_map(d_persistent_key_map);
+
+ if (!d_persistent_key.empty())
+ d_current_algorithm->set_key(d_persistent_key);
+ }
+
+ return d_current_algorithm;
+}
+
+void crypto_module::set_key(const crypto_algorithm::key_type& key)
+{
+ d_persistent_key = key;
+
+ if (d_current_algorithm)
+ d_current_algorithm->set_key(d_persistent_key);
+}
+
+void crypto_module::set_key_map(const crypto_algorithm::key_map_type& keys)
+{
+ d_persistent_key_map = keys;
+
+ if (d_current_algorithm)
+ d_current_algorithm->set_key_map(d_persistent_key_map);
+}
+
+void crypto_module::set_logging(bool on/* = true*/)
+{
+ d_verbose = on;
+
+ if (d_current_algorithm)
+ d_current_algorithm->set_logging(on);
+}
diff --git a/op25/gr-op25/lib/crypto.h b/op25/gr-op25/lib/crypto.h
new file mode 100644
index 0000000..dd0ef2e
--- /dev/null
+++ b/op25/gr-op25/lib/crypto.h
@@ -0,0 +1,73 @@
+#ifndef INCLUDED_CRYPTO_H
+#define INCLUDED_CRYPTO_H
+
+#include <stdint.h>
+#include <vector>
+#include <map>
+#include <boost/shared_ptr.hpp>
+
+static const int MESSAGE_INDICATOR_LENGTH = 9;
+
+class CryptoState
+{
+public:
+ CryptoState() :
+ mi(MESSAGE_INDICATOR_LENGTH), kid(0), algid(0)
+ { }
+public:
+ std::vector<uint8_t> mi;
+ uint16_t kid;
+ uint8_t algid;
+};
+
+class crypto_state_provider
+{
+public:
+ virtual struct CryptoState crypto_state() const=0;
+};
+
+class crypto_algorithm
+{
+public:
+ typedef boost::shared_ptr<class crypto_algorithm> sptr;
+ typedef std::vector<uint8_t> key_type;
+ typedef std::map<uint16_t, key_type > key_map_type;
+ typedef uint8_t type_id;
+ enum
+ {
+ NONE = 0x80,
+ DES_OFB = 0x81,
+ };
+public:
+ virtual const type_id id() const=0;
+ virtual bool set_key(const key_type& key)=0;
+ virtual void set_key_map(const key_map_type& key_map)=0;
+ virtual bool update(const struct CryptoState& state)=0;
+ virtual uint64_t generate(size_t n_bits)=0; // Can request up to 64 bits of key stream at one time
+ virtual void set_logging(bool on)=0;
+};
+
+class crypto_module
+{
+public:
+ typedef boost::shared_ptr<class crypto_module> sptr;
+public:
+ crypto_module(bool verbose = false);
+public:
+ virtual crypto_algorithm::sptr algorithm(crypto_algorithm::type_id algid);
+ virtual void set_key(const crypto_algorithm::key_type& key);
+ virtual void set_key_map(const crypto_algorithm::key_map_type& keys);
+ virtual void set_logging(bool on = true);
+protected:
+ crypto_algorithm::sptr d_current_algorithm;
+ crypto_algorithm::key_type d_persistent_key;
+ crypto_algorithm::key_map_type d_persistent_key_map;
+ bool d_verbose;
+public:
+ virtual crypto_algorithm::sptr current_algorithm() const
+ { return d_current_algorithm; }
+ virtual bool logging_enabled() const
+ { return d_verbose; }
+};
+
+#endif // INCLUDED_CRYPTO_H
diff --git a/op25/gr-op25/lib/crypto_module_du_handler.cc b/op25/gr-op25/lib/crypto_module_du_handler.cc
new file mode 100644
index 0000000..b8baf0c
--- /dev/null
+++ b/op25/gr-op25/lib/crypto_module_du_handler.cc
@@ -0,0 +1,64 @@
+#include "crypto_module_du_handler.h"
+
+#include "abstract_data_unit.h"
+
+#include <boost/format.hpp>
+#include <sstream>
+#include <stdio.h>
+
+crypto_module_du_handler::crypto_module_du_handler(data_unit_handler_sptr next, crypto_module::sptr crypto_mod)
+ : data_unit_handler(next)
+ , d_crypto_mod(crypto_mod)
+{
+}
+
+void
+crypto_module_du_handler::handle(data_unit_sptr du)
+{
+ if (!d_crypto_mod)
+ {
+ data_unit_handler::handle(du);
+ return;
+ }
+
+ crypto_state_provider* p = dynamic_cast<crypto_state_provider*>(du.get());
+ if (p == NULL)
+ {
+ data_unit_handler::handle(du);
+ return;
+ }
+
+ CryptoState state = p->crypto_state();
+
+ ///////////////////////////////////
+
+ if (d_crypto_mod->logging_enabled())
+ {
+ std::string duid_str("?");
+ abstract_data_unit* adu = dynamic_cast<abstract_data_unit*>(du.get());
+ if (adu)
+ duid_str = adu->duid_str();
+
+ std::stringstream ss;
+ for (size_t n = 0; n < state.mi.size(); ++n)
+ ss << (boost::format("%02x") % (int)state.mi[n]);
+
+ fprintf(stderr, "%s:\tAlgID: 0x%02x, KID: 0x%04x, MI: %s\n", duid_str.c_str(), state.algid, state.kid, ss.str().c_str());
+ }
+
+ ///////////////////////////////////
+
+ crypto_algorithm::sptr algorithm = d_crypto_mod->algorithm(state.algid);
+ if (!algorithm)
+ {
+ data_unit_handler::handle(du);
+ return;
+ }
+
+ // TODO: Could do key management & selection here with 'state.kid'
+ // Assuming we're only using one key (ignoring 'kid')
+
+ algorithm->update(state);
+
+ data_unit_handler::handle(du);
+}
diff --git a/op25/gr-op25/lib/crypto_module_du_handler.h b/op25/gr-op25/lib/crypto_module_du_handler.h
new file mode 100644
index 0000000..03479fe
--- /dev/null
+++ b/op25/gr-op25/lib/crypto_module_du_handler.h
@@ -0,0 +1,21 @@
+#ifndef INCLUDED_CRYPTO_MODULE_DU_HANDLER_H
+#define INCLUDED_CRYPTO_MODULE_DU_HANDLER_H
+
+#include <boost/shared_ptr.hpp>
+
+#include "data_unit_handler.h"
+#include "crypto.h"
+
+class crypto_module_du_handler : public data_unit_handler
+{
+public:
+ crypto_module_du_handler(data_unit_handler_sptr next, crypto_module::sptr crypto_mod);
+public:
+ typedef boost::shared_ptr<class crypto_module_du_handler> sptr;
+public:
+ virtual void handle(data_unit_sptr du);
+private:
+ crypto_module::sptr d_crypto_mod;
+};
+
+#endif //INCLUDED_CRYPTO_MODULE_HANDLER_H
diff --git a/op25/gr-op25/lib/data_unit.h b/op25/gr-op25/lib/data_unit.h
index bc824d9..670ab3a 100644
--- a/op25/gr-op25/lib/data_unit.h
+++ b/op25/gr-op25/lib/data_unit.h
@@ -32,6 +32,8 @@
#include <iosfwd>
#include <stdint.h>
+#include "crypto.h"
+
typedef std::deque<bool> bit_queue;
typedef const std::deque<bool> const_bit_queue;
@@ -76,7 +78,7 @@ public:
* \precondition is_complete() == true.
* \param imbe The imbe_decoder to use to generate the audio.
*/
- virtual void decode_audio(imbe_decoder& imbe) = 0;
+ virtual void decode_audio(imbe_decoder& imbe, crypto_module::sptr crypto_mod) = 0;
/**
* Decode the frame into an octet vector.
@@ -132,6 +134,8 @@ public:
*/
virtual std::string snapshot() const = 0;
+ virtual void set_logging(bool on) = 0;
+
protected:
/**
diff --git a/op25/gr-op25/lib/decoder_bf_impl.cc b/op25/gr-op25/lib/decoder_bf_impl.cc
index 4b49f57..54dd49a 100644
--- a/op25/gr-op25/lib/decoder_bf_impl.cc
+++ b/op25/gr-op25/lib/decoder_bf_impl.cc
@@ -34,6 +34,7 @@
#include "offline_imbe_decoder.h"
#include "voice_du_handler.h"
#include "op25_yank.h"
+#include "bch.h"
using namespace std;
@@ -41,13 +42,13 @@ namespace gr {
namespace op25 {
decoder_bf::sptr
- decoder_bf::make()
+ decoder_bf::make(bool idle_silence /*= true*/, bool verbose /*= false*/)
{
return gnuradio::get_initial_sptr
- (new decoder_bf_impl());
+ (new decoder_bf_impl(idle_silence, verbose));
}
- decoder_bf_impl::decoder_bf_impl() :
+ decoder_bf_impl::decoder_bf_impl(bool idle_silence /*= true*/, bool verbose /*= false*/) :
gr::block("decoder_bf",
gr::io_signature::make(1, 1, sizeof(uint8_t)),
gr::io_signature::make(0, 1, sizeof(float))),
@@ -56,14 +57,25 @@ namespace gr {
d_frame_hdr(),
d_imbe(imbe_decoder::make()),
d_state(SYNCHRONIZING),
- d_p25cai_du_handler(NULL)
+ d_p25cai_du_handler(NULL),
+ d_idle_silence(idle_silence),
+ d_verbose(false)
{
+ set_logging(verbose);
+
d_p25cai_du_handler = new p25cai_du_handler(d_data_unit_handler,
"224.0.0.1", 23456);
d_data_unit_handler = data_unit_handler_sptr(d_p25cai_du_handler);
+
d_snapshot_du_handler = new snapshot_du_handler(d_data_unit_handler);
d_data_unit_handler = data_unit_handler_sptr(d_snapshot_du_handler);
- d_data_unit_handler = data_unit_handler_sptr(new voice_du_handler(d_data_unit_handler, d_imbe));
+
+ d_crypto_module = crypto_module::sptr(new crypto_module(verbose));
+
+ d_crypto_module_du_handler = crypto_module_du_handler::sptr(new crypto_module_du_handler(d_data_unit_handler, d_crypto_module));
+ d_data_unit_handler = data_unit_handler_sptr(d_crypto_module_du_handler);
+
+ d_data_unit_handler = data_unit_handler_sptr(new voice_du_handler(d_data_unit_handler, d_imbe, d_crypto_module));
}
decoder_bf_impl::~decoder_bf_impl()
@@ -104,34 +116,35 @@ namespace gr {
gr_vector_void_star &output_items)
{
try {
+ gr::thread::scoped_lock lock(d_mutex);
- // process input
- const uint8_t *in = reinterpret_cast<const uint8_t*>(input_items[0]);
- for(int i = 0; i < ninput_items[0]; ++i) {
- dibit d = in[i] & 0x3;
- receive_symbol(d);
- }
- consume_each(ninput_items[0]);
-
- // produce audio
- audio_samples *samples = d_imbe->audio();
- float *out = reinterpret_cast<float*>(output_items[0]);
- const int n = min(static_cast<int>(samples->size()), noutput_items);
- if(0 < n) {
- copy(samples->begin(), samples->begin() + n, out);
- samples->erase(samples->begin(), samples->begin() + n);
- }
- if(n < noutput_items) {
- fill(out + n, out + noutput_items, 0.0);
- }
- return noutput_items;
+ // process input
+ const uint8_t *in = reinterpret_cast<const uint8_t*>(input_items[0]);
+ for(int i = 0; i < ninput_items[0]; ++i) {
+ dibit d = in[i] & 0x3;
+ receive_symbol(d);
+ }
+ consume_each(ninput_items[0]);
+
+ // produce audio
+ audio_samples *samples = d_imbe->audio();
+ float *out = reinterpret_cast<float*>(output_items[0]);
+ const int n = min(static_cast<int>(samples->size()), noutput_items);
+ if(0 < n) {
+ copy(samples->begin(), samples->begin() + n, out);
+ samples->erase(samples->begin(), samples->begin() + n);
+ }
+ if((d_idle_silence) && (n < noutput_items)) {
+ fill(out + n, out + noutput_items, 0.0);
+ }
+ return (d_idle_silence ? noutput_items : n);
} catch(const std::exception& x) {
- cerr << x.what() << endl;
- exit(1);
+ cerr << x.what() << endl;
+ exit(1);
} catch(...) {
- cerr << "unhandled exception" << endl;
- exit(2); }
+ cerr << "unhandled exception" << endl;
+ exit(2); }
}
const char*
@@ -177,14 +190,12 @@ namespace gr {
};
size_t NID_SZ = sizeof(NID) / sizeof(NID[0]);
- itpp::bvec b(63), zeroes(16);
- itpp::BCH bch(63, 16, 11, "6 3 3 1 1 4 1 3 6 7 2 3 5 4 5 3", true);
+ bit_vector b(NID_SZ);
yank(d_frame_hdr, NID, NID_SZ, b, 0);
- b = bch.decode(b);
- if(b != zeroes) {
- b = bch.encode(b);
+ if(bchDec(b) >= 0) {
yank_back(b, 0, d_frame_hdr, NID, NID_SZ);
d_data_unit = data_unit::make_data_unit(d_frame_hdr);
+ d_data_unit->set_logging(d_verbose);
} else {
data_unit_sptr null;
d_data_unit = null;
@@ -229,5 +240,36 @@ namespace gr {
break;
}
}
+
+ void
+ decoder_bf_impl::set_idle_silence(bool idle_silence/* = true*/)
+ {
+ gr::thread::scoped_lock lock(d_mutex);
+
+ d_idle_silence = idle_silence;
+ }
+
+ void
+ decoder_bf_impl::set_logging(bool verbose/* = true*/)
+ {
+ if (verbose) fprintf(stderr, "[%s<%lu>] verbose logging enabled\n", name().c_str(), unique_id());
+
+ d_verbose = verbose;
+
+ if (d_crypto_module)
+ d_crypto_module->set_logging(verbose);
+ }
+
+ void
+ decoder_bf_impl::set_key(const crypto_algorithm::key_type& key)
+ {
+ d_crypto_module->set_key(key);
+ }
+
+ void
+ decoder_bf_impl::set_key_map(const crypto_algorithm::key_map_type& keys)
+ {
+ d_crypto_module->set_key_map(keys);
+ }
} /* namespace op25 */
} /* namespace gr */
diff --git a/op25/gr-op25/lib/decoder_bf_impl.h b/op25/gr-op25/lib/decoder_bf_impl.h
index f907863..7129549 100644
--- a/op25/gr-op25/lib/decoder_bf_impl.h
+++ b/op25/gr-op25/lib/decoder_bf_impl.h
@@ -24,11 +24,14 @@
#define INCLUDED_OP25_DECODER_BF_IMPL_H
#include <op25/decoder_bf.h>
+#include <gnuradio/thread/thread.h>
#include "data_unit.h"
#include "data_unit_handler.h"
#include "imbe_decoder.h"
#include "p25cai_du_handler.h"
#include "snapshot_du_handler.h"
+#include "crypto.h"
+#include "crypto_module_du_handler.h"
namespace gr {
namespace op25 {
@@ -102,8 +105,21 @@ namespace gr {
*/
class snapshot_du_handler *d_snapshot_du_handler;
+ /*
+ * Whether or not to output silence when no audio is synthesised.
+ */
+ bool d_idle_silence;
+
+ bool d_verbose;
+
+ crypto_module::sptr d_crypto_module;
+
+ crypto_module_du_handler::sptr d_crypto_module_du_handler;
+
+ gr::thread::mutex d_mutex;
+
public:
- decoder_bf_impl();
+ decoder_bf_impl(bool idle_silence = true, bool verbose = false);
~decoder_bf_impl();
// Where all the action really happens
@@ -139,6 +155,14 @@ namespace gr {
* message queue.
*/
void set_msgq(gr::msg_queue::sptr msgq);
+
+ void set_idle_silence(bool idle_silence = true);
+
+ void set_logging(bool verbose = true);
+
+ void set_key(const crypto_algorithm::key_type& key);
+
+ void set_key_map(const crypto_algorithm::key_map_type& keys);
};
} // namespace op25
} // namespace gr
diff --git a/op25/gr-op25/lib/decoder_ff_impl.cc b/op25/gr-op25/lib/decoder_ff_impl.cc
index 60238c7..9115146 100644
--- a/op25/gr-op25/lib/decoder_ff_impl.cc
+++ b/op25/gr-op25/lib/decoder_ff_impl.cc
@@ -34,6 +34,7 @@
#include "offline_imbe_decoder.h"
#include "voice_du_handler.h"
#include "op25_yank.h"
+#include "bch.h"
using namespace std;
@@ -185,12 +186,9 @@ namespace gr {
};
size_t NID_SZ = sizeof(NID) / sizeof(NID[0]);
- itpp::bvec b(63), zeroes(16);
- itpp::BCH bch(63, 16, 11, "6 3 3 1 1 4 1 3 6 7 2 3 5 4 5 3", true);
+ bit_vector b(NID_SZ);
yank(d_frame_hdr, NID, NID_SZ, b, 0);
- b = bch.decode(b);
- if(b != zeroes) {
- b = bch.encode(b);
+ if(bchDec(b) >= 0) {
yank_back(b, 0, d_frame_hdr, NID, NID_SZ);
d_data_unit = data_unit::make_data_unit(d_frame_hdr);
} else {
diff --git a/op25/gr-op25/lib/des.h b/op25/gr-op25/lib/des.h
new file mode 100644
index 0000000..0dfd56c
--- /dev/null
+++ b/op25/gr-op25/lib/des.h
@@ -0,0 +1,15 @@
+typedef unsigned long DES_KS[16][2]; /* Single-key DES key schedule */
+typedef unsigned long DES3_KS[48][2]; /* Triple-DES key schedule */
+
+/* In deskey.c: */
+void deskey(DES_KS,unsigned char *,int);
+void des3key(DES3_KS,unsigned char *,int);
+
+/* In desport.c, desborl.cas or desgnu.s: */
+void des(DES_KS,unsigned char *);
+/* In des3port.c, des3borl.cas or des3gnu.s: */
+void des3(DES3_KS,unsigned char *);
+
+extern int Asmversion; /* 1 if we're linked with an asm version, 0 if C */
+
+
diff --git a/op25/gr-op25/lib/deskey.c b/op25/gr-op25/lib/deskey.c
new file mode 100644
index 0000000..fe8b677
--- /dev/null
+++ b/op25/gr-op25/lib/deskey.c
@@ -0,0 +1,124 @@
+/* Portable C code to create DES key schedules from user-provided keys
+ * This doesn't have to be fast unless you're cracking keys or UNIX
+ * passwords
+ */
+
+#include <string.h>
+#include "des.h"
+
+/* Key schedule-related tables from FIPS-46 */
+
+/* permuted choice table (key) */
+static unsigned char pc1[] = {
+ 57, 49, 41, 33, 25, 17, 9,
+ 1, 58, 50, 42, 34, 26, 18,
+ 10, 2, 59, 51, 43, 35, 27,
+ 19, 11, 3, 60, 52, 44, 36,
+
+ 63, 55, 47, 39, 31, 23, 15,
+ 7, 62, 54, 46, 38, 30, 22,
+ 14, 6, 61, 53, 45, 37, 29,
+ 21, 13, 5, 28, 20, 12, 4
+};
+
+/* number left rotations of pc1 */
+static unsigned char totrot[] = {
+ 1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28
+};
+
+/* permuted choice key (table) */
+static unsigned char pc2[] = {
+ 14, 17, 11, 24, 1, 5,
+ 3, 28, 15, 6, 21, 10,
+ 23, 19, 12, 4, 26, 8,
+ 16, 7, 27, 20, 13, 2,
+ 41, 52, 31, 37, 47, 55,
+ 30, 40, 51, 45, 33, 48,
+ 44, 49, 39, 56, 34, 53,
+ 46, 42, 50, 36, 29, 32
+};
+
+/* End of DES-defined tables */
+
+
+/* bit 0 is left-most in byte */
+static int bytebit[] = {
+ 0200,0100,040,020,010,04,02,01
+};
+
+
+/* Generate key schedule for encryption or decryption
+ * depending on the value of "decrypt"
+ */
+void
+deskey(DES_KS k,unsigned char *key,int decrypt)
+/* Key schedule array */
+/* 64 bits (will use only 56) */
+/* 0 = encrypt, 1 = decrypt */
+{
+ unsigned char pc1m[56]; /* place to modify pc1 into */
+ unsigned char pcr[56]; /* place to rotate pc1 into */
+ register int i,j,l;
+ int m;
+ unsigned char ks[8];
+
+ for (j=0; j<56; j++) { /* convert pc1 to bits of key */
+ l=pc1[j]-1; /* integer bit location */
+ m = l & 07; /* find bit */
+ pc1m[j]=(key[l>>3] & /* find which key byte l is in */
+ bytebit[m]) /* and which bit of that byte */
+ ? 1 : 0; /* and store 1-bit result */
+ }
+ for (i=0; i<16; i++) { /* key chunk for each iteration */
+ memset(ks,0,sizeof(ks)); /* Clear key schedule */
+ for (j=0; j<56; j++) /* rotate pc1 the right amount */
+ pcr[j] = pc1m[(l=j+totrot[decrypt? 15-i : i])<(j<28? 28 : 56) ? l: l-28];
+ /* rotate left and right halves independently */
+ for (j=0; j<48; j++){ /* select bits individually */
+ /* check bit that goes to ks[j] */
+ if (pcr[pc2[j]-1]){
+ /* mask it in if it's there */
+ l= j % 6;
+ ks[j/6] |= bytebit[l] >> 2;
+ }
+ }
+ /* Now convert to packed odd/even interleaved form */
+ k[i][0] = ((long)ks[0] << 24)
+ | ((long)ks[2] << 16)
+ | ((long)ks[4] << 8)
+ | ((long)ks[6]);
+ k[i][1] = ((long)ks[1] << 24)
+ | ((long)ks[3] << 16)
+ | ((long)ks[5] << 8)
+ | ((long)ks[7]);
+ if(Asmversion){
+ /* The assembler versions pre-shift each subkey 2 bits
+ * so the Spbox indexes are already computed
+ */
+ k[i][0] <<= 2;
+ k[i][1] <<= 2;
+ }
+ }
+}
+
+/* Generate key schedule for triple DES in E-D-E (or D-E-D) mode.
+ *
+ * The key argument is taken to be 24 bytes. The first 8 bytes are K1
+ * for the first stage, the second 8 bytes are K2 for the middle stage
+ * and the third 8 bytes are K3 for the last stage
+ */
+void
+des3key(DES3_KS k,unsigned char *key,int decrypt)
+/* 192 bits (will use only 168) */
+/* 0 = encrypt, 1 = decrypt */
+{
+ if(!decrypt){
+ deskey(&k[0],&key[0],0);
+ deskey(&k[16],&key[8],1);
+ deskey(&k[32],&key[16],0);
+ } else {
+ deskey(&k[32],&key[0],1);
+ deskey(&k[16],&key[8],0);
+ deskey(&k[0],&key[16],1);
+ }
+}
diff --git a/op25/gr-op25/lib/desport.c b/op25/gr-op25/lib/desport.c
new file mode 100644
index 0000000..0073be3
--- /dev/null
+++ b/op25/gr-op25/lib/desport.c
@@ -0,0 +1,236 @@
+/* Portable C version of des() function */
+
+#include <stdint.h>
+#include "des.h"
+
+/* Tables defined in the Data Encryption Standard documents
+ * Three of these tables, the initial permutation, the final
+ * permutation and the expansion operator, are regular enough that
+ * for speed, we hard-code them. They're here for reference only.
+ * Also, the S and P boxes are used by a separate program, gensp.c,
+ * to build the combined SP box, Spbox[]. They're also here just
+ * for reference.
+ */
+#ifdef notdef
+/* initial permutation IP */
+static unsigned char ip[] = {
+ 58, 50, 42, 34, 26, 18, 10, 2,
+ 60, 52, 44, 36, 28, 20, 12, 4,
+ 62, 54, 46, 38, 30, 22, 14, 6,
+ 64, 56, 48, 40, 32, 24, 16, 8,
+ 57, 49, 41, 33, 25, 17, 9, 1,
+ 59, 51, 43, 35, 27, 19, 11, 3,
+ 61, 53, 45, 37, 29, 21, 13, 5,
+ 63, 55, 47, 39, 31, 23, 15, 7
+};
+
+/* final permutation IP^-1 */
+static unsigned char fp[] = {
+ 40, 8, 48, 16, 56, 24, 64, 32,
+ 39, 7, 47, 15, 55, 23, 63, 31,
+ 38, 6, 46, 14, 54, 22, 62, 30,
+ 37, 5, 45, 13, 53, 21, 61, 29,
+ 36, 4, 44, 12, 52, 20, 60, 28,
+ 35, 3, 43, 11, 51, 19, 59, 27,
+ 34, 2, 42, 10, 50, 18, 58, 26,
+ 33, 1, 41, 9, 49, 17, 57, 25
+};
+/* expansion operation matrix */
+static unsigned char ei[] = {
+ 32, 1, 2, 3, 4, 5,
+ 4, 5, 6, 7, 8, 9,
+ 8, 9, 10, 11, 12, 13,
+ 12, 13, 14, 15, 16, 17,
+ 16, 17, 18, 19, 20, 21,
+ 20, 21, 22, 23, 24, 25,
+ 24, 25, 26, 27, 28, 29,
+ 28, 29, 30, 31, 32, 1
+};
+/* The (in)famous S-boxes */
+static unsigned char sbox[8][64] = {
+ /* S1 */
+ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
+ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
+ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
+ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
+
+ /* S2 */
+ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
+ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
+ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
+ 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
+
+ /* S3 */
+ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
+ 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
+ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
+ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
+
+ /* S4 */
+ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
+ 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
+ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
+ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
+
+ /* S5 */
+ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
+ 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
+ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
+ 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
+
+ /* S6 */
+ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
+ 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
+ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
+ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
+
+ /* S7 */
+ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
+ 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
+ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
+ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
+
+ /* S8 */
+ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
+ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
+ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
+ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
+};
+
+/* 32-bit permutation function P used on the output of the S-boxes */
+static unsigned char p32i[] = {
+ 16, 7, 20, 21,
+ 29, 12, 28, 17,
+ 1, 15, 23, 26,
+ 5, 18, 31, 10,
+ 2, 8, 24, 14,
+ 32, 27, 3, 9,
+ 19, 13, 30, 6,
+ 22, 11, 4, 25
+};
+#endif
+
+int Asmversion = 0;
+
+/* Combined SP lookup table, linked in
+ * For best results, ensure that this is aligned on a 32-bit boundary;
+ * Borland C++ 3.1 doesn't guarantee this!
+ */
+extern uint64_t Spbox[8][64]; /* Combined S and P boxes */
+
+/* Primitive function F.
+ * Input is r, subkey array in keys, output is XORed into l.
+ * Each round consumes eight 6-bit subkeys, one for
+ * each of the 8 S-boxes, 2 longs for each round.
+ * Each long contains four 6-bit subkeys, each taking up a byte.
+ * The first long contains, from high to low end, the subkeys for
+ * S-boxes 1, 3, 5 & 7; the second contains the subkeys for S-boxes
+ * 2, 4, 6 & 8 (using the origin-1 S-box numbering in the standard,
+ * not the origin-0 numbering used elsewhere in this code)
+ * See comments elsewhere about the pre-rotated values of r and Spbox.
+ */
+#define F(l,r,key){\
+ work = ((r >> 4) | (r << 28)) ^ key[0];\
+ l ^= Spbox[6][work & 0x3f];\
+ l ^= Spbox[4][(work >> 8) & 0x3f];\
+ l ^= Spbox[2][(work >> 16) & 0x3f];\
+ l ^= Spbox[0][(work >> 24) & 0x3f];\
+ work = r ^ key[1];\
+ l ^= Spbox[7][work & 0x3f];\
+ l ^= Spbox[5][(work >> 8) & 0x3f];\
+ l ^= Spbox[3][(work >> 16) & 0x3f];\
+ l ^= Spbox[1][(work >> 24) & 0x3f];\
+}
+/* Encrypt or decrypt a block of data in ECB mode */
+void
+des(unsigned long ks[16][2],unsigned char block[8])
+/* Key schedule */
+/* Data block */
+{
+ unsigned long left,right,work;
+
+ /* Read input block and place in left/right in big-endian order */
+ left = ((unsigned long)block[0] << 24)
+ | ((unsigned long)block[1] << 16)
+ | ((unsigned long)block[2] << 8)
+ | (unsigned long)block[3];
+ right = ((unsigned long)block[4] << 24)
+ | ((unsigned long)block[5] << 16)
+ | ((unsigned long)block[6] << 8)
+ | (unsigned long)block[7];
+
+ /* Hoey's clever initial permutation algorithm, from Outerbridge
+ * (see Schneier p 478)
+ *
+ * The convention here is the same as Outerbridge: rotate each
+ * register left by 1 bit, i.e., so that "left" contains permuted
+ * input bits 2, 3, 4, ... 1 and "right" contains 33, 34, 35, ... 32
+ * (using origin-1 numbering as in the FIPS). This allows us to avoid
+ * one of the two rotates that would otherwise be required in each of
+ * the 16 rounds.
+ */
+ work = ((left >> 4) ^ right) & 0x0f0f0f0f;
+ right ^= work;
+ left ^= work << 4;
+ work = ((left >> 16) ^ right) & 0xffff;
+ right ^= work;
+ left ^= work << 16;
+ work = ((right >> 2) ^ left) & 0x33333333;
+ left ^= work;
+ right ^= (work << 2);
+ work = ((right >> 8) ^ left) & 0xff00ff;
+ left ^= work;
+ right ^= (work << 8);
+ right = (right << 1) | (right >> 31);
+ work = (left ^ right) & 0xaaaaaaaa;
+ left ^= work;
+ right ^= work;
+ left = (left << 1) | (left >> 31);
+
+ /* Now do the 16 rounds */
+ F(left,right,ks[0]);
+ F(right,left,ks[1]);
+ F(left,right,ks[2]);
+ F(right,left,ks[3]);
+ F(left,right,ks[4]);
+ F(right,left,ks[5]);
+ F(left,right,ks[6]);
+ F(right,left,ks[7]);
+ F(left,right,ks[8]);
+ F(right,left,ks[9]);
+ F(left,right,ks[10]);
+ F(right,left,ks[11]);
+ F(left,right,ks[12]);
+ F(right,left,ks[13]);
+ F(left,right,ks[14]);
+ F(right,left,ks[15]);
+
+ /* Inverse permutation, also from Hoey via Outerbridge and Schneier */
+ right = (right << 31) | (right >> 1);
+ work = (left ^ right) & 0xaaaaaaaa;
+ left ^= work;
+ right ^= work;
+ left = (left >> 1) | (left << 31);
+ work = ((left >> 8) ^ right) & 0xff00ff;
+ right ^= work;
+ left ^= work << 8;
+ work = ((left >> 2) ^ right) & 0x33333333;
+ right ^= work;
+ left ^= work << 2;
+ work = ((right >> 16) ^ left) & 0xffff;
+ left ^= work;
+ right ^= work << 16;
+ work = ((right >> 4) ^ left) & 0x0f0f0f0f;
+ left ^= work;
+ right ^= work << 4;
+
+ /* Put the block back into the user's buffer with final swap */
+ block[0] = right >> 24;
+ block[1] = right >> 16;
+ block[2] = right >> 8;
+ block[3] = right;
+ block[4] = left >> 24;
+ block[5] = left >> 16;
+ block[6] = left >> 8;
+ block[7] = left;
+}
diff --git a/op25/gr-op25/lib/dessp.c b/op25/gr-op25/lib/dessp.c
new file mode 100644
index 0000000..2470400
--- /dev/null
+++ b/op25/gr-op25/lib/dessp.c
@@ -0,0 +1,131 @@
+#include <stdint.h>
+uint64_t Spbox[8][64] = {
+0x01010400,0x00000000,0x00010000,0x01010404,
+0x01010004,0x00010404,0x00000004,0x00010000,
+0x00000400,0x01010400,0x01010404,0x00000400,
+0x01000404,0x01010004,0x01000000,0x00000004,
+0x00000404,0x01000400,0x01000400,0x00010400,
+0x00010400,0x01010000,0x01010000,0x01000404,
+0x00010004,0x01000004,0x01000004,0x00010004,
+0x00000000,0x00000404,0x00010404,0x01000000,
+0x00010000,0x01010404,0x00000004,0x01010000,
+0x01010400,0x01000000,0x01000000,0x00000400,
+0x01010004,0x00010000,0x00010400,0x01000004,
+0x00000400,0x00000004,0x01000404,0x00010404,
+0x01010404,0x00010004,0x01010000,0x01000404,
+0x01000004,0x00000404,0x00010404,0x01010400,
+0x00000404,0x01000400,0x01000400,0x00000000,
+0x00010004,0x00010400,0x00000000,0x01010004,
+0x80108020,0x80008000,0x00008000,0x00108020,
+0x00100000,0x00000020,0x80100020,0x80008020,
+0x80000020,0x80108020,0x80108000,0x80000000,
+0x80008000,0x00100000,0x00000020,0x80100020,
+0x00108000,0x00100020,0x80008020,0x00000000,
+0x80000000,0x00008000,0x00108020,0x80100000,
+0x00100020,0x80000020,0x00000000,0x00108000,
+0x00008020,0x80108000,0x80100000,0x00008020,
+0x00000000,0x00108020,0x80100020,0x00100000,
+0x80008020,0x80100000,0x80108000,0x00008000,
+0x80100000,0x80008000,0x00000020,0x80108020,
+0x00108020,0x00000020,0x00008000,0x80000000,
+0x00008020,0x80108000,0x00100000,0x80000020,
+0x00100020,0x80008020,0x80000020,0x00100020,
+0x00108000,0x00000000,0x80008000,0x00008020,
+0x80000000,0x80100020,0x80108020,0x00108000,
+0x00000208,0x08020200,0x00000000,0x08020008,
+0x08000200,0x00000000,0x00020208,0x08000200,
+0x00020008,0x08000008,0x08000008,0x00020000,
+0x08020208,0x00020008,0x08020000,0x00000208,
+0x08000000,0x00000008,0x08020200,0x00000200,
+0x00020200,0x08020000,0x08020008,0x00020208,
+0x08000208,0x00020200,0x00020000,0x08000208,
+0x00000008,0x08020208,0x00000200,0x08000000,
+0x08020200,0x08000000,0x00020008,0x00000208,
+0x00020000,0x08020200,0x08000200,0x00000000,
+0x00000200,0x00020008,0x08020208,0x08000200,
+0x08000008,0x00000200,0x00000000,0x08020008,
+0x08000208,0x00020000,0x08000000,0x08020208,
+0x00000008,0x00020208,0x00020200,0x08000008,
+0x08020000,0x08000208,0x00000208,0x08020000,
+0x00020208,0x00000008,0x08020008,0x00020200,
+0x100802001,0x100002081,0x100002081,0x00000080,
+0x00802080,0x100800081,0x100800001,0x100002001,
+0x00000000,0x00802000,0x00802000,0x100802081,
+0x100000081,0x00000000,0x00800080,0x100800001,
+0x100000001,0x00002000,0x00800000,0x100802001,
+0x00000080,0x00800000,0x100002001,0x00002080,
+0x100800081,0x100000001,0x00002080,0x00800080,
+0x00002000,0x00802080,0x100802081,0x100000081,
+0x00800080,0x100800001,0x00802000,0x100802081,
+0x100000081,0x00000000,0x00000000,0x00802000,
+0x00002080,0x00800080,0x100800081,0x100000001,
+0x100802001,0x100002081,0x100002081,0x00000080,
+0x100802081,0x100000081,0x100000001,0x00002000,
+0x100800001,0x100002001,0x00802080,0x100800081,
+0x100002001,0x00002080,0x00800000,0x100802001,
+0x00000080,0x00800000,0x00002000,0x00802080,
+0x00000100,0x02080100,0x02080000,0x42000100,
+0x00080000,0x00000100,0x40000000,0x02080000,
+0x40080100,0x00080000,0x02000100,0x40080100,
+0x42000100,0x42080000,0x00080100,0x40000000,
+0x02000000,0x40080000,0x40080000,0x00000000,
+0x40000100,0x42080100,0x42080100,0x02000100,
+0x42080000,0x40000100,0x00000000,0x42000000,
+0x02080100,0x02000000,0x42000000,0x00080100,
+0x00080000,0x42000100,0x00000100,0x02000000,
+0x40000000,0x02080000,0x42000100,0x40080100,
+0x02000100,0x40000000,0x42080000,0x02080100,
+0x40080100,0x00000100,0x02000000,0x42080000,
+0x42080100,0x00080100,0x42000000,0x42080100,
+0x02080000,0x00000000,0x40080000,0x42000000,
+0x00080100,0x02000100,0x40000100,0x00080000,
+0x00000000,0x40080000,0x02080100,0x40000100,
+0x20000010,0x20400000,0x00004000,0x20404010,
+0x20400000,0x00000010,0x20404010,0x00400000,
+0x20004000,0x00404010,0x00400000,0x20000010,
+0x00400010,0x20004000,0x20000000,0x00004010,
+0x00000000,0x00400010,0x20004010,0x00004000,
+0x00404000,0x20004010,0x00000010,0x20400010,
+0x20400010,0x00000000,0x00404010,0x20404000,
+0x00004010,0x00404000,0x20404000,0x20000000,
+0x20004000,0x00000010,0x20400010,0x00404000,
+0x20404010,0x00400000,0x00004010,0x20000010,
+0x00400000,0x20004000,0x20000000,0x00004010,
+0x20000010,0x20404010,0x00404000,0x20400000,
+0x00404010,0x20404000,0x00000000,0x20400010,
+0x00000010,0x00004000,0x20400000,0x00404010,
+0x00004000,0x00400010,0x20004010,0x00000000,
+0x20404000,0x20000000,0x00400010,0x20004010,
+0x00200000,0x04200002,0x04000802,0x00000000,
+0x00000800,0x04000802,0x00200802,0x04200800,
+0x04200802,0x00200000,0x00000000,0x04000002,
+0x00000002,0x04000000,0x04200002,0x00000802,
+0x04000800,0x00200802,0x00200002,0x04000800,
+0x04000002,0x04200000,0x04200800,0x00200002,
+0x04200000,0x00000800,0x00000802,0x04200802,
+0x00200800,0x00000002,0x04000000,0x00200800,
+0x04000000,0x00200800,0x00200000,0x04000802,
+0x04000802,0x04200002,0x04200002,0x00000002,
+0x00200002,0x04000000,0x04000800,0x00200000,
+0x04200800,0x00000802,0x00200802,0x04200800,
+0x00000802,0x04000002,0x04200802,0x04200000,
+0x00200800,0x00000000,0x00000002,0x04200802,
+0x00000000,0x00200802,0x04200000,0x00000800,
+0x04000002,0x04000800,0x00000800,0x00200002,
+0x10001040,0x00001000,0x00040000,0x10041040,
+0x10000000,0x10001040,0x00000040,0x10000000,
+0x00040040,0x10040000,0x10041040,0x00041000,
+0x10041000,0x00041040,0x00001000,0x00000040,
+0x10040000,0x10000040,0x10001000,0x00001040,
+0x00041000,0x00040040,0x10040040,0x10041000,
+0x00001040,0x00000000,0x00000000,0x10040040,
+0x10000040,0x10001000,0x00041040,0x00040000,
+0x00041040,0x00040000,0x10041000,0x00001000,
+0x00000040,0x10040040,0x00001000,0x00041040,
+0x10001000,0x00000040,0x10000040,0x10040000,
+0x10040040,0x10000000,0x00040000,0x10001040,
+0x00000000,0x10041040,0x00040040,0x10000040,
+0x10040000,0x10001000,0x10001040,0x00000000,
+0x10041040,0x00041000,0x00041000,0x00001040,
+0x00001040,0x00040040,0x10000000,0x10041000,
+};
diff --git a/op25/gr-op25/lib/fsk4_demod_ff_impl.cc b/op25/gr-op25/lib/fsk4_demod_ff_impl.cc
index de77acc..582545b 100644
--- a/op25/gr-op25/lib/fsk4_demod_ff_impl.cc
+++ b/op25/gr-op25/lib/fsk4_demod_ff_impl.cc
@@ -27,6 +27,7 @@
#include <stdio.h>
#include <gnuradio/io_signature.h>
+#include <boost/scoped_array.hpp>
#include "fsk4_demod_ff_impl.h"
/*
@@ -186,7 +187,7 @@ namespace gr {
gr::io_signature::make(1, 1, sizeof(float)),
gr::io_signature::make(1, 1, sizeof(float))),
d_block_rate(sample_rate_Hz / symbol_rate_Hz),
- d_history(new float[NTAPS]),
+ my_d_history(new float[NTAPS]),
d_history_last(0),
d_queue(queue),
d_symbol_clock(0.0),
@@ -196,7 +197,7 @@ namespace gr {
fine_frequency_correction = 0.0;
coarse_frequency_correction = 0.0;
- std::fill(&d_history[0], &d_history[NTAPS], 0.0);
+ std::fill(&my_d_history[0], &my_d_history[NTAPS], 0.0);
}
/*
@@ -269,7 +270,7 @@ namespace gr {
{
d_symbol_clock += d_symbol_time;
- d_history[d_history_last++] = input;
+ my_d_history[d_history_last++] = input;
d_history_last %= NTAPS;
if(d_symbol_clock > 1.0) {
@@ -296,8 +297,8 @@ namespace gr {
double interp = 0.0;
double interp_p1 = 0.0;
for(size_t i = 0, j = d_history_last; i < NTAPS; ++i) {
- interp += TAPS[imu][i] * d_history[j];
- interp_p1 += TAPS[imu_p1][i] * d_history[j];
+ interp += TAPS[imu][i] * my_d_history[j];
+ interp_p1 += TAPS[imu_p1][i] * my_d_history[j];
j = (j + 1) % NTAPS;
}
#else
@@ -306,8 +307,8 @@ namespace gr {
double interp_p1 = 0.0;
for(int i=0; i<NTAPS; i++)
{
- interp += TAPS[imu ][i] * d_history[j];
- interp_p1 += TAPS[imu_p1][i] * d_history[j];
+ interp += TAPS[imu ][i] * my_d_history[j];
+ interp_p1 += TAPS[imu_p1][i] * my_d_history[j];
j = (j+1) % NTAPS;
}
#endif
diff --git a/op25/gr-op25/lib/fsk4_demod_ff_impl.h b/op25/gr-op25/lib/fsk4_demod_ff_impl.h
index e36eb56..063590c 100644
--- a/op25/gr-op25/lib/fsk4_demod_ff_impl.h
+++ b/op25/gr-op25/lib/fsk4_demod_ff_impl.h
@@ -33,7 +33,7 @@ namespace gr {
{
private:
const float d_block_rate;
- boost::scoped_array<float> d_history;
+ boost::scoped_array<float> my_d_history;
size_t d_history_last;
gr::msg_queue::sptr d_queue;
double d_symbol_clock;
diff --git a/op25/gr-op25/lib/hdu.cc b/op25/gr-op25/lib/hdu.cc
index 737fbb7..ae89dc1 100644
--- a/op25/gr-op25/lib/hdu.cc
+++ b/op25/gr-op25/lib/hdu.cc
@@ -28,6 +28,8 @@
#include <iomanip>
#include <sstream>
+#include <boost/format.hpp>
+#include <stdio.h>
using namespace std;
@@ -65,6 +67,8 @@ hdu::do_correct_errors(bit_vector& frame)
{
apply_golay_correction(frame);
apply_rs_correction(frame);
+
+ if (logging_enabled()) fprintf(stderr, "\n");
}
void
@@ -136,34 +140,59 @@ hdu::frame_size_max() const
return 792;
}
-string
-hdu::algid_str() const
+uint8_t
+hdu::algid() const
{
const size_t ALGID_BITS[] = {
356, 357, 360, 361, 374, 375, 376, 377
};
const size_t ALGID_BITS_SZ = sizeof(ALGID_BITS) / sizeof(ALGID_BITS[0]);
- uint8_t algid = extract(frame_body(), ALGID_BITS, ALGID_BITS_SZ);
- return lookup(algid, ALGIDS, ALGIDS_SZ);
+ return extract(frame_body(), ALGID_BITS, ALGID_BITS_SZ);
}
string
-hdu::kid_str() const
+hdu::algid_str() const
+{
+ uint8_t _algid = algid();
+ return lookup(_algid, ALGIDS, ALGIDS_SZ);
+}
+
+uint16_t
+hdu::kid() const
{
const size_t KID_BITS[] = {
378, 379, 392, 393, 394, 395, 396, 397,
410, 411, 412, 413, 414, 415, 428, 429
};
const size_t KID_BITS_SZ = sizeof(KID_BITS) / sizeof(KID_BITS[0]);
- uint16_t kid = extract(frame_body(), KID_BITS, KID_BITS_SZ);
+ return extract(frame_body(), KID_BITS, KID_BITS_SZ);
+}
+
+string
+hdu::kid_str() const
+{
+ uint16_t _kid = kid();
ostringstream os;
- os << hex << showbase << setfill('0') << setw(4) << kid;
+ os << hex << showbase << setfill('0') << setw(4) << _kid;
return os.str();
}
std::string
hdu::mi_str() const
{
+ std::vector<uint8_t> _mi(mi());
+ ostringstream os;
+ os << "0x";
+ for(size_t i = 0; i < _mi.size(); ++i) {
+ uint16_t octet = _mi[i];
+ os << hex << setfill('0') << setw(2) << octet;
+ }
+ return os.str();
+}
+
+std::vector<uint8_t>
+hdu::mi() const
+{
const size_t MI_BITS[] = {
114, 115, 116, 117, 118, 119, 132, 133,
134, 135, 136, 137, 152, 153, 154, 155,
@@ -177,15 +206,9 @@ hdu::mi_str() const
};
const size_t MI_BITS_SZ = sizeof(MI_BITS) / sizeof(MI_BITS[0]);
- uint8_t mi[9];
- extract(frame_body(), MI_BITS, MI_BITS_SZ, mi);
- ostringstream os;
- os << "0x";
- for(size_t i = 0; i < (sizeof(mi) / sizeof(mi[0])); ++i) {
- uint16_t octet = mi[i];
- os << hex << setfill('0') << setw(2) << octet;
- }
- return os.str();
+ std::vector<uint8_t> _mi(((MI_BITS_SZ + 7) / 8));
+ extract(frame_body(), MI_BITS, MI_BITS_SZ, &_mi[0]);
+ return _mi;
}
string
@@ -219,7 +242,21 @@ hdu::tgid_str() const
};
const size_t TGID_BITS_SZ = sizeof(TGID_BITS) / sizeof(TGID_BITS[0]);
const uint16_t tgid = extract(frame_body(), TGID_BITS, TGID_BITS_SZ);
- ostringstream os;
- os << hex << showbase << setfill('0') << setw(4) << tgid;
- return os.str();
+ // Zero fill isn't working properly in original implementation
+ //ostringstream os;
+ //os << hex << showbase << setfill('0') << setw(4) << tgid;
+ //return os.str();
+ return (boost::format("0x%04x") % tgid).str();
+}
+
+struct CryptoState
+hdu::crypto_state() const
+{
+ struct CryptoState state;
+
+ state.mi = mi();
+ state.kid = kid();
+ state.algid = algid();
+
+ return state;
}
diff --git a/op25/gr-op25/lib/hdu.h b/op25/gr-op25/lib/hdu.h
index b7586fa..ef2373a 100644
--- a/op25/gr-op25/lib/hdu.h
+++ b/op25/gr-op25/lib/hdu.h
@@ -25,11 +25,12 @@
#define INCLUDED_HDU_H
#include "abstract_data_unit.h"
+#include "crypto.h"
/**
* P25 header data unit (HDU).
*/
-class hdu : public abstract_data_unit
+class hdu : public abstract_data_unit, public crypto_state_provider
{
public:
@@ -96,7 +97,9 @@ protected:
*/
virtual uint16_t frame_size_max() const;
-private:
+public:
+
+ uint8_t algid() const;
/**
* Return a string describing the encryption algorithm ID (ALGID).
@@ -105,6 +108,8 @@ private:
*/
std::string algid_str() const;
+ virtual uint16_t kid() const;
+
/**
* Returns a string describing the key id (KID).
*
@@ -119,6 +124,8 @@ private:
*/
virtual std::string mfid_str() const;
+ virtual std::vector<uint8_t> mi() const;
+
/**
* Returns a string describing the message indicator (MI).
*
@@ -139,6 +146,10 @@ private:
* \return A string identifying the TGID.
*/
virtual std::string tgid_str() const;
+
+public:
+
+ struct CryptoState crypto_state() const;
};
#endif /* INCLUDED_HDU_H */
diff --git a/op25/gr-op25/lib/ldu.cc b/op25/gr-op25/lib/ldu.cc
new file mode 100644
index 0000000..40e6870
--- /dev/null
+++ b/op25/gr-op25/lib/ldu.cc
@@ -0,0 +1,102 @@
+#include "ldu.h"
+
+#include <stdio.h>
+
+#include <itpp/base/vec.h>
+#include <itpp/base/mat.h>
+#include <itpp/base/binary.h>
+#include <itpp/base/converters.h>
+
+const static itpp::Mat<int> ham_10_6_3_6("1 1 1 0 0 1 1 0 0 0; 1 1 0 1 0 1 0 1 0 0; 1 0 1 1 1 0 0 0 1 0; 0 1 1 1 1 0 0 0 0 1");
+
+typedef std::vector<itpp::Vec<int> > VecArray;
+
+ldu::ldu(const_bit_queue& frame_body) :
+ voice_data_unit(frame_body),
+ m_hamming_error_count(0)
+{
+}
+
+void
+ldu::do_correct_errors(bit_vector& frame_body)
+{
+ voice_data_unit::do_correct_errors(frame_body);
+}
+
+bool
+ldu::process_meta_data(bit_vector& frame_body)
+{
+ m_hamming_error_count = 0;
+
+ //std::vector<uint8_t> lc(30);
+ //std::vector<uint16_t> ham(24);
+ int lc_bit_idx = 0;
+ VecArray arrayVec;
+ itpp::Vec<int> vecRaw(10); // First 6 bits contain data
+
+ for (int i = 400; i < 1360; i += 184)
+ {
+ for (int j = 0; j < 40; j++)
+ {
+ int x = (i + j) + (((i + j) / 70) * 2); // Adjust bit index for status
+ unsigned char ch = frame_body[x];
+
+ //lc[lc_bit_idx / 8] |= (ch << (7 - (lc_bit_idx % 8)));
+ //ham[lc_bit_idx / 10] = ((ham[lc_bit_idx / 10]) << 1) | ch;
+ vecRaw(lc_bit_idx % 10) = ch;
+
+ ++lc_bit_idx;
+
+ if ((lc_bit_idx % 10) == 0)
+ arrayVec.push_back(vecRaw);
+ }
+ }
+
+ if (lc_bit_idx != 240) // Not enough bits
+ {
+ return false;
+ }
+
+ if (arrayVec.size() != 24) // Not enough vectors
+ {
+ return false;
+ }
+
+ itpp::Vec<int> vecZero(4);
+ vecZero.zeros();
+
+ m_raw_meta_data.clear();
+
+ for (int i = 0; i < arrayVec.size(); ++i)
+ {
+ itpp::Vec<int>& vec = arrayVec[i];
+ itpp::bvec vB(itpp::to_bvec(vec));
+
+ itpp::Vec<int> vS = ham_10_6_3_6 * vec;
+ for (int i = 0; i < vS.length(); ++i)
+ vS[i] = vS[i] % 2;
+ itpp::bvec vb(to_bvec(vS));
+ if (itpp::bin2dec(vb) != 0)
+ {
+ ++m_hamming_error_count;
+ }
+
+ m_raw_meta_data = concat(m_raw_meta_data, vB.mid(0, 6)); // Includes RS for last 72 bits
+ }
+
+ if (logging_enabled()) fprintf(stderr, "%s: %lu hamming errors, %s\n", duid_str().c_str(), m_hamming_error_count, (meta_data_valid() ? "valid" : "invalid"));
+
+ return meta_data_valid();
+}
+
+const itpp::bvec&
+ldu::raw_meta_data() const
+{
+ return m_raw_meta_data;
+}
+
+bool
+ldu::meta_data_valid() const
+{
+ return (m_raw_meta_data.length() == 144); // Not enough bits after Hamming(10,6,3)
+}
diff --git a/op25/gr-op25/lib/ldu.h b/op25/gr-op25/lib/ldu.h
new file mode 100644
index 0000000..75fb3ef
--- /dev/null
+++ b/op25/gr-op25/lib/ldu.h
@@ -0,0 +1,28 @@
+#ifndef INCLUDED_LDU_H
+#define INCLUDED_LDU_H
+
+#include "voice_data_unit.h"
+
+class ldu : public voice_data_unit
+{
+private:
+
+ size_t m_hamming_error_count;
+ itpp::bvec m_raw_meta_data;
+
+protected:
+
+ virtual void do_correct_errors(bit_vector& frame_body);
+
+ virtual bool process_meta_data(bit_vector& frame_body);
+
+ virtual const itpp::bvec& raw_meta_data() const;
+
+public:
+
+ ldu(const_bit_queue& frame_body);
+
+ virtual bool meta_data_valid() const;
+};
+
+#endif // INCLUDED_LDU_H
diff --git a/op25/gr-op25/lib/ldu1.cc b/op25/gr-op25/lib/ldu1.cc
index 52f3b00..5acbf45 100644
--- a/op25/gr-op25/lib/ldu1.cc
+++ b/op25/gr-op25/lib/ldu1.cc
@@ -23,10 +23,19 @@
#include "ldu1.h"
+#include <itpp/base/vec.h>
+#include <itpp/base/converters.h>
+
+#include <boost/format.hpp>
+#include <iostream>
+
+#include "pickle.h"
+#include "value_string.h"
+
using std::string;
ldu1::ldu1(const_bit_queue& frame_body) :
- voice_data_unit(frame_body)
+ ldu(frame_body)
{
}
@@ -34,6 +43,64 @@ ldu1::~ldu1()
{
}
+void ldu1::do_correct_errors(bit_vector& frame_body)
+{
+ ldu::do_correct_errors(frame_body);
+
+ if (!process_meta_data(frame_body))
+ return;
+
+ const itpp::bvec& data = raw_meta_data();
+
+ std::stringstream ss;
+
+ m_meta_data.m.lcf = bin2dec(data.mid(0, 8));
+ m_meta_data.m.mfid = bin2dec(data.mid(8, 8));
+ ss << (boost::format("%s: LCF: 0x%02x, MFID: 0x%02x") % duid_str() % m_meta_data.m.lcf % m_meta_data.m.mfid);
+ if (m_meta_data.m.lcf == 0x00)
+ {
+ m_meta_data.m0.emergency = data[16];
+ m_meta_data.m0.reserved = bin2dec(data.mid(17, 15));
+ m_meta_data.m0.tgid = bin2dec(data.mid(32, 16));
+ m_meta_data.m0.source = bin2dec(data.mid(48, 24));
+ ss << (boost::format(", Emergency: 0x%02x, Reserved: 0x%04x, TGID: 0x%04x, Source: 0x%06x") % m_meta_data.m0.emergency % m_meta_data.m0.reserved % m_meta_data.m0.tgid % m_meta_data.m0.source);
+ }
+ else if (m_meta_data.m.lcf == 0x03)
+ {
+ m_meta_data.m3.reserved = bin2dec(data.mid(16, 8));
+ m_meta_data.m3.destination = bin2dec(data.mid(24, 24));
+ m_meta_data.m3.source = bin2dec(data.mid(48, 24));
+ ss << (boost::format(", Reserved: 0x%02x, Destination: 0x%06x, Source: 0x%06x") % m_meta_data.m3.reserved % m_meta_data.m3.destination % m_meta_data.m3.source);
+ }
+ else
+ {
+ ss << " (unknown LCF)";
+ }
+
+ if (logging_enabled()) std::cerr << ss.str() << std::endl;
+}
+
+std::string
+ldu1::snapshot() const
+{
+ pickle p;
+ p.add("duid", duid_str());
+ p.add("mfid", lookup(m_meta_data.m.mfid, MFIDS, MFIDS_SZ));
+ if ((m_meta_data.m.lcf == 0x00) || (m_meta_data.m.lcf == 0x03))
+ p.add("source", (boost::format("0x%06x") % m_meta_data.m0.source).str());
+ if (m_meta_data.m.lcf == 0x00)
+ p.add("tgid", (boost::format("0x%04x") % m_meta_data.m0.tgid).str());
+ if (m_meta_data.m.lcf == 0x03)
+ p.add("dest", (boost::format("0x%06x") % m_meta_data.m3.destination).str());
+ return p.to_string();
+}
+
+ldu1::combined_meta_data
+ldu1::meta_data() const
+{
+ return m_meta_data;
+}
+
string
ldu1::duid_str() const
{
diff --git a/op25/gr-op25/lib/ldu1.h b/op25/gr-op25/lib/ldu1.h
index b7baf55..9dce260 100644
--- a/op25/gr-op25/lib/ldu1.h
+++ b/op25/gr-op25/lib/ldu1.h
@@ -24,13 +24,45 @@
#ifndef INCLUDED_LDU1_H
#define INCLUDED_LDU1_H
-#include "voice_data_unit.h"
+#include "ldu.h"
/**
* P25 Logical Data Unit 1.
*/
-class ldu1 : public voice_data_unit
+class ldu1 : public ldu
{
+protected:
+
+ void do_correct_errors(bit_vector& frame_body);
+
+public:
+
+ struct base_meta_data
+ {
+ unsigned char lcf;
+ unsigned char mfid;
+ unsigned int source;
+ unsigned short reserved;
+ };
+
+ struct meta_data_0 : public base_meta_data
+ {
+ bool emergency;
+ unsigned short tgid;
+ };
+
+ struct meta_data_3 : public base_meta_data
+ {
+ unsigned int destination;
+ };
+
+ union combined_meta_data
+ {
+ base_meta_data m;
+ meta_data_0 m0;
+ meta_data_3 m3;
+ } m_meta_data;
+
public:
/**
@@ -50,6 +82,10 @@ public:
*/
std::string duid_str() const;
+ virtual std::string snapshot() const;
+
+ combined_meta_data meta_data() const;
+
};
#endif /* INCLUDED_LDU1_H */
diff --git a/op25/gr-op25/lib/ldu2.cc b/op25/gr-op25/lib/ldu2.cc
index c3e9932..76cfe1a 100644
--- a/op25/gr-op25/lib/ldu2.cc
+++ b/op25/gr-op25/lib/ldu2.cc
@@ -23,10 +23,18 @@
#include "ldu2.h"
+#include <itpp/base/vec.h>
+#include <itpp/base/converters.h>
+
+#include <boost/format.hpp>
+
+#include "pickle.h"
+#include "value_string.h"
+
using std::string;
ldu2::ldu2(const_bit_queue& frame_body) :
- voice_data_unit(frame_body)
+ ldu(frame_body)
{
}
@@ -39,3 +47,43 @@ ldu2::duid_str() const
{
return string("LDU2");
}
+
+std::string
+ldu2::snapshot() const
+{
+ pickle p;
+ p.add("duid", duid_str());
+ std::stringstream ss;
+ ss << "0x";
+ for (size_t n = 0; n < m_crypto_state.mi.size(); ++n)
+ ss << (boost::format("%02x") % (int)m_crypto_state.mi[n]);
+ p.add("mi", ss.str());
+ p.add("algid", lookup(m_crypto_state.algid, ALGIDS, ALGIDS_SZ));
+ p.add("kid", (boost::format("0x%04x") % m_crypto_state.kid).str());
+ return p.to_string();
+}
+
+void
+ldu2::do_correct_errors(bit_vector& frame_body)
+{
+ ldu::do_correct_errors(frame_body);
+
+ if (!process_meta_data(frame_body))
+ return;
+
+ const itpp::bvec& data = raw_meta_data();
+
+ for (int i = 0; i < 72; i += 8)
+ {
+ m_crypto_state.mi[i/8] = bin2dec(data.mid(i, 8));
+ }
+
+ m_crypto_state.algid = bin2dec(data.mid(72, 8));
+ m_crypto_state.kid = bin2dec(data.mid(80, 16));
+}
+
+struct CryptoState
+ldu2::crypto_state() const
+{
+ return m_crypto_state;
+}
diff --git a/op25/gr-op25/lib/ldu2.h b/op25/gr-op25/lib/ldu2.h
index d1e62b7..ce3deef 100644
--- a/op25/gr-op25/lib/ldu2.h
+++ b/op25/gr-op25/lib/ldu2.h
@@ -24,13 +24,22 @@
#ifndef INCLUDED_LDU2_H
#define INCLUDED_LDU2_H
-#include "voice_data_unit.h"
+#include "ldu.h"
+#include "crypto.h"
/**
* P25 Logical Data Unit 2.
*/
-class ldu2 : public voice_data_unit
+class ldu2 : public ldu, public crypto_state_provider
{
+private:
+
+ struct CryptoState m_crypto_state;
+
+protected:
+
+ void do_correct_errors(bit_vector& frame_body);
+
public:
/**
@@ -49,6 +58,10 @@ public:
* Returns a string describing the Data Unit ID (DUID).
*/
std::string duid_str() const;
+
+ virtual std::string snapshot() const;
+
+ struct CryptoState crypto_state() const;
};
#endif /* INCLUDED_LDU2_H */
diff --git a/op25/gr-op25/lib/message.cc b/op25/gr-op25/lib/message.cc
new file mode 100644
index 0000000..ab397cb
--- /dev/null
+++ b/op25/gr-op25/lib/message.cc
@@ -0,0 +1,63 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gnuradio/message.h>
+#include <cassert>
+#include <cstring>
+
+namespace gr {
+namespace op25 {
+
+static long s_ncurrently_allocated = 0;
+
+message::sptr message::make(long type, double arg1, double arg2, size_t length)
+{
+ return message::sptr(new message(type, arg1, arg2, length));
+}
+
+message::sptr
+message::make_from_string(const std::string s, long type, double arg1, double arg2)
+{
+ message::sptr m = message::make(type, arg1, arg2, s.size());
+ memcpy(m->msg(), s.data(), s.size());
+ return m;
+}
+
+message::message(long type, double arg1, double arg2, size_t length)
+ : d_type(type), d_arg1(arg1), d_arg2(arg2), d_buf(length)
+{
+ if (length == 0)
+ d_msg_start = d_msg_end = nullptr;
+ else {
+ d_msg_start = d_buf.data();
+ d_msg_end = d_msg_start + length;
+ }
+ s_ncurrently_allocated++;
+}
+
+message::~message()
+{
+ assert(d_next == 0);
+ s_ncurrently_allocated--;
+}
+
+std::string message::to_string() const
+{
+ return std::string((char*)d_msg_start, length());
+}
+
+long message_ncurrently_allocated() { return s_ncurrently_allocated; }
+
+} /* namespace op25 */
+} /* namespace gr */
diff --git a/op25/gr-op25/lib/msg_handler.cc b/op25/gr-op25/lib/msg_handler.cc
new file mode 100644
index 0000000..7521a73
--- /dev/null
+++ b/op25/gr-op25/lib/msg_handler.cc
@@ -0,0 +1,23 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005,2013 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <op25/msg_handler.h>
+
+namespace gr {
+namespace op25 {
+
+msg_handler::~msg_handler() {}
+
+} /* namespace op25 */
+} /* namespace gr */
diff --git a/op25/gr-op25/lib/msg_queue.cc b/op25/gr-op25/lib/msg_queue.cc
new file mode 100644
index 0000000..b42ba29
--- /dev/null
+++ b/op25/gr-op25/lib/msg_queue.cc
@@ -0,0 +1,113 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2005,2009,2013 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gnuradio/msg_queue.h>
+#include <stdexcept>
+
+namespace gr {
+namespace op25 {
+
+msg_queue::sptr msg_queue::make(unsigned int limit)
+{
+ return msg_queue::sptr(new msg_queue(limit));
+}
+
+msg_queue::msg_queue(unsigned int limit)
+ : d_not_empty(),
+ d_not_full(),
+ /*d_head(0), d_tail(0),*/ d_count(0),
+ d_limit(limit)
+{
+}
+
+msg_queue::~msg_queue() { flush(); }
+
+void msg_queue::insert_tail(message::sptr msg)
+{
+ if (msg->d_next)
+ throw std::invalid_argument("gr::msg_queue::insert_tail: msg already in queue");
+
+ gr::thread::scoped_lock guard(d_mutex);
+
+ while (full_p())
+ d_not_full.wait(guard);
+
+ if (d_tail == 0) {
+ d_tail = d_head = msg;
+ // msg->d_next = 0;
+ msg->d_next.reset();
+ } else {
+ d_tail->d_next = msg;
+ d_tail = msg;
+ // msg->d_next = 0;
+ msg->d_next.reset();
+ }
+ d_count++;
+ d_not_empty.notify_one();
+}
+
+message::sptr msg_queue::delete_head()
+{
+ gr::thread::scoped_lock guard(d_mutex);
+ message::sptr m;
+
+ while ((m = d_head) == 0)
+ d_not_empty.wait(guard);
+
+ d_head = m->d_next;
+ if (d_head == 0) {
+ // d_tail = 0;
+ d_tail.reset();
+ }
+
+ d_count--;
+ // m->d_next = 0;
+ m->d_next.reset();
+ d_not_full.notify_one();
+ return m;
+}
+
+message::sptr msg_queue::delete_head_nowait()
+{
+ gr::thread::scoped_lock guard(d_mutex);
+ message::sptr m;
+
+ if ((m = d_head) == 0) {
+ // return 0;
+ return message::sptr();
+ }
+
+ d_head = m->d_next;
+ if (d_head == 0) {
+ // d_tail = 0;
+ d_tail.reset();
+ }
+
+ d_count--;
+ // m->d_next = 0;
+ m->d_next.reset();
+ d_not_full.notify_one();
+ return m;
+}
+
+void msg_queue::flush()
+{
+ message::sptr m;
+
+ while ((m = delete_head_nowait()) != 0)
+ ;
+}
+
+} /* namespace op25 */
+} /* namespace gr */
diff --git a/op25/gr-op25/lib/op25.i b/op25/gr-op25/lib/op25.i
deleted file mode 100644
index 5c4716e..0000000
--- a/op25/gr-op25/lib/op25.i
+++ /dev/null
@@ -1,113 +0,0 @@
-/* -*- C++ -*- */
-
-%feature("autodoc", "1");
-
-%{
-#include <stddef.h>
-%}
-
-%include "exception.i"
-%import "gnuradio.i"
-
-%{
-#include "gnuradio/swig/gnuradio_swig_bug_workaround.h"
-#include "op25_fsk4_demod_ff.h"
-#include "op25_fsk4_slicer_fb.h"
-#include "op25_decoder_bf.h"
-#include "op25_pcap_source_b.h"
-%}
-
-// ----------------------------------------------------------------
-
-/*
- * This does some behind-the-scenes magic so we can
- * access fsk4_square_ff from python as fsk4.square_ff
- */
-GR_SWIG_BLOCK_MAGIC(op25, fsk4_demod_ff);
-
-/*
- * Publicly-accesible default constuctor function for op25_fsk4_demod_bf.
- */
-op25_fsk4_demod_ff_sptr op25_make_fsk4_demod_ff(gr::msg_queue::sptr queue, float sample_rate, float symbol_rate);
-
-class op25_fsk4_demod_ff : public gr_block
-{
-private:
- op25_fsk4_demod_ff(gr::msg_queue::sptr queue, float sample_rate, float symbol_rate);
-};
-
-// ----------------------------------------------------------------
-
-/*
- * This does some behind-the-scenes magic so we can invoke
- * op25_make_slicer_fb from python as op25.slicer_fbf.
- */
-GR_SWIG_BLOCK_MAGIC(op25, fsk4_slicer_fb);
-
-/*
- * Publicly-accesible default constuctor function for op25_decoder_bf.
- */
-op25_fsk4_slicer_fb_sptr op25_make_fsk4_slicer_fb(const std::vector<float> &slice_levels);
-
-/*
- * The op25_fsk4_slicer block. Takes a series of float samples and
- * partitions them into dibit symbols according to the slices_levels
- * provided to the constructor.
- */
-class op25_fsk4_slicer_fb : public gr_sync_block
-{
-private:
- op25_fsk4_slicer_fb (const std::vector<float> &slice_levels);
-};
-
-// ----------------------------------------------------------------
-
-/*
- * This does some behind-the-scenes magic so we can invoke
- * op25_make_decoder_bsf from python as op25.decoder_bf.
- */
-GR_SWIG_BLOCK_MAGIC(op25, decoder_bf);
-
-/*
- * Publicly-accesible default constuctor function for op25_decoder_bf.
- */
-op25_decoder_bf_sptr op25_make_decoder_bf();
-
-/**
- * The op25_decoder_bf block. Accepts a stream of dibit symbols and
- * produces an 8KS/s audio stream.
- */
-class op25_decoder_bf : public gr_block
-{
-private:
- op25_decoder_bf();
-public:
- const char *destination() const;
- gr::msg_queue::sptr get_msgq() const;
- void set_msgq(gr::msg_queue::sptr msgq);
-};
-
-// ----------------------------------------------------------------
-
-/*
- * This does some behind-the-scenes magic so we can invoke
- * op25_make_pcap_source_b from python as op25.pcap_source_b.
- */
-GR_SWIG_BLOCK_MAGIC(op25, pcap_source_b);
-
-/*
- * Publicly-accesible constuctor function for op25_pcap_source.
- */
-op25_pcap_source_b_sptr op25_make_pcap_source_b(const char *path, float delay);
-
-/*
- * The op25_pcap_source block. Reads symbols from a tcpdump-formatted
- * file and produces a stream of symbols of the appropriate size.
- */
-class op25_pcap_source_b : public gr_sync_block
-{
-private:
- op25_pcap_source_b(const char *path, float delay);
-};
-
-// ----------------------------------------------------------------
diff --git a/op25/gr-op25/lib/op25_hamming.h b/op25/gr-op25/lib/op25_hamming.h
index 0ab3c7a..b958996 100644
--- a/op25/gr-op25/lib/op25_hamming.h
+++ b/op25/gr-op25/lib/op25_hamming.h
@@ -3,6 +3,7 @@
#include <cstddef>
#include <stdint.h>
+#include <assert.h>
/*
* APCO Hamming(15,11,3) ecoder.
@@ -183,4 +184,18 @@ hamming_15_decode(uint16_t& cw)
return errs;
}
+static const uint32_t hmg1063EncTbl[64] = {
+ 0, 12, 3, 15, 7, 11, 4, 8, 11, 7, 8, 4, 12, 0, 15, 3,
+ 13, 1, 14, 2, 10, 6, 9, 5, 6, 10, 5, 9, 1, 13, 2, 14,
+ 14, 2, 13, 1, 9, 5, 10, 6, 5, 9, 6, 10, 2, 14, 1, 13,
+ 3, 15, 0, 12, 4, 8, 7, 11, 8, 4, 11, 7, 15, 3, 12, 0 };
+
+static const uint32_t hmg1063DecTbl[16] = {
+ 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 8, 1, 16, 32, 0 };
+
+static inline int hmg1063Dec (uint32_t Dat, uint32_t Par) {
+ assert ((Dat < 64) && (Par < 16));
+ return Dat ^ hmg1063DecTbl[hmg1063EncTbl[Dat] ^ Par];
+}
+
#endif /* INCLUDED_OP25_HAMMING_H */
diff --git a/op25/gr-op25/lib/op25_imbe_frame.h b/op25/gr-op25/lib/op25_imbe_frame.h
index fa00616..0ee0e7a 100644
--- a/op25/gr-op25/lib/op25_imbe_frame.h
+++ b/op25/gr-op25/lib/op25_imbe_frame.h
@@ -10,9 +10,54 @@
#include <vector>
typedef std::vector<bool> voice_codeword;
+typedef std::vector<uint8_t> packed_codeword;
typedef const std::vector<bool> const_bit_vector;
typedef std::vector<bool> bit_vector;
+static const uint16_t hdu_codeword_bits[658] = { // 329 symbols = 324 + 5 pad
+ 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
+ 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 144, 145, 146, 147,
+ 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
+ 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
+ 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195,
+ 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,
+ 212, 213, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229,
+ 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
+ 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
+ 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277,
+ 278, 279, 280, 281, 282, 283, 284, 285, 288, 289, 290, 291, 292, 293, 294, 295,
+ 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311,
+ 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327,
+ 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343,
+ 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 360, 361,
+ 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377,
+ 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393,
+ 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409,
+ 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425,
+ 426, 427, 428, 429, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443,
+ 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459,
+ 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475,
+ 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491,
+ 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 504, 505, 506, 507, 508, 509,
+ 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525,
+ 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541,
+ 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557,
+ 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573,
+ 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591,
+ 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607,
+ 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623,
+ 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639,
+ 640, 641, 642, 643, 644, 645, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657,
+ 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673,
+ 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689,
+ 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705,
+ 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 720, 721, 722, 723,
+ 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739,
+ 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755,
+ 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771,
+ 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787,
+ 788, 789 };
+
static const size_t nof_voice_codewords = 9, voice_codeword_sz = 144;
static const uint16_t imbe_ldu_NID_bits[] = {
@@ -251,8 +296,8 @@ pngen23(uint32_t& Pr)
* \param u0-u7 Result output vectors
*/
-static inline void
-imbe_header_decode(const voice_codeword& cw, uint32_t& u0, uint32_t& u1, uint32_t& u2, uint32_t& u3, uint32_t& u4, uint32_t& u5, uint32_t& u6, uint32_t& u7, uint32_t& E0, uint32_t& ET)
+static inline size_t
+imbe_header_decode(const voice_codeword& cw, uint32_t& u0, uint32_t& u1, uint32_t& u2, uint32_t& u3, uint32_t& u4, uint32_t& u5, uint32_t& u6, uint32_t& u7, uint32_t& E0, uint32_t& ET, bool bot_shift = true)
{
ET = 0;
@@ -294,7 +339,30 @@ imbe_header_decode(const voice_codeword& cw, uint32_t& u0, uint32_t& u1, uint32_
u6 = v6;
u7 = extract(cw, 137, 144);
- u7 <<= 1; /* so that bit0 is free (see note about BOT bit */
+ if (bot_shift)
+ u7 <<= 1; /* so that bit0 is free (see note about BOT bit */
+
+ return errs;
+}
+
+/*
+ * Pack 88 bit IMBE parameters into uint8_t vector
+ */
+static inline void
+imbe_pack(packed_codeword& cw, uint32_t u0, uint32_t u1, uint32_t u2, uint32_t u3, uint32_t u4, uint32_t u5, uint32_t u6, uint32_t u7)
+{
+ cw.empty();
+ cw.push_back(u0 >> 4);
+ cw.push_back(((u0 & 0xf) << 4) + (u1 >> 8));
+ cw.push_back(u1 & 0xff);
+ cw.push_back(u2 >> 4);
+ cw.push_back(((u2 & 0xf) << 4) + (u3 >> 8));
+ cw.push_back(u3 & 0xff);
+ cw.push_back(u4 >> 3);
+ cw.push_back(((u4 & 0x7) << 5) + (u5 >> 6));
+ cw.push_back(((u5 & 0x3f) << 2) + (u6 >> 9));
+ cw.push_back(u6 >> 1);
+ cw.push_back(((u6 & 0x1) << 7) + (u7 >> 1));
}
/* APCO IMBE header encoder.
diff --git a/op25/gr-op25/lib/value_string.cc b/op25/gr-op25/lib/value_string.cc
index ce96dc3..d5f0133 100644
--- a/op25/gr-op25/lib/value_string.cc
+++ b/op25/gr-op25/lib/value_string.cc
@@ -2,6 +2,7 @@
/*
* Copyright 2008 Steve Glass
+ * Copyright 2022 Matt Ames
*
* This file is part of OP25.
*
@@ -53,18 +54,40 @@ const value_string ALGIDS[] = {
{ 0x02, "FIREFLY Type 1" },
{ 0x03, "MAYFLY Type 1" },
{ 0x04, "SAVILLE" },
+ { 0x05, "Motorola Assigned - PADSTONE" },
{ 0x41, "BATON (Auto Odd)" },
/* Type III */
- { 0x80, "Plain" },
- { 0x81, "DES-OFB" },
- { 0x82, "2 key Triple DES" },
- { 0x83, "3 key Triple DES" },
- { 0x84, "AES-256" },
- /* Motorola proprietary */
- { 0x9F, "Motorola DES-XL" },
+ { 0x80, "Unencrypted" },
+ { 0x81, "DES-OFB, 56 bit key" },
+ { 0x83, "3 key Triple DES, 168 bit key" },
+ { 0x84, "AES-256-OFB" },
+ { 0x85, "AES-128-ECB"},
+ { 0x88, "AES-CBC"},
+ { 0x89, "AES-128-OFB"},
+ /* Motorola proprietary - some of these have been observed over the air,
+ some have been taken from firmware dumps on various devices, others
+ have come from the TIA's FTP website while it was still public,
+ from document "ALGID Guide 2015-04-15.pdf", and others have been
+ have been worked out with a little bit of "guesswork" ;) */
+ { 0x9F, "Motorola DES-XL 56-bit key" },
{ 0xA0, "Motorola DVI-XL" },
{ 0xA1, "Motorola DVP-XL" },
- { 0xAA, "Motorola ADP" },
+ { 0xA2, "Motorola DVI-XL-SPFL"},
+ { 0xA3, "Motorola HAYSTACK" },
+ { 0xA4, "Motorola Assigned - Unknown" },
+ { 0xA5, "Motorola Assigned - Unknown" },
+ { 0xA6, "Motorola Assigned - Unknown" },
+ { 0xA7, "Motorola Assigned - Unknown" },
+ { 0xA8, "Motorola Assigned - Unknown" },
+ { 0xA9, "Motorola Assigned - Unknown" },
+ { 0xAA, "Motorola ADP (40 bit RC4)" },
+ { 0xAB, "Motorola CFX-256" },
+ { 0xAC, "Motorola GOST 28147-89 (RFC 5830)" },
+ { 0xAD, "Motorola Assigned - LOCALIZED" },
+ { 0xAE, "Motorola Assigned - Unknown" },
+ { 0xAF, "Motorola AES+" },
+ { 0xB0, "Motorola DVP"},
+ { 0xD0, "Motorola LOCAL_BR"}
};
const size_t ALGIDS_SZ = sizeof(ALGIDS) / sizeof(ALGIDS[0]);
diff --git a/op25/gr-op25/lib/voice_data_unit.cc b/op25/gr-op25/lib/voice_data_unit.cc
index c15eb1c..56462b3 100644
--- a/op25/gr-op25/lib/voice_data_unit.cc
+++ b/op25/gr-op25/lib/voice_data_unit.cc
@@ -24,32 +24,325 @@
#include "voice_data_unit.h"
#include "op25_imbe_frame.h"
-#include <sstream>
+#include <map>
+#include <iostream>
+#include <boost/format.hpp>
+#include <stdio.h>
+
+#include <itpp/base/vec.h>
+#include <itpp/base/mat.h>
+#include <itpp/base/binary.h>
+#include <itpp/base/converters.h>
using namespace std;
-voice_data_unit::~voice_data_unit()
+static void vec_mod(itpp::ivec& vec, int modulus = 2)
{
+ for (int i = 0; i < vec.length(); ++i)
+ vec[i] = vec[i] % modulus;
}
+class cyclic_16_8_5_syndromes
+{
+public:
+ typedef map<unsigned char,unsigned short> SyndromeTableMap;
+
+ const static itpp::imat cyclic_16_8_5;
+private:
+ SyndromeTableMap m_syndrome_table;
+public:
+ inline const SyndromeTableMap table() const
+ {
+ return m_syndrome_table;
+ }
+
+ cyclic_16_8_5_syndromes(bool generate_now = false)
+ {
+ if (generate_now)
+ generate();
+ }
+
+ int generate()
+ {
+ if (m_syndrome_table.empty() == false)
+ return -1;
+
+ // n=16, k=8
+
+ // E1
+ itpp::ivec v("1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0");
+ itpp::ivec r(cyclic_16_8_5 * v);
+ vec_mod(r);
+ itpp::bvec b(to_bvec(r));
+ unsigned char ch = (unsigned char)bin2dec(b);
+ itpp::bvec bV(to_bvec(v));
+ unsigned short us = (unsigned short)bin2dec(bV);
+ m_syndrome_table.insert(make_pair(ch, us));
+
+ // E2
+ for (int i = 0; i <= (16 - 2); ++i)
+ {
+ itpp::ivec v2(v);
+ v2[15-i] = 1;
+ r = cyclic_16_8_5 * v2;
+ bV = itpp::to_bvec(v2);
+
+ vec_mod(r);
+ b = itpp::to_bvec(r);
+ unsigned char ch = (unsigned char)itpp::bin2dec(b);
+ unsigned short us = (unsigned short)itpp::bin2dec(bV);
+ m_syndrome_table.insert(make_pair(ch, us));
+ }
+
+ // E3 - disabled: min.d = 5, t=floor(5/2)=2
+ /*for (int i = 0; i <= (16 - 2); ++i)
+ {
+ for (int j = 0; j < i; ++j)
+ {
+ ivec v3(v);
+ v3[15-i] = 1;
+ v3[15-j] = 1;
+ r = cyclic_16_8_5 * v3;
+ bV = to_bvec(v3);
+
+ vec_mod(r);
+ b = to_bvec(r);
+ unsigned char ch = (unsigned char)bin2dec(b);
+ unsigned short us = (unsigned short)bin2dec(bV);
+ m_syndrome_table.insert(make_pair(ch, us));
+ }
+ }*/
+
+ return m_syndrome_table.size();
+ }
+};
+
+const itpp::imat cyclic_16_8_5_syndromes::cyclic_16_8_5(
+"0 0 1 1 1 1 0 0 1 0 0 0 0 0 0 0;"
+"1 0 0 1 1 1 1 0 0 1 0 0 0 0 0 0;"
+"0 1 0 0 1 1 1 1 0 0 1 0 0 0 0 0;"
+"0 0 0 1 1 0 1 1 0 0 0 1 0 0 0 0;"
+"1 0 1 1 0 0 0 1 0 0 0 0 1 0 0 0;"
+"1 1 1 0 0 1 0 0 0 0 0 0 0 1 0 0;"
+"1 1 1 1 0 0 1 0 0 0 0 0 0 0 1 0;"
+"0 1 1 1 1 0 0 1 0 0 0 0 0 0 0 1"
+);
+
+static cyclic_16_8_5_syndromes g_cyclic_16_8_5_syndromes(true);
+
+static int decode_cyclic_16_8_5(const itpp::ivec& vec, itpp::ivec& out)
+{
+ itpp::ivec vc(cyclic_16_8_5_syndromes::cyclic_16_8_5 * vec);
+ vec_mod(vc);
+ itpp::bvec vb(to_bvec(vc));
+
+ unsigned char ch = (unsigned char)itpp::bin2dec(vb);
+ if (ch == 0x00)
+ return 0;
+
+ const cyclic_16_8_5_syndromes::SyndromeTableMap& syndrome_table = g_cyclic_16_8_5_syndromes.table();
+ cyclic_16_8_5_syndromes::SyndromeTableMap::const_iterator it = syndrome_table.find(ch);
+ int j = 0;
+ while (it == syndrome_table.end())
+ {
+ ++j;
+ vc = itpp::concat(itpp::ivec("0 0 0 0 0 0 0 0"), vc); // Restore to 16 bits
+ vc.shift_left(vc[0]); // Rotate (s * x)
+ vc = cyclic_16_8_5_syndromes::cyclic_16_8_5 * vc;
+ vec_mod(vc);
+ vb = itpp::to_bvec(vc);
+ ch = (unsigned char)itpp::bin2dec(vb);
+ it = syndrome_table.find(ch);
+
+ if (j >= 15)
+ break;
+ }
+
+ if (it == syndrome_table.end())
+ {
+ return -1;
+ }
+
+ unsigned short us = it->second;
+ itpp::bvec es(itpp::dec2bin(16, us));
+ if (j > 0)
+ es.shift_right(es.mid(16-j, j)); // e
+ vb = itpp::to_bvec(vec);
+ vb -= es;
+ out = itpp::to_ivec(vb);
+
+ vc = cyclic_16_8_5_syndromes::cyclic_16_8_5 * out;
+ vec_mod(vc);
+ vb = itpp::to_bvec(vc);
+ if (itpp::bin2dec(vb) != 0x00)
+ {
+ return -1;
+ }
+
+ return 1;
+}
+
+static int decode_cyclic_16_8_5(itpp::ivec& vec)
+{
+ return decode_cyclic_16_8_5(vec, vec);
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+
voice_data_unit::voice_data_unit(const_bit_queue& frame_body) :
- abstract_data_unit(frame_body)
+ abstract_data_unit(frame_body),
+ d_lsdw(0),
+ d_lsdw_valid(false)
+{
+ memset(d_lsd_byte_valid, 0x00, sizeof(d_lsd_byte_valid));
+}
+
+voice_data_unit::~voice_data_unit()
{
}
void
voice_data_unit::do_correct_errors(bit_vector& frame_body)
{
+ if (logging_enabled()) fprintf(stderr, "\n");
+
+ d_lsd_byte_valid[0] = d_lsd_byte_valid[1] = false;
+ d_lsdw_valid = false;
+
+ itpp::ivec lsd1(16), lsd2(16);
+
+ for (int i = 0; i < 32; ++i)
+ {
+ int x = 1504 + i;
+ x = x + ((x / 70) * 2); // Adjust bit index for status
+ if (i < 16)
+ lsd1[i] = frame_body[x];
+ else
+ lsd2[i-16] = frame_body[x];
+ }
+
+ int iDecode1 = decode_cyclic_16_8_5(lsd1);
+ if (iDecode1 >= 0)
+ {
+ d_lsd_byte_valid[0] = true;
+ }
+ else if (iDecode1 == -1)
+ {
+ // Error
+ }
+ int iDecode2 = decode_cyclic_16_8_5(lsd2);
+ if (iDecode2 >= 0)
+ {
+ d_lsd_byte_valid[1] = true;
+ }
+ else
+ {
+ // Error
+ }
+
+ d_lsdw = 0;
+ for (int i = 0; i < 8; ++i)
+ d_lsdw = d_lsdw | (lsd1[i] << (7 - i)); // Little-endian byte swap
+ for (int i = 0; i < 8; ++i)
+ d_lsdw = d_lsdw | (lsd2[i] << (15 - i)); // Little-endian byte swap
+
+ if (d_lsd_byte_valid[0] && d_lsd_byte_valid[1])
+ d_lsdw_valid = true;
+}
+
+uint16_t
+voice_data_unit::lsdw() const
+{
+ return d_lsdw;
+}
+
+bool
+voice_data_unit::lsdw_valid() const
+{
+ return d_lsdw_valid;
+}
+
+static void extract(unsigned int u, size_t n, std::vector<bool>& out)
+{
+ for (size_t i = 0; i < n; ++i)
+ out.push_back(((u & (1 << (n-1-i))) != 0));
}
void
-voice_data_unit::do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe)
+voice_data_unit::do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe, crypto_module::sptr crypto_mod)
{
voice_codeword cw(voice_codeword_sz);
for(size_t i = 0; i < nof_voice_codewords; ++i) {
imbe_deinterleave(frame_body, cw, i);
+
+ unsigned int u0 = 0;
+ unsigned int u1,u2,u3,u4,u5,u6,u7;
+ unsigned int E0 = 0;
+ unsigned int ET = 0;
+
+ // PN/Hamming/Golay - etc.
+ size_t errs = imbe_header_decode(cw, u0, u1, u2, u3, u4, u5, u6, u7, E0, ET, false); // E0 & ET are not used, and are always returned as 0
+
+ crypto_algorithm::sptr algorithm;
+ if (crypto_mod)
+ algorithm = crypto_mod->current_algorithm();
+
+ if (algorithm)
+ {
+ if (i == 8)
+ {
+ d_lsdw ^= algorithm->generate(16); // LSDW
+ }
+
+ u0 ^= (int)algorithm->generate(12);
+ u1 ^= (int)algorithm->generate(12);
+ u2 ^= (int)algorithm->generate(12);
+ u3 ^= (int)algorithm->generate(12);
+
+ u4 ^= (int)algorithm->generate(11);
+ u5 ^= (int)algorithm->generate(11);
+ u6 ^= (int)algorithm->generate(11);
+
+ u7 ^= (int)algorithm->generate(7);
+
+ imbe_header_encode(cw, u0, u1, u2, u3, u4, u5, u6, (u7 << 1));
+ }
+
+ std::vector<bool> cw_raw;
+ extract(u0, 12, cw_raw);
+ extract(u1, 12, cw_raw);
+ extract(u2, 12, cw_raw);
+ extract(u3, 12, cw_raw);
+ extract(u4, 11, cw_raw);
+ extract(u5, 11, cw_raw);
+ extract(u6, 11, cw_raw);
+ extract(u7, 7, cw_raw);
+
+ const int cw_octets = 11;
+
+ std::vector<uint8_t> cw_vector(cw_octets);
+ extract(cw_raw, 0, (cw_octets * 8), &cw_vector[0]);
+
+ if (logging_enabled())
+ {
+ std::stringstream ss;
+ for (size_t n = 0; n < cw_vector.size(); ++n)
+ {
+ ss << (boost::format("%02x") % (int)cw_vector[n]);
+ if (n < (cw_vector.size() - 1))
+ ss << " ";
+ }
+
+ if (errs > 0)
+ ss << (boost::format(" (%llu errors)") % errs);
+
+ std:cerr << (boost::format("%s:\t%s") % duid_str() % ss.str()) << std::endl;
+ }
+
imbe.decode(cw);
}
+
+ if (logging_enabled()) fprintf(stderr, "%s: LSDW: 0x%04x, %s\n", duid_str().c_str(), d_lsdw, (d_lsdw_valid ? "valid" : "invalid"));
}
uint16_t
diff --git a/op25/gr-op25/lib/voice_data_unit.h b/op25/gr-op25/lib/voice_data_unit.h
index f57b365..6d49485 100644
--- a/op25/gr-op25/lib/voice_data_unit.h
+++ b/op25/gr-op25/lib/voice_data_unit.h
@@ -38,6 +38,17 @@ public:
*/
virtual ~voice_data_unit();
+ const static int LSD_BYTE_COUNT=2;
+
+private:
+
+ union {
+ uint8_t d_lsd_byte[LSD_BYTE_COUNT];
+ uint16_t d_lsdw;
+ };
+ bool d_lsdw_valid;
+ bool d_lsd_byte_valid[LSD_BYTE_COUNT];
+
protected:
/**
@@ -63,7 +74,7 @@ protected:
* \param frame_body The const_bit_vector to decode.
* \param imbe The imbe_decoder to use to generate the audio.
*/
- virtual void do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe);
+ virtual void do_decode_audio(const_bit_vector& frame_body, imbe_decoder& imbe, crypto_module::sptr crypto_mod);
/**
* Returns the expected size (in bits) of this data_unit. For
@@ -74,6 +85,10 @@ protected:
*/
virtual uint16_t frame_size_max() const;
+ virtual uint16_t lsdw() const;
+
+ virtual bool lsdw_valid() const;
+
};
#endif /* INCLUDED_VOICE_DATA_UNIT_H */
diff --git a/op25/gr-op25/lib/voice_du_handler.cc b/op25/gr-op25/lib/voice_du_handler.cc
index 3b52460..cd967bf 100644
--- a/op25/gr-op25/lib/voice_du_handler.cc
+++ b/op25/gr-op25/lib/voice_du_handler.cc
@@ -28,9 +28,10 @@
using namespace std;
-voice_du_handler::voice_du_handler(data_unit_handler_sptr next, imbe_decoder_sptr decoder) :
+voice_du_handler::voice_du_handler(data_unit_handler_sptr next, imbe_decoder_sptr decoder, crypto_module::sptr crypto_mod) :
data_unit_handler(next),
- d_decoder(decoder)
+ d_decoder(decoder),
+ d_crypto_mod(crypto_mod)
{
}
@@ -42,6 +43,6 @@ voice_du_handler::~voice_du_handler()
void
voice_du_handler::handle(data_unit_sptr du)
{
- du->decode_audio(*d_decoder);
+ du->decode_audio(*d_decoder, d_crypto_mod);
data_unit_handler::handle(du);
}
diff --git a/op25/gr-op25/lib/voice_du_handler.h b/op25/gr-op25/lib/voice_du_handler.h
index 9278ddd..6a4f3a1 100644
--- a/op25/gr-op25/lib/voice_du_handler.h
+++ b/op25/gr-op25/lib/voice_du_handler.h
@@ -26,6 +26,7 @@
#include "data_unit_handler.h"
#include "imbe_decoder.h"
+#include "crypto.h"
#include <boost/noncopyable.hpp>
@@ -43,7 +44,7 @@ public:
* \param next The next data_unit_handler in the chain.
* \param decoder An imbe_decoder_sptr to the IMBE decoder to use.
*/
- voice_du_handler(data_unit_handler_sptr next, imbe_decoder_sptr decoder);
+ voice_du_handler(data_unit_handler_sptr next, imbe_decoder_sptr decoder, crypto_module::sptr crypto_mod = crypto_module::sptr()); // TODO: Add capability to decoder_ff (remove default argument)
/**
* voice_du_handler virtual destructor.
@@ -64,6 +65,8 @@ private:
*/
imbe_decoder_sptr d_decoder;
+ crypto_module::sptr d_crypto_mod;
+
};
#endif /* INCLUDED_VOICE_DU_HANDLER_H */
diff --git a/op25/gr-op25/python/CMakeLists.txt b/op25/gr-op25/python/CMakeLists.txt
index 03361a2..e497faa 100644
--- a/op25/gr-op25/python/CMakeLists.txt
+++ b/op25/gr-op25/python/CMakeLists.txt
@@ -31,7 +31,7 @@ endif()
GR_PYTHON_INSTALL(
FILES
__init__.py
- DESTINATION ${GR_PYTHON_DIR}/op25
+ DESTINATION ${OP25_PYTHON_DIR}/op25
)
########################################################################
diff --git a/op25/gr-op25/python/__init__.py b/op25/gr-op25/python/__init__.py
index f9ce6d5..7338b06 100644
--- a/op25/gr-op25/python/__init__.py
+++ b/op25/gr-op25/python/__init__.py
@@ -31,9 +31,9 @@ try:
from dl import RTLD_GLOBAL as _RTLD_GLOBAL
except ImportError:
try:
- from DLFCN import RTLD_GLOBAL as _RTLD_GLOBAL
+ from DLFCN import RTLD_GLOBAL as _RTLD_GLOBAL
except ImportError:
- pass
+ pass
if _RTLD_GLOBAL != 0:
_dlopenflags = sys.getdlopenflags()
@@ -42,7 +42,7 @@ if _RTLD_GLOBAL != 0:
# import swig generated symbols into the op25 namespace
-from op25_swig import *
+from .op25_swig import *
# import any pure python here
#
diff --git a/op25/gr-op25/python/op25/bindings/message_python.cc b/op25/gr-op25/python/op25/bindings/message_python.cc
new file mode 100644
index 0000000..0e6e469
--- /dev/null
+++ b/op25/gr-op25/python/op25/bindings/message_python.cc
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2022 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+/***********************************************************************************/
+/* This file is automatically generated using bindtool and can be manually edited */
+/* The following lines can be configured to regenerate this file during cmake */
+/* If manual edits are made, the following tags should be modified accordingly. */
+/* BINDTOOL_GEN_AUTOMATIC(0) */
+/* BINDTOOL_USE_PYGCCXML(0) */
+/* BINDTOOL_HEADER_FILE(message.h) */
+/* BINDTOOL_HEADER_FILE_HASH(e324acfee988515a91a4759680dbabbf) */
+/***********************************************************************************/
+
+#include <pybind11/complex.h>
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+namespace py = pybind11;
+
+#include <gnuradio/op25/message.h>
+// pydoc.h is automatically generated in the build directory
+#include <message_pydoc.h>
+
+void bind_message(py::module& m)
+{
+
+ using message = ::gr::op25::message;
+
+
+ py::class_<message,
+ std::shared_ptr<message>>(m, "message", D(message))
+
+ .def(py::init(&message::make),
+ py::arg("type") = 0,
+ py::arg("arg1") = 0,
+ py::arg("arg2") = 0,
+ py::arg("length") = 0,
+ D(message,make)
+ )
+
+
+
+
+
+
+ .def_static("make_from_string",&message::make_from_string,
+ py::arg("s"),
+ py::arg("type") = 0,
+ py::arg("arg1") = 0,
+ py::arg("arg2") = 0,
+ D(message,make_from_string)
+ )
+
+
+
+ .def("type",&message::type,
+ D(message,type)
+ )
+
+
+
+ .def("arg1",&message::arg1,
+ D(message,arg1)
+ )
+
+
+
+ .def("arg2",&message::arg2,
+ D(message,arg2)
+ )
+
+
+
+ .def("set_type",&message::set_type,
+ py::arg("type"),
+ D(message,set_type)
+ )
+
+
+
+ .def("set_arg1",&message::set_arg1,
+ py::arg("arg1"),
+ D(message,set_arg1)
+ )
+
+
+
+ .def("set_arg2",&message::set_arg2,
+ py::arg("arg2"),
+ D(message,set_arg2)
+ )
+
+
+
+ .def("msg",&message::msg,
+ D(message,msg)
+ )
+
+
+
+ //.def("to_string",&message::to_string,
+ // D(message,to_string)
+ //)
+ .def("to_string",
+ [](std::shared_ptr<message> msg) {
+ std::string s = msg->to_string();
+ return py::bytes(s); // Return the data without transcoding
+ })
+
+ ;
+
+
+
+ m.def("message_ncurrently_allocated",&::gr::op25::message_ncurrently_allocated,
+ D(message_ncurrently_allocated)
+ );
+
+
+
+}
+
+
+
+
+
+
+
+
diff --git a/op25/gr-op25/python/op25/bindings/msg_handler_python.cc b/op25/gr-op25/python/op25/bindings/msg_handler_python.cc
new file mode 100644
index 0000000..ae5c488
--- /dev/null
+++ b/op25/gr-op25/python/op25/bindings/msg_handler_python.cc
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2022 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+/***********************************************************************************/
+/* This file is automatically generated using bindtool and can be manually edited */
+/* The following lines can be configured to regenerate this file during cmake */
+/* If manual edits are made, the following tags should be modified accordingly. */
+/* BINDTOOL_GEN_AUTOMATIC(0) */
+/* BINDTOOL_USE_PYGCCXML(0) */
+/* BINDTOOL_HEADER_FILE(msg_handler.h) */
+/* BINDTOOL_HEADER_FILE_HASH(668ae41ad9b9d463886fcf60a87e9ede) */
+/***********************************************************************************/
+
+#include <pybind11/complex.h>
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+namespace py = pybind11;
+
+#include <gnuradio/op25/msg_handler.h>
+// pydoc.h is automatically generated in the build directory
+#include <msg_handler_pydoc.h>
+
+void bind_msg_handler(py::module& m)
+{
+
+ using msg_handler = ::gr::op25::msg_handler;
+
+
+ py::class_<msg_handler,
+ std::shared_ptr<msg_handler>>(m, "msg_handler", D(msg_handler))
+
+ // .def(py::init<>(),D(msg_handler,msg_handler,0))
+ // .def(py::init<gr::op25::msg_handler const &>(), py::arg("arg0"),
+ // D(msg_handler,msg_handler,1)
+ // )
+
+
+
+ .def("handle",&msg_handler::handle,
+ py::arg("msg"),
+ D(msg_handler,handle)
+ )
+
+ ;
+
+
+
+
+}
+
+
+
+
+
+
+
+
diff --git a/op25/gr-op25/python/op25/bindings/msg_queue_python.cc b/op25/gr-op25/python/op25/bindings/msg_queue_python.cc
new file mode 100644
index 0000000..63027cd
--- /dev/null
+++ b/op25/gr-op25/python/op25/bindings/msg_queue_python.cc
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2022 Free Software Foundation, Inc.
+ *
+ * This file is part of GNU Radio
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ *
+ */
+
+/***********************************************************************************/
+/* This file is automatically generated using bindtool and can be manually edited */
+/* The following lines can be configured to regenerate this file during cmake */
+/* If manual edits are made, the following tags should be modified accordingly. */
+/* BINDTOOL_GEN_AUTOMATIC(0) */
+/* BINDTOOL_USE_PYGCCXML(0) */
+/* BINDTOOL_HEADER_FILE(msg_queue.h) */
+/* BINDTOOL_HEADER_FILE_HASH(3f70adbde5e636fca8dc78e0505b06fd) */
+/***********************************************************************************/
+
+#include <pybind11/complex.h>
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+namespace py = pybind11;
+
+#include <gnuradio/op25/msg_queue.h>
+// pydoc.h is automatically generated in the build directory
+#include <msg_queue_pydoc.h>
+
+void bind_msg_queue(py::module& m)
+{
+
+ using msg_queue = ::gr::op25::msg_queue;
+
+
+ py::class_<msg_queue,
+ std::shared_ptr<msg_queue>>(m, "msg_queue", D(msg_queue))
+
+ .def(py::init(&msg_queue::make),
+ py::arg("limit") = 0,
+ D(msg_queue,make)
+ )
+
+
+
+
+
+
+ .def("handle",&msg_queue::handle,
+ py::arg("msg"),
+ D(msg_queue,handle)
+ )
+
+
+
+ .def("insert_tail",&msg_queue::insert_tail,
+ py::arg("msg"),
+ D(msg_queue,insert_tail)
+ )
+
+
+
+ .def("delete_head",&msg_queue::delete_head, py::call_guard<py::gil_scoped_release>(),
+ D(msg_queue,delete_head)
+ )
+
+
+
+ .def("delete_head_nowait",&msg_queue::delete_head_nowait,
+ D(msg_queue,delete_head_nowait)
+ )
+
+
+
+ .def("flush",&msg_queue::flush,
+ D(msg_queue,flush)
+ )
+
+
+
+ .def("empty_p",&msg_queue::empty_p,
+ D(msg_queue,empty_p)
+ )
+
+
+
+ .def("full_p",&msg_queue::full_p,
+ D(msg_queue,full_p)
+ )
+
+
+
+ .def("count",&msg_queue::count,
+ D(msg_queue,count)
+ )
+
+
+
+ .def("limit",&msg_queue::limit,
+ D(msg_queue,limit)
+ )
+
+ ;
+
+
+
+
+}
+
+
+
+
+
+
+
+
diff --git a/op25/gr-op25/swig/CMakeLists.txt b/op25/gr-op25/swig/CMakeLists.txt
index e99226f..fd7bd85 100644
--- a/op25/gr-op25/swig/CMakeLists.txt
+++ b/op25/gr-op25/swig/CMakeLists.txt
@@ -21,7 +21,7 @@
# Include swig generation macros
########################################################################
find_package(SWIG)
-find_package(PythonLibs 2)
+find_package(PythonLibs 3)
if(NOT SWIG_FOUND OR NOT PYTHONLIBS_FOUND)
return()
endif()
@@ -31,9 +31,7 @@ include(GrPython)
########################################################################
# Setup swig generation
########################################################################
-foreach(incdir ${GNURADIO_RUNTIME_INCLUDE_DIRS})
- list(APPEND GR_SWIG_INCLUDE_DIRS ${incdir}/gnuradio/swig)
-endforeach(incdir)
+set(GR_SWIG_INCLUDE_DIRS $<TARGET_PROPERTY:gnuradio::runtime_swig,INTERFACE_INCLUDE_DIRECTORIES>)
set(GR_SWIG_LIBRARIES gnuradio-op25)
set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/op25_swig_doc.i)
@@ -44,7 +42,7 @@ GR_SWIG_MAKE(op25_swig op25_swig.i)
########################################################################
# Install the build swig module
########################################################################
-GR_SWIG_INSTALL(TARGETS op25_swig DESTINATION ${GR_PYTHON_DIR}/op25)
+GR_SWIG_INSTALL(TARGETS op25_swig DESTINATION ${OP25_PYTHON_DIR}/op25)
########################################################################
# Install swig .i files for development
diff --git a/op25/gr-op25/swig/op25_swig.i b/op25/gr-op25/swig/op25_swig.i
index 0762474..bd654d5 100644
--- a/op25/gr-op25/swig/op25_swig.i
+++ b/op25/gr-op25/swig/op25_swig.i
@@ -1,5 +1,7 @@
/* -*- c++ -*- */
+%include "pycontainer.swg"
+
#define OP25_API
%include "gnuradio.i" // the common stuff
@@ -15,6 +17,11 @@
#include "op25/pcap_source_b.h"
%}
+%template(key_type) std::vector<unsigned char>;
+// This causes SWIG to segfault
+//%template(key_map_type) std::map<uint16_t,key_type >;
+%template(key_map_type) std::map<uint16_t,std::vector<unsigned char> >;
+
%include "op25/fsk4_demod_ff.h"
GR_SWIG_BLOCK_MAGIC2(op25, fsk4_demod_ff);
%include "op25/fsk4_slicer_fb.h"
diff --git a/op25/gr-op25_repeater/CMakeLists.txt b/op25/gr-op25_repeater/CMakeLists.txt
index f998705..dc1d8e7 100644
--- a/op25/gr-op25_repeater/CMakeLists.txt
+++ b/op25/gr-op25_repeater/CMakeLists.txt
@@ -64,6 +64,31 @@ if(NOT Boost_FOUND)
endif()
########################################################################
+# Find gnuradio build dependencies
+########################################################################
+find_package(CppUnit)
+
+set(ENABLE_PYTHON "TRUE" CACHE BOOL "enable python")
+cmake_policy(SET CMP0012 NEW)
+
+# To run a more advanced search for GNU Radio and it's components and
+# versions, use the following. Add any components required to the list
+# of GR_REQUIRED_COMPONENTS (in all caps) and change "version" to the
+# minimum API compatible version required.
+#
+set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
+# find_package(Gnuradio "version")
+set(MIN_GR_VERSION "3.8.0")
+find_package(Gnuradio REQUIRED)
+if("${Gnuradio_VERSION}" VERSION_LESS MIN_GR_VERSION)
+ MESSAGE(FATAL_ERROR "GnuRadio version required: >=\"" ${MIN_GR_VERSION} "\" found: \"" ${Gnuradio_VERSION} "\"")
+endif()
+
+if(NOT CPPUNIT_FOUND)
+ message(FATAL_ERROR "CppUnit required to compile op25_repeater")
+endif()
+
+########################################################################
# Install directories
########################################################################
include(GrPlatform) #define LIB_SUFFIX
@@ -81,31 +106,6 @@ set(GR_PKG_LIBEXEC_DIR ${GR_LIBEXEC_DIR}/${CMAKE_PROJECT_NAME})
set(GRC_BLOCKS_DIR ${GR_PKG_DATA_DIR}/grc/blocks)
########################################################################
-# Find gnuradio build dependencies
-########################################################################
-find_package(GnuradioRuntime)
-find_package(CppUnit)
-
-# To run a more advanced search for GNU Radio and it's components and
-# versions, use the following. Add any components required to the list
-# of GR_REQUIRED_COMPONENTS (in all caps) and change "version" to the
-# minimum API compatible version required.
-#
-# set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER ...)
-# find_package(Gnuradio "version")
-if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
- set(GR_REQUIRED_COMPONENTS RUNTIME BLOCKS FILTER PMT)
- find_package(Gnuradio)
-endif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
-
-if(NOT GNURADIO_RUNTIME_FOUND)
- message(FATAL_ERROR "GnuRadio Runtime required to compile op25_repeater")
-endif()
-if(NOT CPPUNIT_FOUND)
- message(FATAL_ERROR "CppUnit required to compile op25_repeater")
-endif()
-
-########################################################################
# Setup the include and linker paths
########################################################################
include_directories(
diff --git a/op25/gr-op25_repeater/apps/900.tsv b/op25/gr-op25_repeater/apps/900.tsv
new file mode 100644
index 0000000..6cc8224
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/900.tsv
@@ -0,0 +1,2 @@
+"Sysname" "Control Channel List" "Offset" "NAC" "Modulation" "TGID Tags File" "Whitelist" "Blacklist" "Center Frequency"
+"Fake" "924.975" "0" "0x293" "FSK4" "" "" "" "924.95"
diff --git a/op25/gr-op25_repeater/apps/README b/op25/gr-op25_repeater/apps/README
index f02f687..513f0b6 100644
--- a/op25/gr-op25_repeater/apps/README
+++ b/op25/gr-op25_repeater/apps/README
@@ -37,6 +37,7 @@ should open. You must click on the terminal window to restore it to
focus, otherwise all keystrokes are consumed by gnuplot. Once in the
terminal window there are several keyboard commands:
h - hold
+ H - hold/goto the specified tgid
l - lockout
s - skip
q - quit program
@@ -52,6 +53,19 @@ to suspend the program and examine stderr.2 for error messages. If there
is a traceback please report the full traceback (and the command line) to
the mail list.
+REMOTE TERMINAL
+===============
+Adding (for example) "-l 56111" to the rx.py command starts rx.py but does
+not attach a curses terminal. Instead the program runs as normal in the
+foreground (hit CTRL-C to end rx.py as desired). To connect to a running
+instance of rx.py, (in this example)
+ ./terminal.py 127.0.0.1 56111
+NOTE: rx.py and terminal.py need not run on the same machine. The machine
+where terminal.py is running need not have an SDR device directly attached;
+but GNU Radio (and OP25) must be available.
+
+WARNING: there is no security or encryption on the UDP port.
+
EXTERNAL UDP AUDIO SERVER
=========================
Starting rx.py with the "-w -W host" options directs udp audio data to
@@ -129,6 +143,8 @@ Options:
-H HAMLIB_MODEL, --hamlib-model=HAMLIB_MODEL
specify model for hamlib
-s SEEK, --seek=SEEK ifile seek in K
+ -l TERMINAL_TYPE, --terminal-type=TERMINAL_TYPE
+ 'curses' or udp port or 'http:host:port'
-L LOGFILE_WORKERS, --logfile-workers=LOGFILE_WORKERS
number of demodulators to instantiate
-S SAMPLE_RATE, --sample-rate=SAMPLE_RATE
@@ -161,3 +177,67 @@ Options:
-2, --phase2-tdma enable phase2 tdma decode
-Z DECIM_AMT, --decim-amt=DECIM_AMT
spectrum decimation
+
+HTTP CONSOLE
+============
+New as of Jan. 2018, the OP25 dashboard is accessible to any Web browser over
+HTTP. Include the option "-l http:<host>:<port>" when starting the rx.py app,
+where <host> is either "127.0.0.1" to limit access from only this host, or
+"0.0.0.0" if HTTP access from anywhere is to be allowed*. After rx.py has
+started it begins listening on the specified port for incoming connections.
+
+Once connected the status page should automatically update to show trunking
+system status, frequency list, adjacent sites, and other data.
+
+Example: you have started rx.py with the option "-l http:127.0.0.1:8080".
+To connect, set your web browser URL to "http://127.0.0.1:8080".
+
+If one or more plot modes has been selected using the "-P" option you may
+view them by clicking the "PLOT" button. The plots are updated approx.
+every five seconds. Click "STATUS" to return to the main status page.
+
+*WARNING*: there is no security or encryption. Be careful when using "0.0.0.0"
+as the listening address since anyone with access to the network can connect.
+
+NOTE: the python-pyramid package is required when using this option. It can
+be installed by running
+ sudo apt-get install python-pyramid
+
+MULTI-RECEIVER
+==============
+The multi_rx.py app allows an arbitrary number of SDR devices and channels
+to be defined. Each channel may have one or more plot windows attached.
+
+Configuration is achieved via a json file (see cfg.json for an example).
+In this version, channels are automatically assigned to the first device
+found whose frequency span includes the selected frequency.
+
+As of this writing (winter, 2017), neither trunking nor P25 P2/TDMA are
+supported in multi_rx.py. The rx.py app should be used for P25 trunking,
+for either P1/FDMA or P2/TDMA.
+
+Below is a summary of the major config file keys:
+demod_type: 'cqpsk' for qpsk p25 only; 'fsk4' for ysf/dstar/dmr/fsk4 p25
+filter_type: 'rc' for p25; 'rrc' for dmr and ysf; 'gmsk' for d-star
+plot: 'fft', 'constellation', 'datascope', 'symbol'
+ [if more than one plot desired, provide a comma-separated list]
+destination: 'udp://host:port' or 'file://<filename>'
+name: arbitrary string used to identify channels and devices
+
+bug: 'fft' and 'constellation' currently mutually exclusive
+bug: 'gmsk' needs work
+
+Note: DMR audio for the second time slot is sent on the specified port number
+plus two. In the example 'udp://127.0.0.1:56122', audio for the first slot
+would use 56122; and 56124 for the second.
+
+The command line options for multi_rx:
+Usage: multi_rx.py [options]
+
+Options:
+ -h, --help show this help message and exit
+ -c CONFIG_FILE, --config-file=CONFIG_FILE
+ specify config file name
+ -v VERBOSITY, --verbosity=VERBOSITY
+ message debug level
+ -p, --pause block on startup
diff --git a/op25/gr-op25_repeater/apps/README-July-2021 b/op25/gr-op25_repeater/apps/README-July-2021
new file mode 100644
index 0000000..911a07e
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/README-July-2021
@@ -0,0 +1,291 @@
+
+New features in this release (June, 2021)
+=========================================
+
+1. With thanks to OP25 user Triptolemus, the web client is enhanced to
+ include comprehensive logs of recent control channel signalling and
+ call activity. Many other features are also added:
+ * unit ID (subscriber ID) tagging - similar to the existing TGID
+ tags setup.
+ * tag color coding (for both TGID and SUID tags).
+ * tag ranges and wildcarding - for both the TGID and SUID tag maps,
+ a single definition line may be used to create tags for a range of
+ IDs.
+ * real time system frequency status table
+ * smart colors
+ * user settings (colors, preferences) may be edited and saved via a
+ convenient set of web forms and applications
+
+2. The multi_rx app adds extensions to include trunked P25 call following
+ concurrent with full-time tracking of one or more P25 control channels.
+ If necessary, additional SDR devices may be configured to allow full
+ coverage of all control channels without loss of CC data even during voice
+ call reception. Several new command line options to multi_rx have been
+ added - -T (trunking TSV file) -l (terminal type) as well as -X and -U,
+ all having the same meaning as in rx.py.
+
+3. Control channel logging to SQL database is added. For details see the
+ section on the Flask Datatables App, below.
+
+4. Experimental TDMA Control Channel support
+
+Installation
+============
+
+First locate and change to your current OP25 install build/ directory and
+run the command
+ sude make uninstall
+
+Since this version includes library C++ code updates it requires a full
+source rebuild via the standard install script (install.sh).
+
+The installation will include one or more SDR receivers, depending
+on the the amount of spectrum utilized by the target trunking system, how
+many control channels are to be monitored concurrently, and whether voice
+call following is desired.
+
+ * When SQL logging is used, it is most desirable to keep the control channel
+ tuned in 100% of the time. With a single SDR this is not possible when the
+ range of control channel and voice channel frequencies exceed the tuning band
+ of the SDR.
+ * When voice call following is to be used, a separate voice channel must be
+ defined for each device over which voice reception is desired. It is
+ redundant to have more than one voice channel assigned to a given device.
+ * A separate SDR can be dedicated to voice call following if needed. If there
+ is already a frequency-locked ("tunable"=false) device whose tuning band
+ includes all desired voice frequencies, a separate voice SDR is not needed.
+ * This version of OP25 follows the same voice call system as in rx.py.
+ That is, a single call at a time is monitored and a 3-second (nominal)
+ time delay is applied at the end of each call to catch possible replies.
+ * A single device may be shared by multiple channels. When more than one channel
+ is assigned to a device, the device should be tuned to a fixed frequency and
+ "tunable" should be set to "false".
+
+Simplified example: Of all frequencies (control and voice) in the system,
+the lowest frequency is 464.05 and the highest is 464.6. An RTL-SDR having
+a maximum sample rate of 2.56 MHz is to be used. Since the band required is
+0.55 MHz, a single SDR configuration can be used. The sample rate for
+this example, 2.56 MHz, could be reduced to 1.0 MHz to conserve CPU.
+
+NOTE: Proper logging of CC activity requires two things:
+ 1) Device and/or channel resources must be allocated so that there
+ is 100% time coverage of the control channel. Voice channel
+ operation on the same SDR can only occur when the entire system
+ fits within the SDR tuning band.
+ 2) Control channel reception and demodulation must be 100% error-free.
+ Occasional errors are potentially corrected by the FEC but a better
+ course is to increase the receive SNR and/or decrease the system BER.
+
+Notes on JSON Configuration/Parameters
+======================================
+Example json config files are included in the apps/ directory. You
+should choose one of these files (as described above) and make edits
+to a working copy of the file. The name of the resulting JSON config
+file must be passed to multi_rx.py via the "-c" parameter.
+ cfg-trunk.json - When all system frequencies (CC and VC) will fit
+ within the SDR tuning band (without retuning the SDR),
+ or voice decode is not needed.
+ cfg-trunk2.json - When two SDRs are needed to cover both CC and all VCs.
+ cfg-trunkx.json - Large system example with voice following and several CCs.
+
+There are several key values to note:
+"tunable" In the single-SDR configuration where all system frequencies
+ (primary/secondary CCs and VCs) are within the SDR band,
+ you should set this to "false". In this case the SDR is
+ fixed-tuned and remains on a single frequency, the center
+ frequency. You must set the center frequency to a value
+ halfway between the lowest and highest frequencies in the
+ system, via the device "frequency" setting.
+"frequency" See above. When "tunable" is set to "true" this value must
+ be filled in. Otherwise the value is used to set the device
+ frequency at startup time (must be a valid frequency for the
+ device). The device will most likely be retuned one or more
+ times during execution.
+"decode" Assists multi_rx in assigning channels to the proper device(s).
+ If the value of "decode" starts with the string "p25_decoder",
+ multi_rx uses the p25 decoder instead of its standard decoder.
+
+Note that "tunable" is a device-specific parameter, and that "decode" is a
+channel-specific parameter. Also, while both the device and channel define
+the "frequency" parameter, the description above is for device entries. A
+channel entry may also define a frequency, but the channel "frequency" parameter
+is ignored (in this version).
+
+When the p25_decoder is used, there is a parameter string consisting of a
+colon-separated list of parameters with each parameter in the form "key=value",
+with the parameter string defined as the value of the "decode" parameter.
+
+Here are two examples:
+ "decode": "p25_decoder:role=cc:dev=rtl11:nac=0x4e1", [control]
+ "decode": "p25_decoder:role=vc:dev=rtl12_vc", [voice]
+The valid parameter keywords are:
+"p25_decoder" Required for trunked P25. This keyword introduces the
+ parameter list. There is no value.
+"role" Must be set to "vc" or "cc".
+"dev" Must be set to the name of the device. Each channel is
+ assigned to exactly one device.
+"nac" Comma-separated list of NACs for the channel. Only trunked
+ systems having a NAC in the list can be assigned to this
+ channel.
+"sysid" Comma-separated list of SYSIDs for the channel. Only trunked
+ systems having a SYSID in the list can be assigned to this
+ channel.
+
+The "nac" and "sysid" options are only checked for control channels ("role=cc").
+Values starting with "0x" are hexadecimal; otherwise decimal values are assumed .
+A blank/default value for "sysid" and/or "nac" indicates that parameter is not
+checked.
+
+The following startup messages in the stderr log are typical in a 2-SDR config:
+ assigning channel "p25 control channel" (channel id 1) to device "rtl11_cc"
+ assigning channel "p25 voice channel" (channel id 2) to device "rtl12_vc"
+Note that the channel ID displayed in the "tuning error +/-1200" messages can be
+linked to the specific device(s) encountering the error using this ID.
+
+Experimental TDMA Control Channel Support
+=========================================
+
+The following specifics detail the JSON configuration file channel parameters
+needed to define a TDMA control channel:
+ "demod_type": "cqpsk",
+ "if_rate": 24000,
+ "symbol_rate": 6000,
+ "decode": "p25_decoder:role=cc:dev=<device-name>:nac=0x4e1",
+The NAC should be changed to match that of the system being received, and
+<device-name> should refer to the assigned device.
+
+Colors and Tags for Talkgroup and Radio IDs
+===========================================
+Tags and colors are defined in two TSV files, one for TGIDs and one for SUIDs.
+The TSV file format, compatible with earlier versions of OP25 has the TAB
+separated columns defined as:
+column one: decimal TG or SU ID. May contain wildcards (see below)
+column two: tag text (string)
+column three(optional): encoded priority/color value, decimal (see below)
+The color code is directly mapped by client JS into style sheet (CSS) colors.
+If only two columns are present the third column is defaulted to zero.
+
+The file names of the two files are specified (comma-separated) in the
+trunking TSV "TGID Tags File" column (the trunking TSV in turn is the
+file referred to by the "-T" command option of rx.py or multi_rx.py).
+The talkgroup tags file name is specified first, followed by a comma,
+then the SUID tags file. The SUID tags file can't be specified alone.
+
+Wildcard IDs (column one) may be (for example)
+ * 123-678 [all IDs in range, inclusive, are set to same tag/color]
+ * 444.... [all IDs from 4440000 to 4449999]
+ * 456* [all IDs starting with 456]
+ * 54321 [defines that one ID]
+
+Column three contains a color value from 0-99 (decimal).
+In the TGID file (only), the column value also contains a talkgroup
+priority, encoded as follows:
+ - the low-order two decimal digits (tens and units digits) are the
+ color code
+ - the remaining upper-order decimal digits (hundreds digit and above) are
+ the priority value for talkgroup pre-emption purposes.
+
+Setup SQL Log Database (Optional)
+=================================
+
+This addition provides a permanent server-side log of control channel
+activity via logging to an SQL database. See the next section for details
+on installing and using the log viewer.
+
+1. Make sure that sqlite3 is installed in python
+
+ WARNING: OP25 MUST NOT BE RUNNING DURING THIS STEP
+2. Initialize DB (any existing DB data will be destroyed)
+op25/.../apps$ python sql_dbi.py reset_db
+ WARNING: OP25 MUST NOT BE RUNNING DURING THIS STEP
+
+3. Import talkgroups tags file
+op25/.../apps$ python sql_dbi.py import_tgid tags.tsv <sysid>
+ also, import the radio ID tags file (optional)
+op25/.../apps$ python sql_dbi.py import_unit radio-tags.tsv <sysid>
+ import the System ID tags file (see below)
+op25/.../apps$ python sql_dbi.py import_sysid sysid-tags.tsv 0
+
+The sysid tags must be a TSV file containing two columns
+column 1 is the P25 trunked sysid (int, decimal)
+colunn 2 is the System Name (text)
+(Note: there is no header row line in this TSV file).
+
+NOTE: in the various import commands above, the sysid (decimal) must follow
+as the next argument after the TSV file name. For the sysid tags file, the
+sysid should be set to zero.
+
+4. Run op25 as usual. Logfile data should be inserted into DB in real time
+ and you should be able to view activity via the OP25 http console (once
+ the flask/datatables app has been set up; see next section).
+
+Setup Flask Datatables App
+==========================
+
+0. The DB must first be established (see previous section)
+
+1. Install the necessary libs. If you are running the install in Ubuntu
+ 16.04 there are two lines in the script that must be un-commented prior
+ to running; then, in any case do:
+op25/.../apps$ sh install-sql.sh
+
+Note: you may need to 'sudo apt install git' prior to running this script.
+
+2. Update your .bashrc file as instructed, then re-login to pick up the
+ update to PATH. Verify that the updated PATH is correct. You can run
+ the command "echo $PATH" to display its current value. Here is an example
+ response: /home/op25/.local/bin:/usr/local/sbin:/usr/local/bin.....
+ You should confirm that the file "flask" exists and is executable (see
+ warning below).
+
+ $ ls -l ~/.local/bin/flask
+-rwxr-xr-x 1 op25 op25 212 Apr 29 21:43 /home/op25/.local/bin/flask
+
+3. First change to the "..../apps/oplog" directory, then run the following
+ commands to start the flask http process (listens on port 5000)
+
+op25/.../apps/oplog$ export FLASK_APP=op25
+op25/.../apps/oplog$ FLASK_DEBUG=1 flask run
+
+WARNING: if you receive the following messages when attempting the "flask run"
+command
+-------------------------------------------------------------
+Command 'flask' not found, but can be installed with:
+sudo apt install python3-flask
+-------------------------------------------------------------
+most likely this indicates the PATH is not properly set up (see step 2).
+In this case we do NOT recommend that you attempt to install the apt version
+of flask. The install-sql.sh script (step 1, above) should have installed a
+version of flask in a directory such as:
+
+ $ ls -l ~/.local/bin/flask
+-rwxr-xr-x 1 op25 op25 212 Apr 29 21:43 /home/op25/.local/bin/flask
+
+If install of the apt version of flask is attempted, it may result in an
+obsolete and/or incompatible flask version being installed.
+
+NOTE: The following command example can be used when starting the oplog
+process as a system service:
+ /home/<user>/op25/op25/gr-op25_repeater/apps/oplog/oplog.sh
+ * Change <user> to match the username
+ * Make appropriate corrections if the git repo is cloned into a different
+ directory than in the command shown
+ * Verify the resulting path and filename is correct.
+============ oplog.sh ============
+#! /bin/sh
+
+export FLASK_APP=op25
+FLASK_DEBUG=1 flask run --host=0.0.0.0
+==================================
+
+In lieu of setting the flask PATH (as per step 2, above) you could also
+specify it explicitly. In that case, replace the last line of oplog.sh as
+follows:
+FLASK_DEBUG=1 /home/<user>/.local/bin/flask run --host=0.0.0.0
+ * Change <user> to match the username
+ * Confirm the "flask" file is present in ..../bin/ and is executable
+ * Set "host" to "127.0.0.1" to restrict HTTP connections to the local
+ machine.
+ * WARNING The web server is not security-hardened. It is not
+ designed for exposure to public web-facing applications.
+
diff --git a/op25/gr-op25_repeater/apps/README-example-udp b/op25/gr-op25_repeater/apps/README-example-udp
new file mode 100644
index 0000000..ae3aeb4
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/README-example-udp
@@ -0,0 +1,38 @@
+
+Linking OP25 TX and RX December 2020
+===================================================================
+
+The OP25 TX application can be configured to transmit one or more
+channels directly to one of the RX apps (rx.py or multi_rx.py) in
+each case by specifying a device args string of the form
+ udp:host:port
+where host and port are the IP address and UDP port number,
+respectively. Typically, the TX is started first followed by
+the RX, but they can be started in any order. UDP port 25252 is
+used in the examples.
+
+The sample RX script is in runudp.sh, and the sample TX json config
+is in cfg-900.json .
+
+To start the TX
+ cd .../op25/op25-gr_repeater/apps/tx
+ ./multi_tx.py -c ../cfg-900.json
+
+The RX is started with
+ cd .../op25/op25-gr_repeater/apps
+ ./runudp.sh
+
+There is a 120KHz sized block of spectrum transmitted (SR=120000)
+which is treated as complex baseband with each side pretending that
+the spectrum is converted to/from the 900 MHz band. On the RX side
+any frequency-change requests are ignored; instead, a "center
+frequency" is defined. There are two channels (P25 trunk control
+channel and P25 voice channel) spaced at 50 KHz separation.
+
+The TX reads two data files that must be created beforehand. To
+create the trunk control channel data symbol file, refer to
+ tx/README-fakecc.txt
+An audio file (PCM/ rate 8000 / mono / signed int16) must also be
+created - this file will be real-time encoded with the voice codec
+and sent on the P25 voice channel. These two files must be defined
+in the cfg-900.json file (channel "source" keyword).
diff --git a/op25/gr-op25_repeater/apps/README-hls b/op25/gr-op25_repeater/apps/README-hls
new file mode 100644
index 0000000..ba9cd60
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/README-hls
@@ -0,0 +1,268 @@
+
+OP25 HTTP live streaming December 2020
+=====================================================================
+
+These hacks ("OP25-hls hacks") add a new option for audio reception
+and playback in OP25; namely, via an HTTP live stream to any remote
+client using a standard Web browser*. The web server software used
+(nginx) is industrial-strength and immediately scalable to dozens or
+hundreds of simultaneous remote users with zero added effort. More
+than one upstream source (in parallel) can be served simultaneously.
+
+OP25's liquidsoap script is hacked to pipe output PCM audio data
+to ffmpeg, which also reads the www/images/status.png image file
+that makes up the video portion of the encoded live stream. The
+image png file is kept updated by rx.py.
+
+The selection of ffmpeg codecs ("libx264" for video and "aac" for
+audio) allows us directly to send the encoded data stream from
+ffmpeg to the web server (nginx) utilizing RTMP. Individual
+MPEG-TS segments are stored as files in nginx web server URL-space,
+and served to web clients via standard HTTP GET requests. The
+hls.js package is used at the client.
+
+The entire effort mostly involved assembling existing off-the-shelf
+building blocks. The ffmpeg package was built manually from source
+to enable the "libx264" codec, and a modified nginx config was
+used.
+
+*the web browser must support the "MediaSource Extensions" API.
+All recent broswer versions should qualify.
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+1. nginx installation
+
+The libnginx-mod-rtmp package must be installed (in addition to
+nginx itself). You can copy the sample nginx configuration at the
+end of this README file to /etc/nginx/nginx.conf, followed by
+restarting the web server
+ sudo systemctl stop nginx
+ sudo systemctl start nginx
+With this configuration the web server should listen on HTTP port
+8081 and RTMP port 1935.
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+2. ffmpeg installation
+ git clone https://code.videolan.org/videolan/x264.git
+ git clone https://git.ffmpeg.org/ffmpeg.git
+ cd x264
+ ./configure
+ make
+ sudo make install
+ cd ../ffmpeg
+ ./configure --enable-shared --enable-libx264 --enable-gpl
+ make
+ sudo make install
+
+ To confirm the installation run the "ffmpeg" command and
+ verify the presence of "--enable-shared" and "--enable-libx264"
+ in the "configuration:" section of the output.
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+3. liquidsoap installation
+ Both packages "liquidsoap" and "liquidsoap-plugin-all" were
+ installed, but not tested whether the plugins are required for
+ this application.
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+4. nginx setup
+ with the custom config installed as per step 1, copy the files
+ from op25/gr_op25_repeater/www to /var/www/html as follows:
+
+ live.html
+ live.m3u8
+ hls.js
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+5. liquidsoap setup
+ in the op25/gr_op25_repeater/apps directory, note the ffmpeg.liq
+ script. Overall the filtering and buffering options should be
+ similar to those in op25.liq. The default version of ffmpeg.liq
+ should be OK for most uses.
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+6. operation
+ With OP25 rx.py started using the options -V -w (and -2 if using
+ TDMA) and with ffmpeg.liq started (both from the apps directory),
+ you should be able to connect to http://hostip:8081/live.html
+ and click the Play button to begin. NOTE: See note E for more
+ details about how to specify the value for 'hostip' in the above
+ link.
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+7. troubleshooting
+ A. with the ffmpeg.liq script running ffmpeg should start sending
+ rtmp data over port 1935 to nginx. You should see files
+ start being populated in /var/www/html/hls/ .
+ B. If /var/www/html/hls is empty, check ffmpeg message output
+ for possible errors, and also check the nginx access and
+ error logs. Note that the /var/www/html/hls directory should
+ start receiving files a few seconds after ffmpeg.liq is started
+ (regardless of whether OP25 is actively receiving a station,
+ or is not receiving).
+ C. js debug can be enabled for hls.js by editing that file as
+ follows; locate the lines of code and change the "debug"
+ setting to "true"
+
+var hlsDefaultConfig = _objectSpread(_objectSpread({
+ autoStartLoad: true,
+ // used by stream-controller
+ startPosition: -1,
+ // used by stream-controller
+ defaultAudioCodec: void 0,
+ // used by stream-controller
+ debug: true, ///// <<<=== change this line from
+ ///// "false" to "true"
+
+ D. after reloading the page and with the web browser js console
+ opened (and with all message types enabled), debug messages
+ should now start appearing in the console. As before another
+ place to look for messages is in the nginx access and error
+ logs.
+ E. if you are doing heavy client-side debugging it may be helpful
+ to obtain a copy of the hls.js distribution and to populate
+ the hls.js.map file (with updated hls.js) in /var/www/html.
+
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+8. notes
+ A. due to the propagation delay inherent in the streaming
+ process, there is a latency of several seconds from when
+ the transmissions are receieved before they are played in
+ the remote web browser. OP25 attempts to keep the video
+ and audio synchronized but the usual user controls (hold,
+ lockout, etc). are not available (in this release) because
+ the several-second delay could cause the commands to operate
+ on stale talkgroup data (without additional work).
+ B. in keeping with the current OP25 liquidsoap setup, the audio
+ stream is converted to mono prior to streaming. It might be
+ possible to retain the stereo data (in cases where the L and
+ R channels contain separate information), but this has not
+ been tested. The ffmpeg.liq script would need to be changed to
+ use "output" instead of "mean(output)" and the ffmpeg script
+ would need to change "-ac 1" to "-ac 2". In addition the
+ options stereo=true and channels=2 would need to be set in the
+ %wav specification parameters.
+ C. multiple independent streams can be served simultaneously by
+ invoking a separate ffmpeg.sh script for each stream and by
+ changing the last component of the rtmp URL to a unique
+ value; for example:
+ rtmp://localhost/live/stream2
+ A unified (parameterized) version of ffmpeg.sh could also be
+ used.
+ Also, new versions of live.html and live.m3u8 in /var/www/html
+ (reflecting the above modification) would need to be added.
+ D. note that pausing and seeking etc. in the media feed isn't
+ possible when doing live streaming.
+ E. when connecting from the remote client to the nginx server as
+ detailed in step 6 (above) you should specify the value for
+ 'hostip' as follows (omitting the quotes):
+
+ 'localhost' (default) - use this when the client is on the same
+ machine as the server
+ 'host.ip.address' - specify the IP address of the server when
+ the client and server machines are different, and the server
+ does not have a DNS hostname.
+ 'hostname' - if the server has a DNS hostname, this name should
+ be used in place of 'hostip'.
+
+ Note that in the second and third cases above you must also
+ change the hostname from 'localhost' to the IP address or DNS
+ hostname, respectively, in the following files
+ live.html
+ live.m3u8
+ in /var/www/html (total three occurrences).
+
+ Similarly, if an IP port other than 8081 is to be used, the same
+ updates as above must be made, and also the nginx conf file must
+ be updated to reflect the changed port number.
+
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+########################################################################
+####### tested on ubuntu 18.04 #######
+####### sample nginx conf file - copy everything below this line #######
+
+user www-data;
+worker_processes auto;
+pid /run/nginx.pid;
+include /etc/nginx/modules-enabled/*.conf;
+
+events {
+ worker_connections 768;
+ # multi_accept on;
+}
+
+# RTMP configuration
+rtmp {
+ server {
+ listen 1935; # Listen on standard RTMP port
+ chunk_size 4000;
+
+ application live {
+ live on;
+ # Turn on HLS
+ hls on;
+ hls_path /var/www/html/hls/;
+ hls_fragment 3;
+ hls_playlist_length 60;
+ # disable consuming the stream from nginx as rtmp
+ deny play all;
+ }
+ }
+}
+
+http {
+ sendfile off;
+ tcp_nopush on;
+ #aio on;
+ directio 512;
+ default_type application/octet-stream;
+
+ server {
+ listen 8081;
+
+ location / {
+ # Disable cache
+ add_header 'Cache-Control' 'no-cache';
+
+ # CORS setup
+ add_header 'Access-Control-Allow-Origin' '*' always;
+ add_header 'Access-Control-Expose-Headers' 'Content-Length';
+
+ # allow CORS preflight requests
+ if ($request_method = 'OPTIONS') {
+ add_header 'Access-Control-Allow-Origin' '*';
+ add_header 'Access-Control-Max-Age' 1728000;
+ add_header 'Content-Type' 'text/plain charset=UTF-8';
+ add_header 'Content-Length' 0;
+ return 204;
+ }
+
+# include /etc/nginx/mime.types;
+ types {
+ text/html html;
+ text/css css;
+ application/javascript js;
+ application/dash+xml mpd;
+ application/vnd.apple.mpegurl m3u8;
+ video/mp2t ts;
+ }
+
+ access_log /var/log/nginx/access.log;
+ error_log /var/log/nginx/error.log;
+
+ root /var/www/html;
+
+ }
+ }
+}
+
diff --git a/op25/gr-op25_repeater/apps/alt-colors.json b/op25/gr-op25_repeater/apps/alt-colors.json
new file mode 100644
index 0000000..0f338d3
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/alt-colors.json
@@ -0,0 +1,7 @@
+{
+ "label_color": "#000000",
+ "tic_color": "#000000",
+ "border_color": "#000000",
+ "plot_color": "#c000ff",
+ "background_color": "#ffffff"
+}
diff --git a/op25/gr-op25_repeater/apps/audio.py b/op25/gr-op25_repeater/apps/audio.py
new file mode 100755
index 0000000..255812f
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/audio.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+
+# Copyright 2017, 2018 Graham Norbury
+#
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+#
+# This file is part of OP25 and part of GNU Radio
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import signal
+import sys
+import time
+
+from optparse import OptionParser
+from sockaudio import socket_audio
+
+def signal_handler(signal, frame):
+ sys.stderr.write("audio.py shutting down\n")
+ audio_handler.stop()
+ sys.exit(0)
+
+parser = OptionParser()
+parser.add_option("-O", "--audio-output", type="string", default="default", help="audio output device name")
+parser.add_option("-H", "--host-ip", type="string", default="0.0.0.0", help="IP address to bind to")
+parser.add_option("-u", "--wireshark-port", type="int", default=23456, help="Wireshark port")
+parser.add_option("-2", "--two-channel", action="store_true", default=False, help="single or two channel audio")
+parser.add_option("-x", "--audio-gain", type="float", default="1.0", help="audio gain (default = 1.0)")
+parser.add_option("-s", "--stdout", action="store_true", default=False, help="write to stdout instead of audio device")
+parser.add_option("-S", "--silence", action="store_true", default=False, help="suppress output of zeros after timeout")
+
+(options, args) = parser.parse_args()
+if len(args) != 0:
+ parser.print_help()
+ sys.exit(1)
+
+audio_handler = socket_audio(options.host_ip, options.wireshark_port, options.audio_output, options.two_channel, options.audio_gain, options.stdout, silent_flag=options.silence)
+
+if __name__ == "__main__":
+ signal.signal(signal.SIGINT, signal_handler)
+ audio_handler.run()
+
diff --git a/op25/gr-op25_repeater/apps/cfg-900.json b/op25/gr-op25_repeater/apps/cfg-900.json
new file mode 100644
index 0000000..b1bb041
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg-900.json
@@ -0,0 +1,40 @@
+{
+ "channels": [
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56120",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 924975000,
+ "if_rate": 24000,
+ "name": "p25 control channel",
+ "plot": "datascope",
+ "source": "symbols:sym-cc925.dat",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 924925000,
+ "if_rate": 24000,
+ "name": "p25 voice channel",
+ "plot": "datascope",
+ "source": "/home/mhp/rand4.raw",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "udp:127.0.0.1:25252",
+ "frequency": 924950000,
+ "gains": "",
+ "name": "udp",
+ "offset": 0,
+ "ppm": 0,
+ "rate": 120000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/cfg-trunk.json b/op25/gr-op25_repeater/apps/cfg-trunk.json
new file mode 100644
index 0000000..b9a2d87
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg-trunk.json
@@ -0,0 +1,40 @@
+{
+ "channels": [
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "p25 control channel",
+ "plot": "symbol",
+ "decode": "p25_decoder:cc",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "p25 voice channel",
+ "plot": "symbol",
+ "decode": "p25_decoder:vc",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "rtl=1",
+ "frequency": 454300000,
+ "gains": "lna:49",
+ "name": "rtl0",
+ "offset": 0,
+ "ppm": 54,
+ "rate": 1000000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/cfg-trunk2.json b/op25/gr-op25_repeater/apps/cfg-trunk2.json
new file mode 100644
index 0000000..3759492
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg-trunk2.json
@@ -0,0 +1,50 @@
+{
+ "channels": [
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "p25 control channel",
+ "plot": "symbol",
+ "decode": "p25_decoder:cc",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "p25 voice channel",
+ "plot": "symbol",
+ "decode": "p25_decoder:vc",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "rtl=00000011",
+ "frequency": 460300000,
+ "gains": "lna:49",
+ "name": "rtl11_cc",
+ "offset": 0,
+ "ppm": 54,
+ "rate": 1000000,
+ "tunable": false
+ },
+ {
+ "args": "rtl=00000012",
+ "frequency": 453000000,
+ "gains": "lna:49",
+ "name": "rtl12_vc",
+ "offset": 0,
+ "ppm": 54,
+ "rate": 1000000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/cfg-trunkx.json b/op25/gr-op25_repeater/apps/cfg-trunkx.json
new file mode 100644
index 0000000..a004d56
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg-trunkx.json
@@ -0,0 +1,98 @@
+{
+ "channels": [
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "Oswego CC",
+ "plot": "symbol",
+ "decode": "p25_decoder:role=cc:dev=rtl12:nac=0x2a4",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "Cayuga CC",
+ "plot": "symbol",
+ "decode": "p25_decoder:role=cc:dev=rtl12:nac=0x2a8",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "460 MHz VC",
+ "plot": "symbol",
+ "decode": "p25_decoder:role=vc:dev=rtl12",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:23456",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "453-454 MHz VC",
+ "plot": "symbol",
+ "decode": "p25_decoder:role=vc:dev=rtl11",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "Onondaga CC",
+ "plot": "symbol",
+ "decode": "p25_decoder:role=cc:dev=rtl12:nac=0x2a0",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 0,
+ "if_rate": 24000,
+ "name": "Cortland CC",
+ "plot": "constellation",
+ "decode": "p25_decoder:role=cc:dev=rtl11:nac=0x4e1",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "rtl=00000012",
+ "frequency": 460500000,
+ "gains": "lna:49",
+ "name": "rtl12",
+ "offset": 0,
+ "ppm": 54,
+ "rate": 1000000,
+ "tunable": false
+ },
+ {
+ "args": "rtl=00000011",
+ "frequency": 453850000,
+ "gains": "lna:49",
+ "name": "rtl11",
+ "offset": 0,
+ "ppm": 55,
+ "rate": 2048000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/cfg-udp.json b/op25/gr-op25_repeater/apps/cfg-udp.json
new file mode 100644
index 0000000..26c476d
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg-udp.json
@@ -0,0 +1,76 @@
+{
+ "channels": [
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56124",
+ "excess_bw": 0.2,
+ "filter_type": "nxdn",
+ "frequency": 442112500,
+ "if_rate": 24000,
+ "name": "nxdn48",
+ "plot": "datascope",
+ "source": "/home/mhp/rand0.raw",
+ "symbol_rate": 2400
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56128",
+ "excess_bw": 0.2,
+ "filter_type": "rrc",
+ "frequency": 442187500,
+ "if_rate": 24000,
+ "name": "dmr",
+ "plot": "datascope",
+ "source": "/home/mhp/rand1.raw",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56132",
+ "excess_bw": 0.2,
+ "filter_type": "gmsk",
+ "frequency": 442262500,
+ "if_rate": 24000,
+ "name": "dstar",
+ "plot": "datascope",
+ "source": "/home/mhp/rand2.raw",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56136",
+ "excess_bw": 0.2,
+ "filter_type": "rrc",
+ "frequency": 442337500,
+ "if_rate": 24000,
+ "name": "ysf",
+ "plot": "datascope",
+ "source": "/home/mhp/rand3.raw",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56120",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 442412500,
+ "if_rate": 24000,
+ "name": "p25",
+ "plot": "datascope",
+ "source": "/home/mhp/rand4.raw",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "udp:127.0.0.1:25252",
+ "frequency": 442262500,
+ "gains": "",
+ "name": "udp",
+ "offset": 0,
+ "ppm": 0,
+ "rate": 480000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/cfg.json b/op25/gr-op25_repeater/apps/cfg.json
new file mode 100644
index 0000000..57a66c7
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/cfg.json
@@ -0,0 +1,49 @@
+{
+ "channels": [
+ {
+ "demod_type": "cqpsk",
+ "destination": "udp://127.0.0.1:56120",
+ "excess_bw": 0.2,
+ "filter_type": "rc",
+ "frequency": 460412500,
+ "if_rate": 24000,
+ "name": "p25",
+ "plot": "symbol",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "file:///tmp/out1.raw",
+ "excess_bw": 0.2,
+ "filter_type": "rrc",
+ "frequency": 460500000,
+ "if_rate": 24000,
+ "name": "ysf",
+ "plot": "datascope",
+ "symbol_rate": 4800
+ },
+ {
+ "demod_type": "fsk4",
+ "destination": "udp://127.0.0.1:56122",
+ "excess_bw": 0.2,
+ "filter_type": "rrc",
+ "frequency": 460050000,
+ "if_rate": 24000,
+ "name": "dmr",
+ "plot": "symbol",
+ "symbol_rate": 4800
+ }
+ ],
+ "devices": [
+ {
+ "args": "rtl=0",
+ "frequency": 460100000,
+ "gains": "lna:49",
+ "name": "rtl0",
+ "offset": 0,
+ "ppm": 38,
+ "rate": 1000000,
+ "tunable": false
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/apps/color-map.json b/op25/gr-op25_repeater/apps/color-map.json
new file mode 100644
index 0000000..ad90812
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/color-map.json
@@ -0,0 +1,602 @@
+[
+ [
+ 500,
+ "placeholder",
+ "do-not-use",
+ false
+ ],
+ [
+ 1,
+ "#0066ff",
+ "",
+ false
+ ],
+ [
+ 2,
+ "#ff0000",
+ "",
+ false
+ ],
+ [
+ 3,
+ "#ff9900",
+ "",
+ false
+ ],
+ [
+ 4,
+ "#eeeeee",
+ "",
+ false
+ ],
+ [
+ 5,
+ "#9966ff",
+ "",
+ false
+ ],
+ [
+ 6,
+ "#00ff00",
+ "",
+ false
+ ],
+ [
+ 7,
+ "#009933",
+ "",
+ false
+ ],
+ [
+ 8,
+ "#ffff00",
+ "",
+ false
+ ],
+ [
+ 9,
+ "#eee",
+ "",
+ false
+ ],
+ [
+ 10,
+ "#ff6666",
+ "",
+ false
+ ],
+ [
+ 11,
+ "#0080C0",
+ "",
+ false
+ ],
+ [
+ 12,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 13,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 14,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 15,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 16,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 17,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 18,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 19,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 20,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 21,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 22,
+ "#ff0000",
+ "",
+ true
+ ],
+ [
+ 23,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 24,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 25,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 26,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 27,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 28,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 29,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 30,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 31,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 32,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 33,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 34,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 35,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 36,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 37,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 38,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 39,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 40,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 41,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 42,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 43,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 44,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 45,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 46,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 47,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 48,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 49,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 50,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 51,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 52,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 53,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 54,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 55,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 56,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 57,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 58,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 59,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 60,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 61,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 62,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 63,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 64,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 65,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 66,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 67,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 68,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 69,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 70,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 71,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 72,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 73,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 74,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 75,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 76,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 77,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 78,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 79,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 80,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 81,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 82,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 83,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 84,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 85,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 86,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 87,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 88,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 89,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 90,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 91,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 92,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 93,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 94,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 95,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 96,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 97,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 98,
+ "#666666",
+ "",
+ false
+ ],
+ [
+ 99,
+ "#00ff00",
+ "#000000",
+ false
+ ]
+] \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/correlation.json b/op25/gr-op25_repeater/apps/correlation.json
new file mode 100644
index 0000000..8f143b0
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/correlation.json
@@ -0,0 +1,27 @@
+[
+ {
+ "fs":[ 1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1 ],
+ "length":864,
+ "name":"P25"
+ },
+ {
+ "fs":[ -3, -3, 1, 1, -3, -3, 3, 3, -3, -3, -3, -3, 3, 3, 3, 3, -1, -1, 3, 3 ],
+ "length":384,
+ "name":"NXDN48"
+ },
+ {
+ "fs":[ -3, 1, -3, 3, -3, -3, 3, 3, -1, 3 ],
+ "length":192,
+ "name":"NXDN96"
+ },
+ {
+ "fs":[ 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1 ],
+ "length":576,
+ "name":"DMR"
+ },
+ {
+ "fs":[ -3, 3, 3, 1, 3, -3, 1, 3, -3, 1, -1, 3, 3, -1, 1, -3, 3, 1, -3, 3 ],
+ "length":480,
+ "name":"YSF"
+ }
+]
diff --git a/op25/gr-op25_repeater/apps/create_image.py b/op25/gr-op25_repeater/apps/create_image.py
new file mode 100644
index 0000000..17c5d25
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/create_image.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+
+#
+# (c) Copyright 2020, OP25
+#
+# This file is part of OP25 and part of GNU Radio
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+""" generate named image file consisting of multi-line text """
+
+from PIL import Image, ImageDraw, ImageFont
+import os
+
+_TTF_FILE = '/usr/share/fonts/truetype/freefont/FreeSerif.ttf'
+
+def create_image(textlist=["Blank"], imgfile="test.png", bgcolor='red', fgcolor='black', windowsize=(400,300)):
+ global _TTF_FILE
+ width=windowsize[0]
+ height=windowsize[1]
+
+ margin = 4
+ if not os.access(_TTF_FILE, os.R_OK):
+ font = ImageFont.load_default()
+ else:
+ font = ImageFont.truetype(_TTF_FILE, 16)
+ img = Image.new('RGB', (width, height), bgcolor)
+ draw = ImageDraw.Draw(img)
+ cursor = 0
+ for line in textlist:
+ w,h = draw.textsize(line, font)
+ # TODO: overwidth check needed?
+ if cursor+h >= height:
+ break
+ draw.text((margin, cursor), line,'black',font)
+ cursor += h + margin // 2
+
+ img.save(imgfile)
+
+if __name__ == '__main__':
+ s = []
+ s.append('Starting...')
+
+ create_image(textlist=s, bgcolor='#c0c0c0')
diff --git a/op25/gr-op25_repeater/apps/emap.py b/op25/gr-op25_repeater/apps/emap.py
new file mode 100644
index 0000000..efd63cc
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/emap.py
@@ -0,0 +1,383 @@
+#sql_dbi events map
+
+events_map = {
+ "grp_v_ch_grant_mbt": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'options'],
+ ['frequency', 'frequency'],
+ ['tgid', 'group'],
+ ['suid', 'srcaddr'],
+ ],
+ "grg_exenc_cmd": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['tgid', 'sg'],
+ ['p', 'keyid'],
+ ],
+ "grp_v_ch_grant": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['p', 'options'],
+ ['frequency', 'frequency'],
+ ['tgid', 'group'],
+ ['suid', 'srcaddr'],
+ ],
+ "mot_grg_cn_grant": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['frequency', 'frequency'],
+ ['tgid', 'sg'],
+ ['suid', 'sa'],
+ ],
+ "grp_v_ch_grant_updt": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['frequency', 'frequency1'],
+ ['tgid', 'group1'],
+ ],
+ "grp_v_ch_grant_updt_exp": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['p', 'options'],
+ ['frequency', 'frequency'],
+ ['tgid', 'group'],
+ ],
+ "ack_resp_fne": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'aiv'],
+ ['p2', 'ex'],
+ ['p3', 'addl'],
+ ['wacn', 'wacn'],
+ ['suid', 'source'],
+ ['suid2', 'target'],
+ ],
+ "deny_resp": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'aiv'],
+ ['p2', 'reason'],
+ ['p3', 'additional'],
+ ['suid', 'target'],
+ ],
+ "grp_aff_resp": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'affiliation'],
+ ['p2', 'group_aff_value'],
+ ['tgid', 'announce_group'],
+ ['tgid2', 'group'],
+ ['suid', 'target'],
+ ],
+ "grp_aff_q": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['suid', 'source'],
+ ['suid2', 'target'],
+ ],
+ "loc_reg_resp": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'rv'],
+ ['p2', 'rfss'],
+ ['p3', 'siteid'],
+ ['tgid', 'group'],
+ ['suid', 'target'],
+ ],
+ "u_reg_resp": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'rv'],
+ ['suid', 'source'],
+ ['suid2', 'target'],
+ ],
+ "u_reg_cmd": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['suid', 'source'],
+ ['suid2', 'target'],
+ ],
+ "u_de_reg_ack": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['wacn', 'wacn'],
+ ['suid', 'source'],
+ ],
+ "ext_fnct_cmd": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['p', 'efclass'],
+ ['p2', 'efoperand'],
+ ['suid', 'efargs'],
+ ],
+ "end_call": [
+ ['time', 'time'],
+ ['sysid', 'sysid'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'code'],
+ ['suid', 'srcaddr'],
+ ['tgid', 'tgid'],
+ ['p2', 'duration'],
+ ['p3', 'count'],
+ ],
+}
+
+# cc_event to numerical id (oplog and sql_dbi)
+cc_events = {
+ "ack_resp_fne": 1,
+ "deny_resp": 2,
+ "end_call": 3,
+ "ext_fnct_cmd": 4,
+ "grg_exenc_cmd": 5,
+ "grp_aff_q": 6,
+ "grp_aff_resp": 7,
+ "grp_v_ch_grant": 8,
+ "grp_v_ch_grant_mbt": 9,
+ "grp_v_ch_grant_updt": 10,
+ "grp_v_ch_grant_updt_exp": 11,
+ "loc_reg_resp": 12,
+ "u_de_reg_ack": 13,
+ "u_reg_cmd": 14,
+ "u_reg_resp": 15,
+ "mot_grg_cn_grant": 16,
+}
+
+# sql column names to DataTables (Oplog)
+oplog_map = {
+ "grp_v_ch_grant_mbt": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['p', 'Options'],
+ ['frequency', 'Frequency'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ],
+ "grg_exenc_cmd": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['tgid', 'SG (tgid)'],
+ ['p', 'Key ID'],
+ ],
+ "grp_v_ch_grant": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['p', 'Options'],
+ ['frequency', 'Frequency'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ],
+ "mot_grg_cn_grant": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['frequency', 'Frequency'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ],
+ "grp_v_ch_grant_updt": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['frequency', 'Frequency'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ],
+ "grp_v_ch_grant_updt_exp": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'mfrid'],
+ ['p', 'Options'],
+ ['frequency', 'Frequency'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ],
+ "ack_resp_fne": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'aiv'],
+ ['p2', 'ex'],
+ ['p3', 'Additional'],
+ ['wacn', 'wacn'],
+ ['suid', 'System Source'],
+ ['suid2', 'Target ID'],
+ ['suid2', 'Target'],
+ ],
+ "deny_resp": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'aiv'],
+ ['p2', 'Reason'],
+ ['p3', 'Additional'],
+ ['suid', 'Target ID'],
+ ['suid', 'Target'],
+ ],
+ "grp_aff_resp": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'Affiliation'],
+ ['p2', 'Group Aff Value'],
+ ['tgid', 'Announce Group'],
+ ['tgid2', 'Talkgroup ID'],
+ ['tgid2', 'Talkgroup'],
+ ['suid', 'Target ID'],
+ ['suid', 'Target'],
+ ],
+ "grp_aff_q": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['suid', 'System Source'],
+ ['suid2', 'Target ID'],
+ ['suid2', 'Target'],
+ ],
+ "loc_reg_resp": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'rv'],
+ ['p2', 'RFSS'],
+ ['p3', 'Site'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ['suid', 'Target ID'],
+ ['suid', 'Target'],
+ ],
+ "u_reg_resp": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'rv'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ['suid2', 'Target'],
+ ],
+ "u_reg_cmd": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['suid', 'System Source'],
+ ['suid2', 'Target ID'],
+ ['suid2', 'Target'],
+ ],
+ "u_de_reg_ack": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['wacn', 'WACN'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ],
+ "ext_fnct_cmd": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['mfrid', 'MFRID'],
+ ['p', 'Class'],
+ ['p2', 'Operand'],
+ ['suid', 'System Source'],
+ ],
+ "end_call": [
+ ['time', 'Time'],
+ ['sysid', 'System'],
+ ['opcode', 'opcode'],
+ ['cc_event', 'cc_event'],
+ ['p', 'Code'],
+ ['suid', 'Source ID'],
+ ['suid', 'Source'],
+ ['tgid', 'Talkgroup ID'],
+ ['tgid', 'Talkgroup'],
+ ['p2', 'Duration (ms)'],
+ ['p3', 'Count (p3)'],
+ ],
+}
+
+# friendly long description strings, used in Oplog
+cc_desc = {
+ "ack_resp_fne": "Acknowledge Response FNE - 0x20",
+ "deny_resp": "Deny Response - 0x27",
+ "end_call": "End Call (not a naitve control channel event)",
+ "ext_fnct_cmd": "Extended Function Command - 0x24",
+ "grg_exenc_cmd": "Harris Group Regroup Explicit Encryption Command - 0x30",
+ "grp_aff_q": "Group Affiliation Query - 0x2A",
+ "grp_aff_resp": "Group Affiliation Response - 0x28",
+ "grp_v_ch_grant": "Group Voice Channel Grant - 0x00",
+ "grp_v_ch_grant_mbt": "Group Voice Channel Grant, Multiple Block Trunking",
+ "grp_v_ch_grant_updt": "Group Voice Channel Grant Update - 0x02",
+ "grp_v_ch_grant_updt_exp": "Group Voice Channel Grant Update, Explicit - 0x03",
+ "loc_reg_resp": "Location Registration Response 0x2B",
+ "mot_grg_cn_grant": "Motorola Patch Channel Grant - 0x02",
+ "u_de_reg_ack": "De-Registration Acknowledge (Logout) - 0x2F",
+ "u_reg_cmd": "Unit Registration Command (Force Unit Registration) - 0x2D",
+ "u_reg_resp": "Unit Registration Response - 0x2C"
+}
diff --git a/op25/gr-op25_repeater/apps/example_liquidsoap.liq b/op25/gr-op25_repeater/apps/example_liquidsoap.liq
new file mode 100644
index 0000000..a0ee73e
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/example_liquidsoap.liq
@@ -0,0 +1,73 @@
+#!/usr/bin/liquidsoap
+
+# Example liquidsoap streaming from op25 to icecast
+# (c) 2019, 2020 gnorbury@bondcar.com, wllmbecks@gmail.com
+#
+
+set("log.stdout", true)
+set("log.file.path", "/home/pi/op25/op25/gr-op25_repeater/apps/liquidsoap.log")
+set("log.file", true)
+set("log.level", 3)
+
+# Make the native sample rate compatible with op25
+set("frame.audio.samplerate", 8000)
+
+# SOURCE INPUT BLOCK OPTIONS
+# Mono and stereo input sources are mutually exclusive. Choose type.
+
+# Mono input source
+input = mksafe(input.external(buffer=0.25, channels=2, samplerate=8000, restart_on_error=false, "./audio.py -x 2 -s"))
+# Consider increasing the buffer value on slow systems such as RPi3. e.g. buffer=0.25
+# Longer buffer results in less choppy audio but at the expense of increased latency.
+
+# Left channel input source and audio summing for two-slot protocols
+#left = input.external(buffer=0.25, channels=2, samplerate=8000, restart_on_error=false, "./audio.py -u 23450 -x 2 -s")
+#left = audio_to_stereo(left)
+#left = stereo.pan(pan=1., left)
+
+# Right channel input source and audio summing for two-slot protocols
+#right = input.external(buffer=0.25, channels=2, samplerate=8000, restart_on_error=false, "./audio.py -u 23460 -x 2 -s")
+#right = audio_to_stereo(right)
+#right = stereo.pan(pan=-1., right)
+
+# OPTIONAL AUDIO SIGNAL PROCESSING BLOCKS
+# Uncomment to enable
+#
+# High pass filter mono
+input = filter.iir.butterworth.high(frequency = 200.0, order = 4, input)
+
+# High pass filter stereo
+#left = filter.iir.butterworth.high(frequency = 200.0, order = 4, left)
+#right = filter.iir.butterworth.high(frequency = 200.0, order = 4, right)
+
+# Low pass filter mono
+input = filter.iir.butterworth.low(frequency = 3250.0, order = 4, input)
+
+# Low pass filter stereo
+#left = filter.iir.butterworth.low(frequency = 3250.0, order = 4, left)
+#right = filter.iir.butterworth.low(frequency = 3250.0, order = 4, right)
+
+# Normalization mono
+input = normalize(input, gain_max = 3.0, gain_min = -3.0, target = -16.0, threshold = -40.0)
+
+# Normalization stereo -- Note -- Adjust target gains independently to achieve left/right balance
+#left = normalize(left, gain_max = 3.0, gain_min = -3.0, target = -16.0, threshold = -40.0)
+#right = normalize(right, gain_max = 3.0, gain_min = -3.0, target = -16.0, threshold = -40.0)
+
+# Commnent out the line below for "non-stereo" (mono) output
+#input = mksafe(add(normalize=false, [left,right]))
+
+# LOCAL AUDIO OUTPUT
+# Uncomment the line below to enable local sound
+#output.ao(input)
+
+# ICECAST STREAMING
+# Uncomment to enable output to an icecast server
+# Change the "host", "password", and "mount" strings appropriately first!
+# For metadata to work properly, the host address given here MUST MATCH the address in op25's meta.json file
+#
+# Mono Stream
+output.icecast(%mp3(bitrate=16, samplerate=22050, stereo=false), description="op25", genre="Public Safety", url="", fallible=false, icy_metadata="false", host="localhost", port=8000, mount="op25", password="hackme", mean(input))
+#
+# Stereo Stream
+#output.icecast(%mp3(bitrate=16, samplerate=22050, stereo=true), description="op25", genre="Public Safety", url="", fallible=false, icy_metadata="false", host="localhost", port=8000, mount="op25", password="hackme", input)
diff --git a/op25/gr-op25_repeater/apps/ffmpeg.liq b/op25/gr-op25_repeater/apps/ffmpeg.liq
new file mode 100755
index 0000000..5a13376
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/ffmpeg.liq
@@ -0,0 +1,15 @@
+#!/usr/bin/liquidsoap
+
+# Example liquidsoap hls streaming from op25 to nginx
+# (c) 2019, 2020 gnorbury@bondcar.com, wllmbecks@gmail.com
+# (c) 2020 KA1RBI
+
+set("log.stdout", true)
+set("log.file", false)
+set("log.level", 1)
+
+set("frame.audio.samplerate", 8000)
+
+input = mksafe(input.external(buffer=0.02, channels=2, samplerate=8000, restart_on_error=false, "./audio.py -x 2 -s -S"))
+
+output.external(%wav(stereo=false, channels=1, samplesize=16, header=false, samplerate=8000), fallible=false, flush=true, "./ffmpeg.sh", mean(input))
diff --git a/op25/gr-op25_repeater/apps/ffmpeg.sh b/op25/gr-op25_repeater/apps/ffmpeg.sh
new file mode 100755
index 0000000..57e946e
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/ffmpeg.sh
@@ -0,0 +1,42 @@
+#! /bin/sh
+
+# Copyright (c) 2020 OP25
+#
+# This file is part of OP25 and part of GNU Radio
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+#
+# this script should not be run directly - run ffmpeg.liq instead
+#
+# requires ffmpeg configured with --enable-libx264
+#
+
+ffmpeg \
+ -ar 8000 \
+ -ac 1 \
+ -acodec pcm_s16le \
+ -f s16le \
+ -i pipe:0 \
+ -f image2 \
+ -loop 1 \
+ -i ../www/images/status.png \
+ -vcodec libx264 \
+ -pix_fmt yuv420p \
+ -f flv \
+ -acodec aac \
+ -b:a 48k \
+ rtmp://localhost/live/stream
diff --git a/op25/gr-op25_repeater/apps/gr_gnuplot.py b/op25/gr-op25_repeater/apps/gr_gnuplot.py
index 2fe3c92..cd828cc 100644
--- a/op25/gr-op25_repeater/apps/gr_gnuplot.py
+++ b/op25/gr-op25_repeater/apps/gr_gnuplot.py
@@ -20,33 +20,93 @@
# 02110-1301, USA.
import sys
+import os
+import time
import subprocess
+import json
+import threading
+import glob
-from gnuradio import gr, gru, eng_notation
+from gnuradio import gr, eng_notation
from gnuradio import blocks, audio
from gnuradio.eng_option import eng_option
import numpy as np
from gnuradio import gr
+from math import pi, sin, cos
_def_debug = 0
_def_sps = 10
+_def_cpm_mode = 'cpm'
GNUPLOT = '/usr/bin/gnuplot'
FFT_AVG = 0.25
+MIX_AVG = 0.15
+BAL_AVG = 0.05
FFT_BINS = 512
+def degrees(r):
+ d = 360 * r / (2*pi)
+ while d <0:
+ d += 360
+ while d > 360:
+ d -= 360
+ return d
+
+def limit(a,lim):
+ if a > lim:
+ return lim
+ return a
+
+def ensure_str(s): # for python 2/3
+ if isinstance(s[0], str):
+ return s
+ ns = ''
+ for i in range(len(s)):
+ ns += chr(s[i])
+ return ns
+
+PSEQ = 0
+
class wrap_gp(object):
- def __init__(self, sps=_def_sps):
+ def __init__(self, sps=_def_sps, logfile=None, title="", color_cfg='plot-colors.json'):
+ global PSEQ
self.sps = sps
- self.center_freq = None
+ self.center_freq = 0.0
self.relative_freq = 0.0
+ self.offset_freq = 0.0
self.width = None
self.ffts = ()
self.freqs = ()
self.avg_pwr = np.zeros(FFT_BINS)
- self.buf = []
+ self.avg_sum_pwr = 0.0
+ self.buf = np.array([])
self.plot_count = 0
+ self.last_plot = 0
+ self.plot_interval = None
+ self.sequence = 0
+ self.output_dir = None
+ self.filename = None
+ self.logfile = logfile
+ self.title = title
+ self.sequence_id = PSEQ
+ PSEQ += 1
+ x = self.sequence_id % 3
+ y = self.sequence_id // 3
+ self.position = (x, y)
+
+ self.colors = {}
+ self.colors['label_color'] = ''
+ self.colors['tic_color'] = ''
+ self.colors['border_color'] = ''
+ self.colors['plot_color'] = ''
+ self.colors['background_color'] = ''
+ if color_cfg and os.access(color_cfg, os.R_OK):
+ ccfg = json.loads(open(color_cfg).read())
+ for color in ccfg:
+ self.colors[color] = ccfg[color]
+
+ self.next_cpmd = time.time()
self.attach_gp()
@@ -56,88 +116,316 @@ class wrap_gp(object):
self.gp = subprocess.Popen(args, executable=exe, stdin=subprocess.PIPE)
def kill(self):
- self.gp.kill()
- self.gp.wait()
+ try:
+ self.gp.stdin.close() # closing pipe should cause subprocess to exit
+ except IOError:
+ pass
+ sleep_count = 0
+ while True: # wait politely, but only for so long
+ self.gp.poll()
+ if self.gp.returncode is not None:
+ break
+ time.sleep(0.1)
+ if self.gp.returncode is not None:
+ break
+ sleep_count += 1
+ if (sleep_count & 1) == 0:
+ self.gp.kill()
+ if sleep_count >= 3:
+ break
+
+ def set_interval(self, v):
+ self.plot_interval = v
+
+ def set_output_dir(self, v):
+ self.output_dir = v
+
+ def set_sps(self, sps):
+ self.sps = sps
def plot(self, buf, bufsz, mode='eye'):
BUFSZ = bufsz
consumed = min(len(buf), BUFSZ-len(self.buf))
if len(self.buf) < BUFSZ:
- self.buf.extend(buf[:consumed])
+ self.buf = np.concatenate((self.buf, buf[:int(consumed)]))
if len(self.buf) < BUFSZ:
return consumed
self.plot_count += 1
if mode == 'eye' and self.plot_count % 20 != 0:
- self.buf = []
+ self.buf = np.array([])
return consumed
plots = []
s = ''
- while(len(self.buf)):
- if mode == 'eye':
- if len(self.buf) < self.sps:
+ plot_size = (320,240)
+ if mode == 'eye':
+ nplots = len(self.buf) // self.sps - 2
+ for i in range(nplots):
+ s += '\n'.join(['%f' % self.buf[i*self.sps+j] for j in range(self.sps+1)])
+ s += '\ne\n'
+ plots.append('"-" with lines')
+ elif mode == 'cpm':
+ nplots = len(self.buf)
+ ab = np.abs(self.buf)
+ for i in range(len(ab)):
+ s += '%f\n' % ab[i]
+ s += 'e\n'
+ plots.append('"-" with lines')
+ elif mode == 'cpmd':
+ if time.time() < self.next_cpmd:
+ self.buf = np.array([])
+ return 0
+ self.next_cpmd = time.time() + 0.5
+ ab = np.abs(self.buf)
+ thresh = np.max(ab) / 2.0
+ mask1 = np.array(ab > thresh, dtype=np.int)
+ maskdf = mask1[1:] - mask1[:-1]
+ nz = np.array(np.nonzero(maskdf), dtype=np.int)[0]
+ nzd = nz[1:]-nz[:-1]
+ nzdn = nzd // self.sps
+ sel = (nzdn > 165) & (nzdn < 185)
+ valid = np.array(np.nonzero(sel), dtype=np.int)[0]
+ if len(valid) < 1:
+ self.buf = np.array([])
+ return 0
+ v0 = valid[0]
+ i0 = nz[v0]
+ samples = self.buf[i0 : i0+170*self.sps+2]
+ fmd = np.angle(samples[1:] * np.conj(samples[:-1]))
+ fmd = fmd[12*self.sps:]
+ for n in range(0,len(fmd),self.sps):
+ sl = fmd[n:n+self.sps+1]
+ if len(sl) != self.sps+1:
break
- for i in range(self.sps):
- s += '%f\n' % self.buf[i]
- s += 'e\n'
- self.buf=self.buf[self.sps:]
+ s += '\n'.join(['%f' % (x*self.sps) for x in sl])
+ s += '\ne\n'
plots.append('"-" with lines')
- elif mode == 'constellation':
- for b in self.buf:
- s += '%f\t%f\n' % (b.real, b.imag)
- s += 'e\n'
- self.buf = []
- plots.append('"-" with points')
- elif mode == 'symbol':
- for b in self.buf:
- s += '%f\n' % (b)
- s += 'e\n'
- self.buf = []
- plots.append('"-" with dots')
- elif mode == 'fft':
- self.ffts = np.fft.fft(self.buf * np.blackman(BUFSZ)) / (0.42 * BUFSZ)
- self.ffts = np.fft.fftshift(self.ffts)
- self.freqs = np.fft.fftfreq(len(self.ffts))
- self.freqs = np.fft.fftshift(self.freqs)
- if self.center_freq and self.width:
- self.freqs = ((self.freqs * self.width) + self.center_freq) / 1e6
- for i in xrange(len(self.ffts)):
+ elif mode == 'constellation':
+ plot_size = (240,240)
+ self.buf = self.buf[:100]
+ for b in self.buf:
+ s += '%f\t%f\n' % (degrees(np.angle(b)), limit(np.abs(b),1.0))
+ s += 'e\n'
+ plots.append('"-" with points')
+ for b in self.buf:
+ #s += '%f\t%f\n' % (b.real, b.imag)
+ s += '%f\t%f\n' % (degrees(np.angle(b)), limit(np.abs(b),1.0))
+ s += 'e\n'
+ plots.append('"-" with lines')
+ elif mode == 'symbol':
+ for b in self.buf:
+ s += '%f\n' % (b)
+ s += 'e\n'
+ plots.append('"-" with points')
+ elif mode == 'fftf':
+ self.ffts = np.fft.rfft(self.buf * np.blackman(BUFSZ)) / (0.42 * BUFSZ)
+ #self.ffts = np.fft.fftshift(self.ffts)
+ self.ffts = np.abs(self.ffts) ** 2.0
+ self.ffts /= np.max(self.ffts)
+ for i in range(len(self.ffts)):
+ s += '%f\n' % (self.ffts[i])
+ s += 'e\n'
+ plots.append('"-" with lines')
+ elif mode == 'fft' or mode == 'mixer':
+ sum_pwr = 0.0
+ self.ffts = np.fft.fft(self.buf * np.blackman(BUFSZ)) / (0.42 * BUFSZ)
+ self.ffts = np.fft.fftshift(self.ffts)
+ self.freqs = np.fft.fftfreq(len(self.ffts))
+ self.freqs = np.fft.fftshift(self.freqs)
+ tune_freq = (self.center_freq - self.relative_freq) / 1e6
+ if self.center_freq and self.width:
+ self.freqs = ((self.freqs * self.width) + self.center_freq + self.offset_freq) / 1e6
+ for i in range(len(self.ffts)):
+ if mode == 'fft':
self.avg_pwr[i] = ((1.0 - FFT_AVG) * self.avg_pwr[i]) + (FFT_AVG * np.abs(self.ffts[i]))
- s += '%f\t%f\n' % (self.freqs[i], 20 * np.log10(self.avg_pwr[i]))
+ else:
+ self.avg_pwr[i] = ((1.0 - MIX_AVG) * self.avg_pwr[i]) + (MIX_AVG * np.abs(self.ffts[i]))
+ s += '%f\t%f\n' % (self.freqs[i], 20 * np.log10(self.avg_pwr[i]))
+ if (mode == 'mixer') and (self.avg_pwr[i] > 1e-5):
+ if (self.freqs[i] - self.center_freq) < 0:
+ sum_pwr -= self.avg_pwr[i]
+ elif (self.freqs[i] - self.center_freq) > 0:
+ sum_pwr += self.avg_pwr[i]
+ self.avg_sum_pwr = ((1.0 - BAL_AVG) * self.avg_sum_pwr) + (BAL_AVG * sum_pwr)
+ s += 'e\n'
+ plots.append('"-" with lines')
+ elif mode == 'float' or mode == 'correlation':
+ for b in self.buf:
+ s += '%f\n' % (b)
+ s += 'e\n'
+ plots.append('"-" with lines')
+ elif mode == 'sync':
+ s_abs = np.abs(self.buf)
+ sums = np.zeros(self.sps)
+ for i in range(self.sps):
+ sums[i] = np.sum(s_abs[range(i, len(self.buf), self.sps)])
+ am = np.argmax(sums)
+ samples = self.buf[am:]
+
+ a1 = -np.angle(samples[0])
+ rz = cos(a1) + 1j * sin(a1)
+
+ while len(samples) >= self.sps+1:
+ for i in range(self.sps+1):
+ z = samples[i] * rz
+ s += '%f\t%f\n' % (z.real, z.imag)
s += 'e\n'
- self.buf = []
- plots.append('"-" with lines')
- self.buf = []
+ plots.append('"-" with linespoints')
+ samples = samples[self.sps:]
+
+ self.buf = np.array([])
- h= 'set terminal x11 noraise\n'
- #background = 'set object 1 circle at screen 0,0 size screen 1 fillcolor rgb"black"\n' #FIXME!
+ # FFT processing needs to be completed to maintain the weighted average buckets
+ # regardless of whether we actually produce a new plot or not.
+ if self.plot_interval and self.last_plot + self.plot_interval > time.time():
+ return consumed
+ self.last_plot = time.time()
+
+ filename = None
+ if self.output_dir:
+ if self.sequence >= 2:
+ delete_pathname = '%s/plot-%s%d-%d.png' % (self.output_dir, mode, self.sequence_id, self.sequence-2)
+ if os.access(delete_pathname, os.W_OK):
+ os.remove(delete_pathname)
+ h0= 'set terminal png size %d, %d\n' % (plot_size)
+ filename = 'plot-%s%d-%d.png' % (mode, self.sequence_id, self.sequence)
+ h0 += 'set output "%s/%s"\n' % (self.output_dir, filename)
+ self.sequence += 1
+ else:
+ pos = ''
+ if self.position is not None:
+ x = self.position[0] * plot_size[0]
+ y = self.position[1] * plot_size[1]
+ x += 50
+ y += 75
+ pos = ' position %d, %d' % (x, y)
+ h0= 'set terminal x11 noraise size %d, %d%s title "%s"\n' % (plot_size[0], plot_size[1], pos, self.title)
background = ''
- h+= 'set key off\n'
+
+ label_color = ''
+ tic_color = ''
+ border_color = ''
+ plot_color = ''
+ background_color = ''
+
+ if self.colors['label_color']:
+ label_color = 'textcolor rgb"%s"' % self.colors['label_color']
+ if self.colors['tic_color']:
+ tic_color = 'textcolor rgb"%s"' % self.colors['tic_color']
+ if self.colors['border_color']:
+ border_color = 'linecolor rgb"%s"' % self.colors['border_color']
+ if self.colors['plot_color']:
+ plot_color = 'linecolor rgb"%s"' % self.colors['plot_color']
+ if self.colors['background_color']:
+ background_color = 'fillcolor rgb"%s"' % self.colors['background_color']
+
+ background += 'set object 1 rectangle from screen 0,0 to screen 1,1 %s behind\n' % (background_color)
+ background += 'set xtics %s\n' % (tic_color)
+ background += 'set ytics %s\n' % (tic_color)
+ background += 'set border %s\n' % (border_color)
+
+ h = 'set key off\n'
if mode == 'constellation':
- h+= background
+ #h+= background
+ plot_color = ''
h+= 'set size square\n'
h+= 'set xrange [-1:1]\n'
h+= 'set yrange [-1:1]\n'
+ h += 'unset border\n'
+ h += 'set polar\n'
+ h += 'set angles degrees\n'
+ h += 'unset raxis\n'
+ h += 'set object 1 rectangle from screen 0,0 to screen 1,1 %s behind\n' % (background_color)
+ h += 'set object 2 circle at 0,0 size 1 fillcolor rgb 0x0f01 fillstyle solid behind\n'
+ h += 'set object 3 circle at 0,0 size 1 %s\n' % 'linecolor rgb"#0000f0"'
+ h += 'set style line 10 lt 1 lc rgb 0x404040 lw 0.1\n'
+ h += 'set grid polar 45\n'
+ h += 'set grid ls 10\n'
+ h += 'set xtics axis\n'
+ h += 'set ytics axis\n'
+ h += 'set xtics scale 0\n'
+ h += 'set xtics ("" 0.2, "" 0.4, "" 0.6, "" 0.8, "" 1)\n'
+ h += 'set ytics 0, 0.2, 1\n'
+ h += 'set format ""\n'
+ h += 'set style line 11 lt 1 lw 2 pt 2 ps 2\n'
+
+ h+= 'set title "Constellation %s" %s\n' % (self.title, label_color)
elif mode == 'eye':
h+= background
h+= 'set yrange [-4:4]\n'
+ h+= 'set title "Datascope %s" %s\n' % (self.title, label_color)
+ plot_color = ''
+ elif mode == 'cpm':
+ h+= background
+ #h+= 'set yrange [-4:4]\n'
+ h+= 'set title "CPM RSSI %s" %s\n' % (self.title, label_color)
+ #plot_color = ''
+ elif mode == 'cpmd':
+ h+= background
+ h+= 'set yrange [-4:4]\n'
+ h+= 'set title "CPM Datascope %s" %s\n' % (self.title, label_color)
+ plot_color = ''
+ elif mode == 'sync':
+ h += 'set object 1 rect from screen 0,0 to screen 1,1 %s behind\n' % (background_color)
+ h += 'set size square\n'
+ h += 'set xtics %s\n' % (tic_color)
+ h += 'set ytics %s\n' % (tic_color)
+ h += 'set border %s\n' % (border_color)
elif mode == 'symbol':
h+= background
h+= 'set yrange [-4:4]\n'
- elif mode == 'fft':
+ h+= 'set title "Symbol %s" %s\n' % (self.title, label_color)
+ elif mode == 'fft' or mode == 'mixer':
+ h+= background
h+= 'unset arrow; unset title\n'
h+= 'set xrange [%f:%f]\n' % (self.freqs[0], self.freqs[len(self.freqs)-1])
+ h+= 'set xlabel "Frequency"\n'
+ h+= 'set ylabel "Power(dB)"\n'
+ h+= 'set grid\n'
h+= 'set yrange [-100:0]\n'
- h+= 'set xlabel "Frequency"\n'
- h+= 'set ylabel "Power(dB)"\n'
- h+= 'set grid\n'
- if self.center_freq:
- arrow_pos = (self.center_freq - self.relative_freq) / 1e6
- h+= 'set arrow from %f, graph 0 to %f, graph 1 nohead\n' % (arrow_pos, arrow_pos)
- h+= 'set title "Tuned to %f Mhz"\n' % ((self.center_freq - self.relative_freq) / 1e6)
- dat = '%splot %s\n%s' % (h, ','.join(plots), s)
- self.gp.stdin.write(dat)
+ if mode == 'mixer': # mixer
+ h+= 'set title "Mixer %s: balance %3.0f (smaller is better)" %s\n' % (self.title, np.abs(self.avg_sum_pwr * 1000), label_color)
+ else: # fft
+ h+= 'set title "Spectrum %s" %s\n' % (self.title, label_color)
+ if self.center_freq:
+ arrow_pos = (self.center_freq - self.relative_freq) / 1e6
+ h+= 'set arrow from %f, graph 0 to %f, graph 1 nohead\n' % (arrow_pos, arrow_pos)
+ h+= 'set title "Spectrum: tuned to %f Mhz" %s\n' % (arrow_pos, label_color)
+ elif mode == 'fftf':
+ h+= 'set yrange [-1:1.2]\n'
+ h+= 'set title "fftf"\n'
+ elif mode == 'float':
+ h+= background
+ h+= 'set yrange [-2:2]\n'
+ h+= 'set title "Oscilloscope %s" %s\n' % (self.title, label_color)
+ elif mode == 'correlation':
+ h+= background
+ title = 'Correlation'
+ if self.title:
+ title = self.title
+ h+= 'set yrange [-1.1:1.1]\n'
+ h+= 'set title "%s" %s\n' % (title, label_color)
+ if self.output_dir:
+ s += 'set output\n' ## flush output png
+ dat = '%s%splot %s %s\n%s' % (h0, h, ','.join(plots), plot_color, s)
+ if self.logfile is not None:
+ with open(self.logfile, 'a') as fd:
+ fd.write(dat)
+ if sys.version[0] != '2':
+ dat = bytes(dat, 'utf8')
+ self.gp.poll()
+ if self.gp.returncode is None: # make sure gnuplot is still running
+ try:
+ rc = self.gp.stdin.write(dat)
+ except (IOError, ValueError):
+ pass
+ try:
+ self.gp.stdin.flush()
+ except (IOError, ValueError):
+ pass
+ if filename:
+ self.filename = filename
return consumed
def set_center_freq(self, f):
@@ -146,9 +434,18 @@ class wrap_gp(object):
def set_relative_freq(self, f):
self.relative_freq = f
+ def set_offset(self, f):
+ self.offset_freq = f
+
def set_width(self, w):
self.width = w
+ def set_logfile(self, logfile=None):
+ self.logfile = logfile
+
+ def set_title(self, title):
+ self.title = title
+
class eye_sink_f(gr.sync_block):
"""
"""
@@ -163,9 +460,37 @@ class eye_sink_f(gr.sync_block):
def work(self, input_items, output_items):
in0 = input_items[0]
- consumed = self.gnuplot.plot(in0, 100 * self.sps, mode='eye')
+ consumed = self.gnuplot.plot(in0, 100*self.sps, mode='eye')
return consumed ### len(input_items[0])
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
+class cpm_sink_c(gr.sync_block):
+ """
+ """
+ def __init__(self, debug = _def_debug, sps = _def_sps, plot_mode=_def_cpm_mode):
+ gr.sync_block.__init__(self,
+ name="cpm_sink_c",
+ in_sig=[np.complex64],
+ out_sig=None)
+ self.debug = debug
+ self.sps = sps
+ self.gnuplot = wrap_gp(sps=self.sps)
+ self.plot_mode=plot_mode
+
+ def work(self, input_items, output_items):
+ in0 = input_items[0]
+ l = len(in0)
+ consumed = self.gnuplot.plot(in0, self.sps*180*10, mode=self.plot_mode)
+ return len(input_items[0])
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
def kill(self):
self.gnuplot.kill()
@@ -182,7 +507,33 @@ class constellation_sink_c(gr.sync_block):
def work(self, input_items, output_items):
in0 = input_items[0]
- self.gnuplot.plot(in0, 1000, mode='constellation')
+ self.gnuplot.plot(in0, 1000, mode='constellation')
+ return len(input_items[0])
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
+class fft_sink_f(gr.sync_block):
+ """
+ """
+ def __init__(self, debug = _def_debug):
+ gr.sync_block.__init__(self,
+ name="fft_sink_f",
+ in_sig=[np.float32],
+ out_sig=None)
+ self.debug = debug
+ self.gnuplot = wrap_gp()
+ self.skip = 0
+
+ def work(self, input_items, output_items):
+ self.skip += 1
+ if self.skip >= 50:
+ self.skip = 0
+ in0 = input_items[0]
+ self.gnuplot.plot(in0, FFT_BINS, mode='fftf')
return len(input_items[0])
def kill(self):
@@ -202,25 +553,140 @@ class fft_sink_c(gr.sync_block):
def work(self, input_items, output_items):
self.skip += 1
- if self.skip == 50:
+ if self.skip >= 50:
self.skip = 0
in0 = input_items[0]
- self.gnuplot.plot(in0, FFT_BINS, mode='fft')
+ self.gnuplot.plot(in0, FFT_BINS, mode='fft')
return len(input_items[0])
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
def kill(self):
self.gnuplot.kill()
def set_center_freq(self, f):
self.gnuplot.set_center_freq(f)
- self.gnuplot.set_relative_freq(0.0)
+ self.gnuplot.set_relative_freq(0.0)
def set_relative_freq(self, f):
self.gnuplot.set_relative_freq(f)
+ def set_offset(self, f):
+ self.gnuplot.set_offset(f)
+
def set_width(self, w):
self.gnuplot.set_width(w)
+class mixer_sink_c(gr.sync_block):
+ """
+ """
+ def __init__(self, debug = _def_debug):
+ gr.sync_block.__init__(self,
+ name="mixer_sink_c",
+ in_sig=[np.complex64],
+ out_sig=None)
+ self.debug = debug
+ self.gnuplot = wrap_gp()
+ self.skip = 0
+
+ def work(self, input_items, output_items):
+ self.skip += 1
+ if self.skip >= 10:
+ self.skip = 0
+ in0 = input_items[0]
+ self.gnuplot.plot(in0, FFT_BINS, mode='mixer')
+ return len(input_items[0])
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
+class sync_plot(threading.Thread):
+ """
+ """
+ def __init__(self, debug = _def_debug, block = None, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.SLEEP_TIME = 3 ## TODO - make more configurable
+ self.sleep_until = time.time() + self.SLEEP_TIME
+ self.last_file_time = time.time()
+ self.keep_running = True
+ self.debug = debug
+ self.warned = False
+
+ block.enable_sync_plot(True) # block must refer to a gardner/costas instance
+ self.blk_id = block.unique_id()
+
+ self.gnuplot = wrap_gp(sps = _def_sps)
+ self.start()
+
+ def run(self):
+ while self.keep_running == True:
+ curr_time = time.time()
+ if curr_time < self.sleep_until:
+ time.sleep(1.0)
+ if self.keep_running == False:
+ break
+ else:
+ self.sleep_until = time.time() + self.SLEEP_TIME
+ self.check_update()
+
+ def read_raw_file(self, fn):
+ s = open(fn, 'rb').read()
+ s_msg = ensure_str(s)
+ p = s_msg.find('\n')
+ if p < 1 or p > 24:
+ return None # error
+ hdrline = s_msg[:p]
+ rest = s[p+1:]
+ params = hdrline.split()
+ params = [int(p) for p in params] #idx, p1p2, sps, error
+ idx = params[0]
+ p1p2 = params[1]
+ sps = params[2]
+ error_amt = params[3]
+ self.gnuplot.set_sps(sps)
+ if error_amt != 0:
+ self.set_title("Tuning Error %d" % error_amt)
+ else:
+ self.set_title("")
+ samples = np.frombuffer(rest, dtype=np.complex64)
+ samples2 = np.concatenate((samples[idx:], samples[:idx]))
+ needed = sps * 25 if p1p2 == 1 else sps * 21
+ if len(samples2) < needed:
+ if not self.warned:
+ self.warned = True
+ sys.stderr.write('read_raw_file: insufficient samples %d, needed %d\n' % (needed, len(samples2)))
+ elif len(samples2) > needed:
+ trim = len(samples2) - needed
+ samples2 = samples2[trim:]
+ return samples2 # return trimmed buf in np.complex64 format
+
+ def check_update(self):
+ patt = 'sample-%d*.dat' % (self.blk_id)
+ names = glob.glob(patt)
+ if len(names) < 1: # no files to work with
+ return
+ d = {n: os.stat(n).st_mtime for n in names}
+ ds = sorted(d.items(), key=lambda x:x[1], reverse = True)[0]
+ if ds[1] <= self.last_file_time:
+ return
+ self.last_file_time = ds[1]
+ dat = self.read_raw_file(ds[0])
+ self.gnuplot.plot(dat, len(dat), mode='sync')
+
+ def kill(self):
+ self.keep_running = False
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
class symbol_sink_f(gr.sync_block):
"""
"""
@@ -234,8 +700,107 @@ class symbol_sink_f(gr.sync_block):
def work(self, input_items, output_items):
in0 = input_items[0]
- self.gnuplot.plot(in0, 2400, mode='symbol')
+ self.gnuplot.plot(in0, 2400, mode='symbol')
+ return len(input_items[0])
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
+class float_sink_f(gr.sync_block):
+ """
+ """
+ def __init__(self, debug = _def_debug):
+ gr.sync_block.__init__(self,
+ name="float_sink_f",
+ in_sig=[np.float32],
+ out_sig=None)
+ self.debug = debug
+ self.gnuplot = wrap_gp()
+
+ def work(self, input_items, output_items):
+ in0 = input_items[0]
+ self.gnuplot.plot(in0, 2000, mode='float')
+ return len(input_items[0])
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def kill(self):
+ self.gnuplot.kill()
+
+class correlation_sink_f(gr.sync_block):
+ """
+ """
+ def __init__(self, sps=_def_sps, debug = _def_debug):
+ gr.sync_block.__init__(self,
+ name="plot_sink_f",
+ in_sig=[np.float32],
+ out_sig=None)
+ self.debug = debug
+ self.sps = sps
+ self.gnuplot = wrap_gp()
+ self.fs = []
+ self.cbuf = np.array([])
+ self.ignore = 0
+ self.pktlen = 1024
+
+ def set_length(self, l):
+ self.pktlen = l
+
+ def set_title(self, title):
+ self.gnuplot.set_title(title)
+
+ def set_signature(self, fs):
+ self.fs = []
+ for s in fs:
+ for i in range(self.sps):
+ self.fs.append(s)
+ self.fs.reverse() # reverse order for np.convolve
+ self.fs = np.array(self.fs)
+
+ def work(self, input_items, output_items):
+ if len(self.cbuf) == 0 and self.ignore > 0:
+ self.ignore -= len(input_items[0])
+ if self.ignore < 0:
+ self.ignore = 0
+ return len(input_items[0])
+ if len(self.fs) == 0:
+ return len(input_items[0])
+ in0 = input_items[0]
+ self.cbuf = np.append(self.cbuf, in0)
+ if len(self.cbuf) < self.pktlen:
+ return len(input_items[0])
+ result = np.convolve(self.cbuf[:self.pktlen], self.fs)
+ hi = np.max(np.abs(result))
+ if hi != 0:
+ result = result / hi
+ self.cbuf = []
+ self.ignore = 3000 * self.sps
+ self.gnuplot.plot(result, len(result), mode='correlation')
return len(input_items[0])
def kill(self):
self.gnuplot.kill()
+
+def setup_correlation(sps, title, connect_bb):
+ CFG_FILE = 'correlation.json'
+ if not os.access(CFG_FILE, os.R_OK):
+ sys.stderr.write('correlation plot ignored, missing config file %s\n' % CFG_FILE)
+ return []
+ ccfg = json.loads(open(CFG_FILE).read())
+ sinks = []
+ for cfg in ccfg:
+ sink = correlation_sink_f(sps=sps)
+ sink.set_title('%s %s' % (title, cfg['name']))
+ l = cfg['length'] * sps * 4
+ LENGTH_LIMIT = 10000
+ if l > LENGTH_LIMIT:
+ l = LENGTH_LIMIT
+ sink.set_length(l)
+ sink.set_signature(cfg['fs'])
+ connect_bb('baseband_amp', sink)
+ sinks.append(sink)
+ return sinks
diff --git a/op25/gr-op25_repeater/apps/h_cpm.m b/op25/gr-op25_repeater/apps/h_cpm.m
new file mode 100644
index 0000000..3b67d7f
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/h_cpm.m
@@ -0,0 +1,350 @@
+
+% P25 H-CPM Demodulator (C) Copyright 2022 Max H. Parke KA1RBI
+% % Experimental H-CPM Demodulator - Release 0 %
+%
+% This file is part of OP25
+%
+% OP25 is free software; you can redistribute it and/or modify it
+% under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 3, or (at your option)
+% any later version.
+%
+% OP25 is distributed in the hope that it will be useful, but WITHOUT
+% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+% License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with OP25; see the file COPYING. If not, write to the Free
+% Software Foundation, Inc., 51 Franklin Street, Boston, MA
+% 02110-1301, USA.
+%
+%
+%
+% Accepts input IF file in GR binary complex64 format;
+% file must be at sample rate 24,000 samples/sec.
+%
+% this implementation has several simplifications, shortcuts,
+% and pitfalls, some of which are:
+%
+% * input sample must be clean and error free, there is
+% currently no tree search (viterbi) stage - decode errors
+% that should be recoverable are not autocorrected
+% * since the first and last one-quarter of the partial-response
+% period (in L=4) appear to contribute a negligible delta-phase,
+% this correlator ignores these intervals, using only the inner-
+% most two periods - accordingly, the value L=2 is assumed
+% * the code is too slow to demod in real time and there are no claims
+% to efficiency
+% * at each symbol period the received waveform vector is derotated.
+% this reduces the number of rows in the waveform matrix by a factor of
+% six (6); instead of derotating the samples, a correct correlator would
+% include these (approx. 80) additional rows
+%
+
+pkg load signal;
+
+global WI0 = [
+ 1.000000, 0.999827, 0.998111, 0.963512, 0.819784, 0.500000,
+ 1.000000, 0.958473, 0.800512, 0.483695, 0.022053, -0.475169,
+ 1.000000, 0.978152, 0.913558, 0.808999, 0.669116, 0.500000,
+ 1.000000, 0.966921, 0.819689, 0.504702, 0.047650, -0.424375,
+ 1.000000, 0.984174, 0.926374, 0.822966, 0.687929, 0.548428,
+ 1.000000, 0.918644, 0.736098, 0.572238, 0.506066, 0.548428,
+ 1.000000, 0.995165, 0.986853, 0.986153, 0.994884, 0.999596,
+ 1.000000, 0.947207, 0.867963, 0.865831, 0.946296, 0.999596,
+ 1.000000, 0.869202, 0.540278, 0.146957, -0.204506, -0.475169,
+ 1.000000, 0.884236, 0.567518, 0.170815, -0.179370, -0.424375,
+ 1.000000, 0.827032, 0.340050, -0.286034, -0.793734, -0.998382,
+ 1.000000, 0.905842, 0.713560, 0.552256, 0.483811, 0.500000,
+ 1.000000, 0.936720, 0.851252, 0.853489, 0.937706, 0.999596,
+ 1.000000, 0.998757, 0.999587, 0.969698, 0.834181, 0.548428,
+ 1.000000, 0.844204, 0.370632, -0.262797, -0.777895, -0.993535,
+ 1.000000, 0.991608, 0.981038, 0.981858, 0.991970, 0.999596,
+ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
+ 0.99179 0.98062998 0.95472002 0.92157 0.89235997 0.87256002];
+
+global WQ0 = [
+ 0.000000, -0.018594, 0.061430, 0.267665, 0.572673, 0.866026,
+ 0.000000, 0.285183, 0.599317, 0.875237, 0.999757, 0.879895,
+ 0.000000, 0.207893, 0.406709, 0.587810, 0.743158, 0.866026,
+ 0.000000, -0.255075, -0.572808, -0.863294, -0.998864, -0.905486,
+ 0.000000, -0.177207, -0.376605, -0.568091, -0.725778, -0.836198,
+ 0.000000, -0.395087, -0.676875, -0.820088, -0.862495, -0.836198,
+ 0.000000, -0.098212, -0.161618, -0.165838, -0.101028, 0.028438,
+ 0.000000, -0.320622, -0.496628, -0.500337, -0.323300, 0.028438,
+ 0.000000, 0.494458, 0.841486, 0.989143, 0.978865, 0.879895,
+ 0.000000, -0.467040, -0.823361, -0.985303, -0.983782, -0.905486,
+ 0.000000, 0.562154, 0.940407, 0.958220, 0.608265, 0.056855,
+ 0.000000, 0.423616, 0.700594, 0.833674, 0.875173, 0.866025,
+ 0.000000, 0.350080, 0.524757, 0.521112, 0.347429, 0.028438,
+ 0.000000, 0.049845, -0.028745, -0.244306, -0.551491, -0.836198,
+ 0.000000, -0.536021, -0.928780, -0.964851, -0.628394, -0.113525,
+ 0.000000, 0.129280, 0.193816, 0.189618, 0.126474, 0.028438,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0. 0.13601001 0.26787999 0.37345001 0.44356 0.48087999];
+
+global S_A = zeros(18,"int");
+global S_B = zeros(18,"int");
+S_A(1) = -1;
+S_B(1) = 3;
+S_A(2) = 1;
+S_B(2) = 3;
+S_A(3) = 1;
+S_B(3) = 1;
+S_A(4) = -1;
+S_B(4) = -3;
+S_A(5) = -1;
+S_B(5) = -1;
+S_A(6) = -3;
+S_B(6) = 1;
+S_A(7) = -1;
+S_B(7) = 1;
+S_A(8) = -3;
+S_B(8) = 3;
+S_A(9) = 3;
+S_B(9) = 1;
+S_A(10) = -3;
+S_B(10) = -1;
+S_A(11) = 3;
+S_B(11) = 3;
+S_A(12) = 3;
+S_B(12) = -1;
+S_A(13) = 3;
+S_B(13) = -3;
+S_A(14) = 1;
+S_B(14) = -3;
+S_A(15) = -3;
+S_B(15) = -3;
+S_A(16) = 1;
+S_B(16) = -1;
+S_A(17) = 0;
+S_B(17) = 0;
+S_A(18) = 1;
+S_B(18) = 1;
+
+global L = 4; %sps
+global M = 10 % interp factor
+global LM = L*M;
+global Q = 8; % decim amount
+global NEWSPS = 5; % after decimation
+global K=360.0 / (2 * pi); % radians -> degrees
+global k = 6.0 / (2 * pi);
+
+% change name of input data file
+fname = 'if-24000-IQ.dat';
+
+function samples = load_text(fname)
+ fid = fopen(fname, 'r');
+ nn = 0;
+ while 1
+ nn = nn+1;
+ s = fgetl(fid);
+ if s == -1
+ break;
+ endif
+ res = sscanf(s, "%f\t%f");
+ samples(nn) = res(1) + 1j*res(2);
+ endwhile
+ g = max(abs(samples));
+ samples = samples / g;
+endfunction
+
+function amt_left = process_dat(dat)
+ global L
+ iq = dat(1:2:end-1) .+ 1j * dat(2:2:end);
+ a = abs(iq);
+ thresh = max(a) / 2.0;
+ msk = a > thresh;
+ m1 = msk(2:end) - msk(1:end-1);
+ f = find(m1);
+ m1f = m1(f)(end);
+ lens = f(2:end) - f(1:end-1);
+ l1 = (lens/L > 170 & lens/L < 180) | (lens/L > 350 & lens/L < 360);
+ l2 = m1(f) == 1;
+ l2 = l2(1:end-1);
+ found = find(l1 & l2);
+ if(length(found)) < 1
+ amt_left = 0;
+ return;
+ endif
+ for n = 1:length(found)
+ valid = found(n);
+ start1 = f(valid);
+ len1 = lens(valid);
+ demod_frag(iq(start1:start1+len1));
+ end
+ validn = found(end);
+ startn = f(validn);
+ lenn = lens(validn);
+ datlen=length(dat);
+ amt_left = length(dat) - (startn + lenn);
+ if (amt_left < 0)
+ amt_left = 0;
+ endif
+endfunction
+
+function process_file(filename)
+ global L
+ bufsize = L * 180 * 12;
+ fid = fopen(filename, 'r');
+ save = [];
+ while 1
+ [dat, l] = fread(fid, bufsize, 'float32', 0);
+ if l < 1
+ break
+ endif
+ savel=size(save);
+ datl=size(dat);
+ concat = [save.' dat.'].';
+ amt_left = process_dat(concat);
+ if (amt_left > 0)
+ save = concat(end-amt_left:end);
+ else
+ save = [];
+ endif
+ endwhile
+endfunction
+
+function large_frag(msg)
+ msgl = length(msg);
+ padsz = 360 - msgl;
+ lenh = round(length(msg) / 2);
+ fmsg1 = frame_msg(msg(1:lenh),1);
+ decode_msg(fmsg1);
+ fmsg2 = frame_msg(msg(lenh:end),2);
+ decode_msg(fmsg2);
+endfunction
+
+function msg=demod_frag(frag)
+ global L
+ global NEWSPS
+ global M
+ amt_trim = mod(length(frag), L);
+ frag = frag(1:end-amt_trim);
+ g = max(abs(frag));
+ frag = frag / g;
+ nsyms = length(frag) / L;
+ intrp0 = interp(frag, M);
+ resampq=timing_sync(intrp0);
+ nsyms = length(resampq) / NEWSPS;
+ resamp1=frequency_sync(resampq);
+ msg=correlation(resamp1);
+ if length(msg) > 270
+ large_frag(msg);
+ else
+ fmsg=frame_msg(msg,1);
+ decode_msg(fmsg);
+ lfmsg=length(fmsg);
+ endif
+endfunction
+
+function decode_msg(msg)
+ if length(msg) != 160
+ return
+ endif
+ DMAP = [3 2 0 1];
+ duid = msg([37,74,123,160]) + 3;
+ duid = (duid / 2) + 1;
+ dibits = DMAP(duid);
+ duidx = dibits(1) * 64 + dibits(2) * 16 + dibits(3) * 4 + dibits(4);
+ printf ('hex %x\n' , duidx);
+endfunction
+
+function resampq=timing_sync(intrp0)
+ global LM
+ global NEWSPS
+ global Q
+ nsyms = length(intrp0) / LM;
+ fmd = angle(intrp0(2:end) .* conj(intrp0(1:end-1)));
+ fmx = mod(LM*6* ([fmd' 0] / (2*pi) + 0.5) + 0.5, 1);
+ matx= reshape(fmx, LM, nsyms );
+ res = std(matx');
+ [m, amin] = min(res);
+ amin = amin + 0 + (LM/2);
+ if amin > LM
+ amin = amin - LM;
+ endif
+ resampq = intrp0(amin:Q:end); # decim by Q
+ amt_trim = mod(length(resampq), NEWSPS);
+ resampq = resampq(1:end-amt_trim);
+endfunction
+
+function resamp1=frequency_sync(resampq)
+ global NEWSPS
+ global k
+ F = 0;
+ sz1 = length(resampq);
+ for iter = 1:4
+ osc = [0:sz1-1] * (F / 30000);
+ osc = exp(j*2*pi*osc);
+ resamp1 = resampq .* osc.';
+ row = resamp1(1:NEWSPS:end);
+ rowz = mod(k*angle(row)+0.5, 1);
+ rowz = unwrap((rowz-0.5) * 2*pi);
+ meanr = mean(rowz(5:15)) - mean(rowz(end-15:end-5));
+ F = F + meanr;
+ end
+ nsyms = length(resamp1) / NEWSPS;
+ rfm = angle(resamp1(2:end) .* conj(resamp1(1:end-1)));
+ afm = angle(resamp1);
+endfunction
+
+function eye_plot(dat, sps)
+ hold on
+ for nn = 1:sps:length(dat)-sps*2
+ sl = dat(nn:nn+sps);
+ plot(sl);
+ end
+ hold off
+ pause
+endfunction
+
+function msg=correlation(resamp1)
+ global NEWSPS
+ global WI0
+ global WQ0
+ global S_A
+ global S_B
+ global K
+ nsyms = length(resamp1) / NEWSPS;
+ for n= 1 : NEWSPS : length(resamp1) - NEWSPS
+ stepn=(n-1)/NEWSPS;
+ idx = ((n-1) / NEWSPS) + 1;
+ sl=resamp1(n:n+NEWSPS);
+ sl = sl * conj(sl(1));
+ sl_i = real(sl);
+ sl_q = imag(sl);
+ corr2 = sl_i' * WI0' + sl_q' * WQ0';
+ [m,am] = max(corr2);
+ msga(idx) = S_A(am);
+ msgb(idx) = S_B(am);
+ end
+ msgok=msga(2:end) == msgb(1:end-1);
+ ok=sum(msgok) / length(msga);
+ msg=msgb;
+endfunction
+
+function msg=frame_msg(imsg, fcode)
+ if (fcode == 1)
+ pilots = [1 -1 -1 1];
+ else
+ pilots = [-3 -3 -1 1];
+ endif
+ fml = length(imsg);
+ msg = [];
+ excess=length(imsg) - 160;
+ for n=1:excess
+ if n+163 > length(imsg)
+ break
+ endif
+ slx = [imsg(n:n+1), imsg(n+162:n+163)];
+ if sum(slx == pilots) == 4
+ msg = imsg(n+2:n+161);
+ return;
+ endif
+ end
+ return;
+endfunction
+
+process_file(fname);
diff --git a/op25/gr-op25_repeater/apps/http_server.py b/op25/gr-op25_repeater/apps/http_server.py
new file mode 100755
index 0000000..1d10795
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/http_server.py
@@ -0,0 +1,589 @@
+#!/usr/bin/env python3
+
+# Copyright 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import sys
+import os
+import time
+import re
+import json
+import socket
+import traceback
+import threading
+import glob
+import subprocess
+import zmq
+import op25
+
+from gnuradio import gr
+from waitress.server import create_server
+from optparse import OptionParser
+from multi_rx import byteify
+from tsvfile import load_tsv, make_config
+
+import logging
+logging.basicConfig()
+
+my_input_q = None
+my_output_q = None
+my_recv_q = None
+my_port = None
+my_backend = None
+CFG_DIR = '../www/config/'
+TSV_DIR = './'
+
+"""
+fake http and ajax server module
+TODO: make less fake
+"""
+def ensure_str(s): # for python 2/3
+ if isinstance(s[0], str):
+ return s
+ ns = ''
+ for i in range(len(s)):
+ ns += chr(s[i])
+ return ns
+
+class event_iterator:
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ _jslog_file = None # set to str(filename) to enable json log
+ msgs = []
+ while True:
+ msg = my_input_q.delete_head()
+ assert msg.type() == -4
+ d = json.loads(msg.to_string())
+ msgs.append(d)
+ if my_input_q.empty_p():
+ break
+ js = json.dumps(msgs)
+ # TODO: json.loads followed by dumps is redundant -
+ # can this be optimized?
+ s = 'data:%s\r\n\r\n' % (js)
+
+ if _jslog_file:
+ t = json.dumps(msgs, indent=4, separators=[',',':'], sort_keys=True)
+ with open(_jslog_file, 'a') as logfd:
+ logfd.write('%s\n' % t)
+
+ if sys.version[0] != '2':
+ if isinstance(s, str):
+ s = s.encode()
+ return s
+
+ next = __next__ # for python2
+
+def static_file(environ, start_response):
+ content_types = {'tsv': 'text/tab-separated-values', 'json': 'application/json', 'png': 'image/png', 'jpeg': 'image/jpeg', 'jpg': 'image/jpeg', 'gif': 'image/gif', 'css': 'text/css', 'js': 'application/javascript', 'html': 'text/html', 'ico': 'image/vnd.microsoft.icon'}
+ img_types = 'png jpg jpeg gif ico'.split()
+ data_types = 'tsv txt json db'.split()
+ if environ['PATH_INFO'] == '/':
+ filename = 'index.html'
+ else:
+ filename = re.sub(r'[^a-zA-Z0-9_.\-/]', '', environ['PATH_INFO'])
+ suf = filename.split('.')[-1]
+ pathname = '../www/www-static'
+ if suf in img_types:
+ pathname = '../www/images'
+ elif suf in data_types:
+ pathname = TSV_DIR
+ pathname = '%s/%s' % (pathname, filename)
+ if suf not in content_types.keys() or '..' in filename or not os.access(pathname, os.R_OK):
+ sys.stderr.write('404 %s\n' % pathname)
+ status = '404 NOT FOUND - PATHNAME: %s FILENAME: %s CWD: %s' % (pathname, filename, os. getcwd())
+ content_type = 'text/plain'
+ output = status
+ else:
+ output = open(pathname, 'rb').read()
+ content_type = content_types[suf]
+ status = '200 OK'
+ return status, content_type, output
+
+def valid_tsv(filename):
+ if not os.access(filename, os.R_OK):
+ return False
+ line = open(filename).readline()
+ for word in 'Sysname Offset NAC Modulation TGID Whitelist Blacklist'.split():
+ if word not in line:
+ return False
+ return True
+
+def tsv_config(filename):
+ DEFAULT_CFG = '../www/config/default.json'
+ filename = '%s%s' % (TSV_DIR, filename)
+ filename = filename.replace('[TSV]', '.tsv')
+ if not valid_tsv(filename):
+ return None
+ cfg = make_config(load_tsv(filename))
+ default_cfg = json.loads(open(DEFAULT_CFG).read())
+
+ result = default_cfg
+ channels = [ {'active': True,
+ 'blacklist': cfg[nac]['blacklist'],
+ 'whitelist': cfg[nac]['whitelist'],
+ 'cclist': cfg[nac]['cclist'],
+ 'demod_type': 'cqpsk',
+ 'destination': 'udp://127.0.0.1:23456',
+ 'filter_type': 'rc',
+ 'frequency': 500000000,
+ 'if_rate': 24000,
+ 'nac': nac,
+ 'name': cfg[nac]['sysname'],
+ 'phase2_tdma': False,
+ 'plot': "",
+ 'tgids': cfg[nac]['tgid_map'],
+ 'trunked': True
+ }
+ for nac in cfg.keys() ]
+ result['channels'] = channels
+ return {'json_type':'config_data', 'data': result}
+
+def do_request(d):
+ global my_backend
+ if d['command'].startswith('rx-'):
+ msg = gr.message().make_from_string(json.dumps(d), -2, 0, 0)
+ if not my_backend.input_q.full_p():
+ my_backend.input_q.insert_tail(msg)
+ return None
+ elif d['command'] == 'config-load':
+ if '[TSV]' in d['data']:
+ return tsv_config(d['data'])
+ filename = '%s%s.json' % (CFG_DIR, d['data'])
+ if not os.access(filename, os.R_OK):
+ return None
+ js_msg = json.loads(open(filename).read())
+ return {'json_type':'config_data', 'data': js_msg}
+ elif d['command'] == 'config-list':
+ files = glob.glob('%s*.json' % CFG_DIR)
+ files = [x.replace('.json', '') for x in files]
+ files = [x.replace(CFG_DIR, '') for x in files]
+ if d['data'] == 'tsv':
+ tsvfiles = glob.glob('%s*.tsv' % TSV_DIR)
+ tsvfiles = [x for x in tsvfiles if valid_tsv(x)]
+ tsvfiles = [x.replace('.tsv', '[TSV]') for x in tsvfiles]
+ tsvfiles = [x.replace(TSV_DIR, '') for x in tsvfiles]
+ files += tsvfiles
+ return {'json_type':'config_list', 'data': files}
+ elif d['command'] == 'config-save':
+ name = d['data']['name']
+ if '..' in name or '.json' in name or '/' in name:
+ return None
+ filename = '%s%s.json' % (CFG_DIR, d['data']['name'])
+ open(filename, 'w').write(json.dumps(d['data']['value'], indent=4, separators=[',',':'], sort_keys=True))
+ return None
+ elif d['command'] == 'config-savesettings':
+ filename = 'ui-settings.json'
+ open(filename, 'w').write(d['data'])
+ sys.stderr.write('saved UI settings to %s\n' % filename)
+ return None
+ elif d['command'] == 'config-tsvsave':
+ filename = d['file']
+ ok = True
+ if filename.lower().endswith('tsv'):
+ ok = True
+ elif filename.lower().endswith('json'):
+ ok = True
+ else:
+ ok = False
+ if filename.startswith('.'):
+ ok = False
+ if '/' in filename:
+ ok = False
+ if '..' in filename:
+ ok = False
+ if not ok:
+ sys.stderr.write('cfg-tsvsave: invalid filename %s\n' % filename)
+ return None
+ open(filename, 'w').write(d['data'])
+ sys.stderr.write('saved UI settings to %s\n' % filename)
+ return None
+
+def post_req(environ, start_response, postdata):
+ global my_input_q, my_output_q, my_recv_q, my_port
+ resp_msg = []
+ data = []
+ try:
+ data = json.loads(postdata)
+ except:
+ sys.stderr.write('post_req: error processing input: %s:\n' % (postdata))
+ traceback.print_exc(limit=None, file=sys.stderr)
+ sys.stderr.write('*** end traceback ***\n')
+ for d in data:
+ if type(d) is str:
+ sys.stderr.write('%f possible json sequence error: len %d type %s value %s\n' % (time.time(), len(d), type(d), d))
+ continue
+ elif type(d) is not dict:
+ sys.stderr.write('%f possible json sequence error: type %s value %s\n' % (time.time(), type(d), d))
+ continue
+ if d['command'].startswith('config-') or d['command'].startswith('rx-'):
+ resp = do_request(d)
+ if resp:
+ resp_msg.append(resp)
+ continue
+ if d['command'].startswith('settings-'):
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ else:
+ msg = gr.message().make_from_string(str(d['command']), -2, d['data'], 0)
+ if my_output_q.full_p():
+ my_output_q.delete_head_nowait() # ignores result
+ if not my_output_q.full_p():
+ my_output_q.insert_tail(msg)
+ time.sleep(0.2)
+
+ status = '200 OK'
+ content_type = 'application/json'
+ output = json.dumps(resp_msg)
+ return status, content_type, output
+
+def http_request(environ, start_response):
+ if environ['REQUEST_METHOD'] == 'GET' and '/stream' in environ['PATH_INFO']:
+ status = '200 OK'
+ content_type = 'text/event-stream'
+ response_headers = [('Content-type', content_type),
+ ('Access-Control-Allow-Origin', '*')]
+ start_response(status, response_headers)
+ return iter(event_iterator())
+ elif environ['REQUEST_METHOD'] == 'GET':
+ status, content_type, output = static_file(environ, start_response)
+ elif environ['REQUEST_METHOD'] == 'POST':
+ postdata = environ['wsgi.input'].read()
+ status, content_type, output = post_req(environ, start_response, postdata)
+ else:
+ status = '200 OK'
+ content_type = 'text/plain'
+ output = status
+ sys.stderr.write('http_request: unexpected input %s\n' % environ['PATH_INFO'])
+
+ response_headers = [('Content-type', content_type),
+ ('Access-Control-Allow-Origin', '*'),
+ ('Content-Length', str(len(output)))]
+ start_response(status, response_headers)
+
+ if sys.version[0] != '2':
+ if isinstance(output, str):
+ output = output.encode()
+ return [output]
+
+def application(environ, start_response):
+ failed = False
+ try:
+ result = http_request(environ, start_response)
+ except:
+ failed = True
+ sys.stderr.write('application: request failed:\n%s\n' % traceback.format_exc())
+ if failed:
+ status = '500 Internal Server Error'
+ response_headers = [ ('Access-Control-Allow-Origin', '*') ]
+ start_response(status, response_headers)
+ output = status
+ if sys.version[0] != '2':
+ if isinstance(output, str):
+ output = output.encode()
+ return [output]
+
+ return result
+
+def process_qmsg(msg):
+ if my_recv_q.full_p():
+ my_recv_q.delete_head_nowait() # ignores result
+ if my_recv_q.full_p():
+ return
+ my_recv_q.insert_tail(msg)
+
+class http_server(object):
+ def __init__(self, input_q, output_q, endpoint, **kwds):
+ global my_input_q, my_output_q, my_recv_q, my_port
+ host, port = endpoint.split(':')
+ if my_port is not None:
+ raise AssertionError('this server is already active on port %s' % my_port)
+ my_input_q = input_q
+ my_output_q = output_q
+ my_port = int(port)
+
+ my_recv_q = gr.msg_queue(10)
+
+ SEND_BYTES = 1024
+ NTHREADS = 10 # TODO: make #threads a function of #plots ?
+ self.server = create_server(application, host=host, port=my_port, send_bytes=SEND_BYTES, expose_tracebacks=True, threads=NTHREADS)
+
+ def run(self):
+ self.server.run()
+
+class queue_watcher(threading.Thread):
+ def __init__(self, msgq, callback, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.msgq = msgq
+ self.callback = callback
+ self.keep_running = True
+ self.start()
+
+ def run(self):
+ while(self.keep_running):
+ msg = self.msgq.delete_head()
+ self.callback(msg)
+
+class Backend(threading.Thread):
+ def __init__(self, options, input_q, output_q, init_config=None, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.keep_running = True
+ self.rx_options = None
+ self.input_q = input_q
+ self.output_q = output_q
+ self.verbosity = options.verbosity
+
+ self.zmq_context = zmq.Context()
+ self.zmq_port = options.zmq_port
+
+ self.zmq_sub = self.zmq_context.socket(zmq.SUB)
+ self.zmq_sub.connect('tcp://localhost:%d' % self.zmq_port)
+ self.zmq_sub.setsockopt_string(zmq.SUBSCRIBE, '')
+
+ self.zmq_pub = self.zmq_context.socket(zmq.PUB)
+ self.zmq_pub.sndhwm = 5
+ self.zmq_pub.bind('tcp://*:%d' % (self.zmq_port+1))
+
+ self.start()
+ self.subproc = None
+ self.msg = None
+
+ self.q_watcher = queue_watcher(self.input_q, self.process_msg)
+
+ if init_config:
+ d = {'command': 'rx-start', 'data': init_config}
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def publish(self, msg):
+ t = msg.type()
+ s = msg.to_string()
+ a = msg.arg1()
+ s = ensure_str(s)
+ self.zmq_pub.send_string(json.dumps({'command': s, 'data': a, 'msgtype': t}))
+
+ def check_subproc(self): # return True if subprocess is active
+ if not self.subproc:
+ return False
+ rc = self.subproc.poll()
+ if rc is None:
+ return True
+ else:
+ self.subproc.wait()
+ self.subproc = None
+ return False
+
+ def process_msg(self, msg):
+ def make_command(options, config_file):
+ py_exe = 'python'
+ if sys.version[0] == '3':
+ py_exe = 'python3'
+ trunked_ct = [True for x in options._js_config['channels'] if x['trunked']]
+ total_ct = [True for x in options._js_config['channels']]
+ if trunked_ct and len(trunked_ct) != len(total_ct):
+ self.msg = 'no suitable backend found for this configuration'
+ return None
+ if not trunked_ct:
+ self.backend = '%s/%s' % (os.getcwd(), 'multi_rx.py')
+ opts = [py_exe, self.backend]
+ filename = '%s%s.json' % (CFG_DIR, config_file)
+ opts.append('--config-file')
+ opts.append(filename)
+ return opts
+
+ # TODO: this probably should be external and/or configurable
+ # these options must match up one for one with the rx.py cli opts
+ types = {'costas-alpha': 'float',
+ 'trunk-conf-file': 'str',
+ 'demod-type': 'str',
+ 'logfile-workers': 'int',
+ 'decim-amt': 'int',
+ 'wireshark-host': 'str',
+ 'gain-mu': 'float',
+ 'phase2-tdma': 'bool',
+ 'seek': 'int',
+ 'ifile': 'str',
+ 'pause': 'bool',
+ 'antenna': 'str',
+ 'calibration': 'float',
+ 'fine-tune': 'float',
+ 'raw-symbols': 'str',
+ 'audio-output': 'str',
+ 'vocoder': 'bool',
+ 'input': 'str',
+ 'wireshark': 'bool',
+ 'gains': 'str',
+ 'args': 'str',
+ 'sample-rate': 'int',
+ 'terminal-type': 'str',
+ 'gain': 'float',
+ 'excess-bw': 'float',
+ 'offset': 'float',
+ 'audio-input': 'str',
+ 'audio': 'bool',
+ 'plot-mode': 'str',
+ 'audio-if': 'bool',
+ 'tone-detect': 'bool',
+ 'frequency': 'int',
+ 'freq-corr': 'float',
+ 'hamlib-model': 'int',
+ 'udp-player': 'bool',
+ 'verbosity': 'int',
+ 'audio-gain': 'float',
+ 'freq-error-tracking': 'bool',
+ 'nocrypt': 'bool',
+ 'wireshark-port': 'int'
+ }
+ self.backend = '%s/%s' % (os.getcwd(), 'rx.py')
+ opts = [py_exe, self.backend]
+ for k in [ x for x in dir(options) if not x.startswith('_') ]:
+ kw = k.replace('_', '-')
+ val = getattr(options, k)
+ if kw not in types.keys():
+ self.msg = 'make_command: unknown option: %s %s type %s' % (k, val, type(val))
+ return None
+ elif types[kw] == 'str':
+ if val:
+ opts.append('--%s' % kw)
+ opts.append('%s' % (val))
+ elif types[kw] == 'float':
+ opts.append('--%s' % kw)
+ if val:
+ opts.append('%f' % (val))
+ else:
+ opts.append('%f' % (0))
+ elif types[kw] == 'int':
+ opts.append('--%s' % kw)
+ if val:
+ opts.append('%d' % (val))
+ else:
+ opts.append('%d' % (0))
+ elif types[kw] == 'bool':
+ if val:
+ opts.append('--%s' % kw)
+ else:
+ self.msg = 'make_command: unknown2 option: %s %s type %s' % (k, val, type(val))
+ return None
+ return opts
+
+ msg = json.loads(msg.to_string())
+ if msg['command'] == 'rx-start':
+ if self.check_subproc():
+ self.msg = 'start command failed: subprocess pid %d already active' % self.subproc.pid
+ return
+ options = rx_options(msg['data'])
+ if getattr(options, '_js_config', None) is None:
+ self.msg = 'start command failed: rx_options: unable to initialize config=%s' % (msg['data'])
+ return
+ options.verbosity = self.verbosity
+ options.terminal_type = 'zmq:tcp:%d' % (self.zmq_port)
+ cmd = make_command(options, msg['data'])
+ sys.stderr.write('executing %s\n' % (' '.join(cmd)))
+ if cmd:
+ self.subproc = subprocess.Popen(cmd)
+ elif msg['command'] == 'rx-stop':
+ if not self.check_subproc():
+ self.msg = 'stop command failed: subprocess not active'
+ return
+ if msg['data'] == 'kill':
+ self.subproc.kill()
+ else:
+ self.subproc.terminate()
+ elif msg['command'] == 'rx-state':
+ d = {}
+ if self.check_subproc():
+ d['rx-state'] = 'subprocess pid %d active' % self.subproc.pid
+ else:
+ d['rx-state'] = 'subprocess not active, last msg: %s' % self.msg
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ if not self.output_q.full_p():
+ self.output_q.insert_tail(msg)
+
+ def run(self):
+ while self.keep_running:
+ js = self.zmq_sub.recv()
+ if not self.keep_running:
+ break
+ js = ensure_str(js)
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ if not self.output_q.full_p():
+ self.output_q.insert_tail(msg)
+
+class rx_options(object):
+ def __init__(self, name):
+ def map_name(k):
+ return k.replace('-', '_')
+
+ filename = '%s%s.json' % (CFG_DIR, name)
+ if not os.access(filename, os.R_OK):
+ sys.stderr.write('unable to access config file %s\n' % (filename))
+ return
+ config = byteify(json.loads(open(filename).read()))
+ dev = [x for x in config['devices'] if x['active']][0]
+ if not dev:
+ return
+ chan = [x for x in config['channels'] if x['active']][0]
+ if not chan:
+ return
+ options = object()
+ for k in config['backend-rx'].keys():
+ setattr(self, map_name(k), config['backend-rx'][k])
+ for k in 'args frequency gains offset'.split():
+ setattr(self, k, dev[k])
+ self.demod_type = chan['demod_type']
+ self.freq_corr = dev['ppm']
+ self.sample_rate = dev['rate']
+ self.plot_mode = chan['plot']
+ self.phase2_tdma = chan['phase2_tdma']
+ self.trunk_conf_file = filename
+ self._js_config = config
+
+def http_main():
+ global my_backend
+ # command line argument parsing
+ parser = OptionParser()
+ parser.add_option("-c", "--config", type="string", default=None, help="config json name, without prefix/suffix")
+ parser.add_option("-e", "--endpoint", type="string", default="127.0.0.1:8080", help="address:port to listen on (use addr 0.0.0.0 to enable external clients)")
+ parser.add_option("-v", "--verbosity", type="int", default=0, help="message debug level")
+ parser.add_option("-p", "--pause", action="store_true", default=False, help="block on startup")
+ parser.add_option("-z", "--zmq-port", type="int", default=25000, help="backend sub port")
+ (options, args) = parser.parse_args()
+
+ # wait for gdb
+ if options.pause:
+ print ('Ready for GDB to attach (pid = %d)' % (os.getpid(),))
+ raw_input("Press 'Enter' to continue...")
+
+ input_q = gr.msg_queue(20)
+ output_q = gr.msg_queue(20)
+ backend_input_q = gr.msg_queue(20)
+ backend_output_q = gr.msg_queue(20)
+
+ my_backend = Backend(options, backend_input_q, backend_output_q, init_config=options.config)
+ server = http_server(input_q, output_q, options.endpoint)
+ q_watcher = queue_watcher(output_q, lambda msg : my_backend.publish(msg))
+ backend_q_watcher = queue_watcher(backend_output_q, lambda msg : process_qmsg(msg))
+
+ server.run()
+
+if __name__ == '__main__':
+ http_main()
diff --git a/op25/gr-op25_repeater/apps/install-sql.sh b/op25/gr-op25_repeater/apps/install-sql.sh
new file mode 100755
index 0000000..aa5c94d
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/install-sql.sh
@@ -0,0 +1,31 @@
+#! /bin/sh
+
+PIP3=`which pip3`
+USERDIR=~/.local/bin
+
+sudo apt-get install python3-pip
+
+# PIP3=`which pip3`
+PIP3=/usr/bin/pip3
+
+# # # # # # un-comment the following two lines for ubuntu 16.04 # # # # # #
+#pip3 install --user pip==10.0.1
+#PIP3=$USERDIR/pip3
+
+echo PIP3 now set to $PIP3
+# # # $PIP3 --version # # # generates errors -- (?)
+
+$PIP3 install --user sqlalchemy
+$PIP3 install --user flask
+$PIP3 install --user datatables
+$PIP3 install --user flask-sqlalchemy
+
+cd
+git clone https://github.com/Pegase745/sqlalchemy-datatables.git
+cd sqlalchemy-datatables
+$PIP3 install --user .
+cd
+
+echo the following line must be added to your .bashrc
+echo "export PATH=$USERDIR:\$PATH"
+
diff --git a/op25/gr-op25_repeater/apps/log_ts.py b/op25/gr-op25_repeater/apps/log_ts.py
new file mode 100755
index 0000000..5306d49
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/log_ts.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python
+
+# Copyright 2020 Graham Norbury
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+# Modify TS_FORMAT to control logger timestamp format
+# 0 = legacy epoch seconds
+# 1 = formatted mm/dd/yy hh:mm:ss.usec
+TS_FORMAT = 1
+
+import time
+class log_ts(object):
+ @staticmethod
+ def get(supplied_ts=None):
+ if supplied_ts is None:
+ ts = time.time()
+ else:
+ ts = supplied_ts
+
+ if TS_FORMAT == 0:
+ formatted_ts = "{:.6f}".format(ts)
+ else:
+ formatted_ts = "{:s}{:s}".format(time.strftime("%m/%d/%y %H:%M:%S",time.localtime(ts)),"{:.6f}".format(ts - int(ts)).lstrip("0"))
+
+ return formatted_ts
+
diff --git a/op25/gr-op25_repeater/apps/multi_rx.py b/op25/gr-op25_repeater/apps/multi_rx.py
new file mode 100755
index 0000000..6ae3456
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/multi_rx.py
@@ -0,0 +1,864 @@
+#!/usr/bin/env python3
+
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import os
+import sys
+import threading
+import time
+import json
+import select
+import traceback
+import osmosdr
+
+from gnuradio import audio, eng_notation, gr, filter, blocks, fft, analog, digital
+from gnuradio.eng_option import eng_option
+from math import pi
+from optparse import OptionParser
+
+import trunking
+
+import op25
+import op25_repeater
+import p25_demodulator
+import p25_decoder
+from sockaudio import audio_thread
+
+from sql_dbi import sql_dbi
+
+from gr_gnuplot import constellation_sink_c
+from gr_gnuplot import fft_sink_c
+from gr_gnuplot import mixer_sink_c
+from gr_gnuplot import symbol_sink_f
+from gr_gnuplot import eye_sink_f
+from gr_gnuplot import setup_correlation
+from gr_gnuplot import sync_plot
+from gr_gnuplot import cpm_sink_c
+
+from nxdn_trunking import cac_message
+
+from terminal import op25_terminal
+
+sys.path.append('tdma')
+import lfsr
+
+os.environ['IMBE'] = 'soft'
+
+_def_symbol_rate = 4800
+_def_interval = 3.0 # sec
+_def_file_dir = '../www/images'
+_def_audio_port = 23456 # udp port for audio thread
+_def_audio_output = 'default' # output device name for audio thread
+
+# The P25 receiver
+#
+
+def byteify(input): # thx so
+ if sys.version[0] != '2': # hack, must be a better way
+ return input
+ if isinstance(input, dict):
+ return {byteify(key): byteify(value)
+ for key, value in input.iteritems()}
+ elif isinstance(input, list):
+ return [byteify(element) for element in input]
+ elif isinstance(input, unicode):
+ return input.encode('utf-8')
+ else:
+ return input
+
+class device(object):
+ def __init__(self, config, tb):
+ self.name = config['name']
+ self.sample_rate = config['rate']
+ self.args = config['args']
+ self.tunable = config['tunable']
+ self.tb = tb
+ self.frequency = 0
+
+ if config['args'].startswith('audio-if:'):
+ self.init_audio_if(config)
+ elif config['args'].startswith('audio:'):
+ self.init_audio(config)
+ elif config['args'].startswith('file:'):
+ self.init_file(config)
+ elif config['args'].startswith('udp:'):
+ self.init_udp(config)
+ else:
+ self.init_osmosdr(config)
+
+ def init_file(self, config):
+ filename = config['args'].replace('file:', '', 1)
+ src = blocks.file_source(gr.sizeof_gr_complex, filename, repeat = False)
+ throttle = blocks.throttle(gr.sizeof_gr_complex, config['rate'])
+ self.tb.connect(src, throttle)
+ self.src = throttle
+ self.frequency = config['frequency']
+ self.offset = config['offset']
+
+ def init_audio_if(self, config):
+ filename = config['args'].replace('audio-if:', '')
+ self.audio_source = audio.source(config['rate'], filename)
+ self.null_source = blocks.null_source (gr.sizeof_float)
+ self.audio_cvt = blocks.float_to_complex()
+ self.tb.connect(self.audio_source, (self.audio_cvt, 0))
+ self.tb.connect(self.null_source, (self.audio_cvt, 1))
+ self.src = self.audio_cvt
+ self.frequency = config['frequency']
+ self.offset = config['offset']
+
+ def init_audio(self, config):
+ filename = config['args'].replace('audio:', '')
+ if filename.startswith('file:'):
+ filename = filename.replace('file:', '')
+ repeat = False
+ s2f = blocks.short_to_float()
+ K = 1 / 32767.0
+ src = blocks.multiply_const_ff(K)
+ throttle = blocks.throttle(gr.sizeof_short, self.sample_rate) # may be redundant in stdin case ?
+ if filename == '-':
+ fd = 0 # stdin
+ fsrc = blocks.file_descriptor_source(gr.sizeof_short, fd, repeat)
+ else:
+ fsrc = blocks.file_source(gr.sizeof_short, filename, repeat)
+ self.tb.connect(fsrc, throttle, s2f, src)
+ else:
+ src = audio.source(self.sample_rate, filename)
+ gain = 1.0
+ if config['gains'].startswith('audio:'):
+ gain = float(config['gains'].replace('audio:', ''))
+ self.src = blocks.multiply_const_ff(gain)
+ self.tb.connect(src, self.src)
+
+ def init_udp(self, config):
+ hostinfo = config['args'].split(':')
+ hostname = hostinfo[1]
+ udp_port = int(hostinfo[2])
+ bufsize = 32000 # might try enlarging this if packet loss
+ self.src = blocks.udp_source(gr.sizeof_gr_complex, hostname, udp_port, payload_size = bufsize)
+ self.ppm = 0
+ self.frequency = config['frequency']
+ self.offset = 0
+
+ def init_osmosdr(self, config):
+ speeds = [250000, 1000000, 1024000, 1800000, 1920000, 2000000, 2048000, 2400000, 2560000]
+
+ sys.stderr.write('device: %s\n' % config)
+ if config['args'].startswith('rtl') and config['rate'] not in speeds:
+ sys.stderr.write('WARNING: requested sample rate %d for device %s may not\n' % (config['rate'], config['name']))
+ sys.stderr.write("be optimal. You may want to use one of the following rates\n")
+ sys.stderr.write('%s\n' % speeds)
+ self.src = osmosdr.source(config['args'])
+
+ for tup in config['gains'].split(','):
+ name, gain = tup.split(':')
+ self.src.set_gain(int(gain), name)
+
+ self.src.set_freq_corr(config['ppm'])
+ self.ppm = config['ppm']
+
+ self.src.set_sample_rate(config['rate'])
+
+ self.src.set_center_freq(config['frequency'])
+ self.frequency = config['frequency']
+
+ self.offset = config['offset']
+
+ def set_frequency(self, frequency):
+ if frequency == self.frequency:
+ return
+ if not self.tunable:
+ return
+ self.frequency = frequency
+ self.src.set_center_freq(frequency)
+
+class channel(object):
+ def __init__(self, config, dev, verbosity, msgq = None, process_msg=None, msgq_id=-1, role=''):
+ sys.stderr.write('channel (dev %s): %s\n' % (dev.name, config))
+ self.device = dev
+ self.name = config['name']
+ self.symbol_rate = _def_symbol_rate
+ self.process_msg = process_msg
+ self.role = role
+ self.dev = ''
+ self.sysid = []
+ self.nac = []
+ if 'symbol_rate' in config.keys():
+ self.symbol_rate = config['symbol_rate']
+ self.config = config
+ self.verbosity = verbosity
+ self.frequency = config['frequency'] if self.device.args.startswith('audio-if') else 0
+ self.tdma_state = False
+ self.xor_cache = {}
+
+ self.tuning_error = 0
+ self.freq_correction = 0
+ self.error_band = 0
+ self.last_error_update = 0
+ self.last_set_freq_at = time.time()
+ self.warned_frequencies = {}
+ self.msgq_id = msgq_id
+ self.next_band_change = time.time()
+
+ self.audio_port = _def_audio_port
+ self.audio_output = _def_audio_output
+ self.audio_gain = 1.0
+ if 'audio_gain' in config:
+ self.audio_gain = float(config['audio_gain'])
+
+ if dev.args.startswith('audio:'):
+ self.demod = p25_demodulator.p25_demod_fb(
+ input_rate = dev.sample_rate,
+ filter_type = config['filter_type'],
+ if_rate = config['if_rate'],
+ symbol_rate = self.symbol_rate)
+ else:
+ self.demod = p25_demodulator.p25_demod_cb(
+ input_rate = dev.sample_rate,
+ demod_type = config['demod_type'],
+ filter_type = config['filter_type'],
+ excess_bw = config['excess_bw'],
+ relative_freq = dev.frequency + dev.offset - config['frequency'],
+ offset = dev.offset,
+ if_rate = config['if_rate'],
+ symbol_rate = self.symbol_rate,
+ use_old_decim = True if self.device.args.startswith('audio-if') else False)
+ if msgq is not None:
+ q = msgq
+ else:
+ q = gr.msg_queue(20)
+ if 'decode' in config.keys() and config['decode'].startswith('p25_decoder'):
+ num_ambe = 1
+ (proto, wireshark_host, udp_port) = config['destination'].split(':')
+ assert proto == 'udp'
+ wireshark_host = wireshark_host.replace('/', '')
+ udp_port = int(udp_port)
+ if role == 'vc':
+ self.audio_port = udp_port
+ if 'audio_output' in config.keys():
+ self.audio_output = config['audio_output']
+
+ self.decoder = p25_decoder.p25_decoder_sink_b(dest='audio', do_imbe=True, num_ambe=num_ambe, wireshark_host=wireshark_host, udp_port=udp_port, do_msgq = True, msgq=q, audio_output=self.audio_output, debug=verbosity, msgq_id=self.msgq_id)
+ else:
+ self.decoder = op25_repeater.frame_assembler(config['destination'], verbosity, q, self.msgq_id)
+
+ if self.symbol_rate == 6000 and role == 'cc':
+ sps = config['if_rate'] // self.symbol_rate
+ self.demod.set_symbol_rate(self.symbol_rate) # this and the foll. call should be merged?
+ self.demod.clock.set_omega(float(sps))
+ self.demod.clock.set_tdma(True)
+ sys.stderr.write('initializing TDMA control channel %s channel ID %d\n' % (self.name, self.msgq_id))
+
+ if self.process_msg is not None and msgq is None:
+ self.q_watcher = du_queue_watcher(q, lambda msg: self.process_msg(msg, sender=self))
+
+ self.kill_sink = []
+
+ if 'blacklist' in config.keys():
+ for g in config['blacklist'].split(','):
+ self.decoder.insert_blacklist(int(g))
+
+ if 'whitelist' in config.keys():
+ for g in config['whitelist'].split(','):
+ self.decoder.insert_whitelist(int(g))
+
+ self.sinks = []
+ if 'plot' not in config.keys():
+ return
+
+ for plot in config['plot'].split(','):
+ if plot == 'datascope':
+ assert config['demod_type'] == 'fsk4' ## datascope plot requires fsk4 demod type
+ sink = eye_sink_f(sps=config['if_rate'] // self.symbol_rate)
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_bb('symbol_filter', sink)
+ self.kill_sink.append(sink)
+ elif plot.startswith('cpm'):
+ if self.symbol_rate != 6000: # fixed rate value for p25p2
+ sys.stderr.write('warning: symbol rate %d may be incorrect for CPM channel %s\n' % (self.symbol_rate, self.name))
+ sink = cpm_sink_c(sps=config['if_rate'] // self.symbol_rate, plot_mode=plot)
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_complex('if_out', sink)
+ self.kill_sink.append(sink)
+ elif plot == 'symbol':
+ sink = symbol_sink_f()
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_float(sink)
+ self.kill_sink.append(sink)
+ elif plot == 'fft':
+ i = len(self.sinks)
+ sink = fft_sink_c()
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_complex('src', self.sinks[i])
+ self.kill_sink.append(self.sinks[i])
+ elif plot == 'mixer':
+ if config['demod_type'] == 'cqpsk':
+ blk = 'mixer'
+ else:
+ blk = 'cutoff'
+ i = len(self.sinks)
+ sink = mixer_sink_c()
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_complex(blk, self.sinks[i])
+ self.kill_sink.append(self.sinks[i])
+ elif plot == 'constellation':
+ i = len(self.sinks)
+ assert config['demod_type'] == 'cqpsk' ## constellation plot requires cqpsk demod type
+ sink = constellation_sink_c()
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.demod.connect_complex('diffdec', self.sinks[i])
+ self.kill_sink.append(self.sinks[i])
+ elif plot == 'correlation':
+ assert config['demod_type'] == 'fsk4' ## correlation plot requires fsk4 demod type
+ assert config['symbol_rate'] == 4800 ## 4800 required for correlation plot
+ sps=config['if_rate'] // self.symbol_rate
+ sinks = setup_correlation(sps, self.name, self.demod.connect_bb)
+ self.kill_sink += sinks
+ self.sinks += sinks
+ elif plot == 'sync':
+ assert config['demod_type'] == 'cqpsk' ## sync plot requires cqpsk demod type
+ i = len(self.sinks)
+ sink = sync_plot(block = self.demod.clock)
+ sink.set_title(self.name)
+ self.sinks.append(sink)
+ self.kill_sink.append(self.sinks[i])
+ # does not issue self.connect()
+ else:
+ sys.stderr.write('unrecognized plot type %s\n' % plot)
+ return
+
+ def set_frequency(self, frequency):
+ assert frequency
+ if self.device.tunable:
+ self.device.set_frequency(frequency)
+ f = self.frequency if self.device.args.startswith('audio-if') else frequency
+ relative_freq = self.device.frequency + self.device.offset + self.tuning_error - f
+ if (not self.device.tunable) and (not self.device.args.startswith('audio-if')) and abs(relative_freq) > ((self.demod.input_rate / 2) - (self.demod.if1 / 2)):
+ if frequency not in self.warned_frequencies:
+ sys.stderr.write('warning: set frequency %f to non-tunable device %s rejected.\n' % (frequency / 1000000.0, self.device.name))
+ self.warned_frequencies[frequency] = 0
+ self.warned_frequencies[frequency] += 1
+ #print 'set_relative_frequency: error, relative frequency %d exceeds limit %d' % (relative_freq, self.demod.input_rate/2)
+ return False
+ self.demod.set_relative_frequency(relative_freq)
+ self.last_set_freq_at = time.time()
+ if not self.device.args.startswith('audio-if'):
+ self.frequency = frequency
+
+ def error_tracking(self, last_change_freq):
+ curr_time = time.time()
+ if self.config['demod_type'] == 'fsk4':
+ return None # todo: allow tracking in fsk4 demod
+ UPDATE_TIME = 3
+ if self.last_error_update + UPDATE_TIME > curr_time:
+ return None
+ self.last_error_update = time.time()
+ if not self.demod.is_muted():
+ band = self.demod.get_error_band()
+ freq_error = self.demod.get_freq_error()
+ if band and curr_time >= self.next_band_change:
+ self.next_band_change = curr_time + 20.0
+ self.error_band += band
+ sys.stderr.write('channel %d set error band %d\n' % (self.msgq_id, self.error_band))
+ self.freq_correction += freq_error * 0.15
+ self.freq_correction = int(self.freq_correction)
+ if self.freq_correction > 600:
+ self.freq_correction -= 1200
+ self.error_band += 1
+ elif self.freq_correction < -600:
+ self.freq_correction += 1200
+ self.error_band -= 1
+ self.error_band = min(self.error_band, 2)
+ self.error_band = max(self.error_band, -2)
+ self.tuning_error = int(self.error_band * 1200 + self.freq_correction)
+ e = 0
+ if last_change_freq > 0:
+ e = (self.tuning_error*1e6) / float(last_change_freq)
+ else:
+ e = 0
+ freq_error = 0
+ band = 0
+ ### self.set_frequency(self.frequency) # adjust relative frequency with updated tuning_error
+ if self.verbosity >= 10:
+ sys.stderr.write('%f\terror_tracking\t%s\t%d\t%d\t%d\t%d\t%d\t%f\n' % (curr_time, self.name, self.msgq_id, freq_error, self.error_band, self.tuning_error, self.freq_correction, e))
+ d = {'time': time.time(), 'json_type': 'freq_error_tracking', 'name': self.name, 'device': self.device.name, 'freq_error': freq_error, 'band': band, 'error_band': self.error_band, 'tuning_error': self.tuning_error, 'freq_correction': self.freq_correction}
+ if self.frequency:
+ self.set_frequency(self.frequency)
+ return d
+
+ def configure_tdma(self, params):
+ set_tdma = False
+ if params['tdma'] is not None:
+ set_tdma = True
+ self.decoder.set_slotid(params['tdma'])
+ self.demod.clock.set_tdma(set_tdma)
+ if set_tdma == self.tdma_state:
+ return # already in desired state
+ self.tdma_state = set_tdma
+ if set_tdma:
+ hash = '%x%x%x' % (params['nac'], params['sysid'], params['wacn'])
+ if hash not in self.xor_cache:
+ self.xor_cache[hash] = lfsr.p25p2_lfsr(params['nac'], params['sysid'], params['wacn']).xor_chars
+ self.decoder.set_xormask(self.xor_cache[hash], hash)
+ self.decoder.set_nac(params['nac'])
+ rate = 6000
+ else:
+ rate = 4800
+ sps = self.config['if_rate'] / rate
+ self.demod.set_symbol_rate(rate) # this and the foll. call should be merged?
+ self.demod.clock.set_omega(float(sps))
+
+class du_queue_watcher(threading.Thread):
+ def __init__(self, msgq, callback, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.msgq = msgq
+ self.callback = callback
+ self.keep_running = True
+ self.start()
+
+ def run(self):
+ while(self.keep_running):
+ msg = self.msgq.delete_head()
+ if not self.keep_running:
+ break
+ self.callback(msg)
+
+class rx_block (gr.top_block):
+
+ # Initialize the receiver
+ #
+ def __init__(self, verbosity, config, trunk_conf_file=None, terminal_type=None, track_errors=False, udp_player=None):
+ self.verbosity = verbosity
+ gr.top_block.__init__(self)
+ self.device_id_by_name = {}
+ self.msg_types = {}
+ self.terminal_type = terminal_type
+ self.last_process_update = 0
+ self.last_freq_params = {'freq' : 0.0, 'tgid' : None, 'tag' : "", 'tdma' : None}
+ self.trunk_rx = None
+ self.track_errors = track_errors
+ self.last_change_freq = 0
+ self.sql_db = sql_dbi()
+ self.input_q = gr.msg_queue(20)
+ self.output_q = gr.msg_queue(20)
+ self.last_voice_channel_id = 0
+ self.terminal = op25_terminal(self.input_q, self.output_q, terminal_type)
+ self.configure_devices(config['devices'])
+ self.configure_channels(config['channels'])
+ if trunk_conf_file:
+ self.trunk_rx = trunking.rx_ctl(frequency_set = self.change_freq, debug = self.verbosity, conf_file = trunk_conf_file, logfile_workers=[], send_event=self.send_event)
+ self.sinks = []
+ for chan in self.channels:
+ if len(chan.sinks):
+ self.sinks += chan.sinks
+ if self.is_http_term():
+ for sink in self.sinks:
+ sink.gnuplot.set_interval(_def_interval)
+ sink.gnuplot.set_output_dir(_def_file_dir)
+
+ if udp_player:
+ chan = self.find_audio_channel() # find chan used for audio
+ self.audio = audio_thread("127.0.0.1", chan.audio_port, chan.audio_output, False, chan.audio_gain)
+ else:
+ self.audio = None
+
+ def find_channel_uplink(self, params):
+ channels = []
+ for chan in self.channels:
+ if chan.role != 'uplink':
+ continue
+ channels.append(chan)
+ if self.verbosity > 0:
+ sys.stderr.write('%f find_channel_uplink: selected channel %d (%s) for tuning request type %s frequency %f\n' % (time.time(), chan.msgq_id, chan.name, 'vc', params['uplink'] / 1000000.0))
+ return channels
+
+ def find_channel_cc(self, params):
+ channels = []
+ for chan in self.channels:
+ if chan.role != 'cc':
+ continue
+ if len(chan.nac) and params['nac'] not in chan.nac:
+ continue
+ if len(chan.sysid) and params['sysid'] not in chan.sysid:
+ continue
+ channels.append(chan)
+ if self.verbosity > 0:
+ sys.stderr.write('%f find_channel_cc: selected channel %d (%s) for tuning request type %s frequency %f\n' % (time.time(), chan.msgq_id, chan.name, 'cc', params['freq'] / 1000000.0))
+ return channels
+
+ def find_channel_vc(self, params):
+ channels = []
+ for chan in self.channels: # pass1 - search for vc on non-tunable dev having frequency within band
+ if chan.role != 'vc':
+ continue
+ if chan.device.tunable:
+ continue
+ if abs(params['freq'] - chan.device.frequency) >= chan.demod.relative_limit:
+ #sys.stderr.write('%f skipping channel %d frequency %f dev freq %f limit %f\n' % (time.time(), chan.msgq_id, params['freq'] / 1000000.0, chan.device.frequency / 1000000.0, chan.demod.relative_limit / 1000000.0))
+ continue
+ channels.append(chan)
+ if self.verbosity > 0:
+ sys.stderr.write('%f find_channel_vc: selected channel %d (%s) for tuning request type %s frequency %f (1)\n' % (time.time(), chan.msgq_id, chan.name, 'vc', params['freq'] / 1000000.0))
+ return channels
+ for chan in self.channels: # pass2 - search for vc on tunable dev
+ if chan.role != 'vc':
+ continue
+ if not chan.device.tunable:
+ continue
+ channels.append(chan)
+ if self.verbosity > 0:
+ sys.stderr.write('%f find_channel_vc: selected channel %d (%s) for tuning request type %s frequency %f (2)\n' % (time.time(), chan.msgq_id, chan.name, 'vc', params['freq'] / 1000000.0))
+ return channels
+ return [] # pass 1 and 2 failed
+
+ def do_error_tracking(self):
+ if not self.track_errors:
+ return
+ for chan in self.channels:
+ d = chan.error_tracking(self.last_change_freq)
+ if d is not None and not self.input_q.full_p():
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def change_freq(self, params):
+ self.last_freq_params = params
+ freq = params['freq']
+ self.last_change_freq = freq
+ channel_type = params['channel_type'] # vc or cc
+ self.uplink_change_freq(params)
+ if channel_type == 'vc':
+ channels = self.find_channel_vc(params)
+ elif channel_type == 'cc':
+ channels = self.find_channel_cc(params)
+ else:
+ raise ValueError('change_freq: invalid channel_type: %s' % channel_type)
+ if len(channels) == 0:
+ sys.stderr.write('change_freq: no channel(s) found for %s frequency %f\n' % (channel_type, freq/1000000.0))
+ return
+ for chan in channels:
+ chan.device.set_frequency(freq)
+ chan.set_frequency(freq)
+ chan.configure_tdma(params)
+ self.freq_update()
+ if channel_type == 'vc':
+ self.last_voice_channel_id = chan.msgq_id
+ #return
+ if self.trunk_rx is None:
+ return
+ voice_chans = [chan for chan in self.channels if chan.role == 'vc']
+ voice_state = channel_type == 'vc'
+ # FIXME: fsk4 case needs work/testing
+ for chan in voice_chans:
+ if voice_state and chan.msgq_id == self.last_voice_channel_id:
+ chan.demod.set_muted(False)
+ else:
+ chan.demod.set_muted(True)
+
+ def uplink_change_freq(self, params):
+ channel_type = params['channel_type'] # vc or cc
+ if 'uplink' not in params:
+ return
+ if channel_type != 'vc':
+ return
+ uplink = params['uplink']
+ channels = self.find_channel_uplink(params)
+ for chan in channels:
+ chan.device.set_frequency(uplink)
+ chan.set_frequency(uplink)
+ chan.configure_tdma(params)
+ if self.verbosity > 0:
+ sys.stderr.write('set uplink frequency %f, channel %s\n' % (uplink / 1000000.0, chan.name))
+
+ def is_http_term(self):
+ if self.terminal_type.startswith('http:'):
+ return True
+ else:
+ return False
+
+ def process_terminal_msg(self, msg):
+ # return true = end top block
+ RX_COMMANDS = 'skip lockout hold'.split()
+ s = msg.to_string()
+ t = msg.type()
+ if t == -4:
+ d = json.loads(s)
+ s = d['command']
+ if type(s) is not str and isinstance(s, bytes):
+ # should only get here if python3
+ s = s.decode()
+ if s == 'quit': return True
+ elif s == 'update': ## deprecated here: to be removed
+ pass
+ # self.process_update()
+ elif s == 'set_freq':
+ sys.stderr.write('set_freq not supported\n')
+ return
+ #freq = msg.arg1()
+ #self.last_freq_params['freq'] = freq
+ #self.set_freq(freq)
+ elif s == 'adj_tune':
+ freq = msg.arg1()
+ elif s == 'dump_tgids':
+ self.trunk_rx.dump_tgids()
+ elif s == 'reload_tags':
+ nac = msg.arg1()
+ self.trunk_rx.reload_tags(int(nac))
+ elif s == 'add_default_config':
+ nac = msg.arg1()
+ self.trunk_rx.add_default_config(int(nac))
+ elif s in RX_COMMANDS:
+ if self.trunk_rx is not None:
+ self.trunk_rx.process_qmsg(msg)
+ elif s == 'settings-enable' and self.trunk_rx is not None:
+ self.trunk_rx.enable_status(d['data'])
+ return False
+
+ def process_ajax(self):
+ if not self.is_http_term():
+ return
+ if self.input_q.full_p():
+ return
+ filenames = [sink.gnuplot.filename for sink in self.sinks if sink.gnuplot.filename]
+ error = []
+ for chan in self.channels:
+ if hasattr(chan.demod, 'get_freq_error'):
+ error.append(chan.demod.get_freq_error())
+ d = {'json_type': 'rx_update', 'error': error, 'files': filenames, 'time': time.time()}
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def process_update(self):
+ UPDATE_INTERVAL = 1.0 # sec.
+ now = time.time()
+ if now < self.last_process_update + UPDATE_INTERVAL:
+ return
+ self.last_process_update = now
+ self.freq_update()
+ if self.input_q.full_p():
+ return
+ if self.trunk_rx is None:
+ return ## possible race cond - just ignore
+ js = self.trunk_rx.to_json()
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ self.input_q.insert_tail(msg)
+ self.process_ajax()
+
+ def send_event(self, d): ## called from trunking module to send json msgs / updates to client
+ if d is not None:
+ self.sql_db.event(d)
+ if d and not self.input_q.full_p():
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+ self.process_update()
+
+ def freq_update(self):
+ if self.input_q.full_p():
+ return
+ params = self.last_freq_params
+ params['json_type'] = 'change_freq'
+ params['current_time'] = time.time()
+ js = json.dumps(params)
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def process_msg(self, msg):
+ mtype = msg.type()
+ if mtype == -2 or mtype == -4:
+ self.process_terminal_msg(msg)
+ else:
+ self.process_channel_msg(msg, mtype)
+
+ def process_channel_msg(self, msg, mtype):
+ msgtext = msg.to_string()
+ aa55 = trunking.get_ordinals(msgtext[:2])
+ assert aa55 == 0xaa55
+ msgq_id = trunking.get_ordinals(msgtext[2:4])
+ msgtext = msgtext[4:]
+ if mtype == -5:
+ self.process_nxdn_msg(msgtext)
+ else:
+ self.process_trunked_qmsg(msg, msgq_id)
+
+ def process_nxdn_msg(self, s):
+ if isinstance(s[0], str): # for python 2/3
+ s = [ord(x) for x in s]
+ msgtype = chr(s[0])
+ lich = s[1]
+ if self.verbosity > 2:
+ sys.stderr.write ('process_nxdn_msg %s lich %x\n' % (msgtype, lich))
+ if msgtype == 'c': # CAC type
+ ran = s[2] & 0x3f
+ msg = cac_message(s[2:])
+ if msg['msg_type'] == 'CCH_INFO' and self.verbosity:
+ sys.stderr.write ('%-10s %-10s system %d site %d ran %d\n' % (msg['cc1']/1e6, msg['cc2']/1e6, msg['location_id']['system'], msg['location_id']['site'], ran))
+ if self.verbosity > 1:
+ sys.stderr.write('%s\n' % json.dumps(msg))
+
+ def filtered(self, msg, msgq_id):
+ # return True if msg should be suppressed
+ chan = self.channels[msgq_id-1]
+ t = msg.type()
+ if chan.role == 'vc' and t in [7, 12]: ## suppress tsbk/mbt/pdu received over vc
+ return True
+ if chan.role == 'uplink' and t in [-1, 7, 12]: ## suppress as above and also timeout
+ return True
+ return False
+
+ def process_trunked_qmsg(self, msg, msgq_id): # p25 trunked message
+ if self.trunk_rx is None:
+ return
+ if self.filtered(msg, msgq_id):
+ return
+ self.trunk_rx.process_qmsg(msg)
+ self.trunk_rx.parallel_hunt_cc()
+ self.do_error_tracking()
+
+ def configure_devices(self, config):
+ self.devices = []
+ for cfg in config:
+ self.device_id_by_name[cfg['name']] = len(self.devices)
+ self.devices.append(device(cfg, self))
+
+ def find_trunked_device(self, chan, requested_dev):
+ if len(self.devices) == 1: # single SDR
+ return self.devices[0]
+ for dev in self.devices:
+ if dev.name == requested_dev:
+ return dev
+ return None
+
+ def find_device(self, chan, requested_dev):
+ if 'decode' in chan.keys() and chan['decode'].startswith('p25_decoder'):
+ return self.find_trunked_device(chan, requested_dev)
+ for dev in self.devices:
+ if dev.args.startswith('audio:') and chan['demod_type'] == 'fsk4':
+ return dev
+ d = abs(chan['frequency'] - dev.frequency)
+ nf = dev.sample_rate // 2
+ if d + 6250 <= nf:
+ return dev
+ return None
+
+ def configure_channels(self, config):
+ self.channels = []
+ for cfg in config:
+ decode_d = {'role': '', 'dev': ''}
+ if 'decode' in cfg.keys() and cfg['decode'].startswith('p25_decoder'):
+ decode_p = cfg['decode'].split(':')[1:]
+ for p in decode_p: # possible keys: dev, role, nac, sysid; valid roles: cc vc
+ (k, v) = p.split('=')
+ if k == 'nac' or k == 'sysid':
+ v = [int(x, base=0) for x in v.split(',')]
+ decode_d[k] = v
+ dev = self.find_device(cfg, decode_d['dev'])
+ if dev is None:
+ sys.stderr.write('* * * No device found for channel %s- ignoring!\n' % cfg['name'])
+ continue
+ msgq_id = len(self.channels) + 1
+ chan = channel(cfg, dev, self.verbosity, msgq=self.output_q, msgq_id = msgq_id, role=decode_d['role'])
+ for k in decode_d.keys():
+ setattr(chan, k, decode_d[k])
+ self.channels.append(chan)
+ self.connect(dev.src, chan.demod, chan.decoder)
+ sys.stderr.write('assigning channel "%s" (channel id %d) to device "%s"\n' % (chan.name, chan.msgq_id, dev.name))
+ if 'log_if' in cfg.keys():
+ chan.logfile_if = blocks.file_sink(gr.sizeof_gr_complex, 'if-%d-%s' % (chan.config['if_rate'], cfg['log_if']))
+ if cfg['demod_type'] == 'cqpsk':
+ chan.demod.connect_complex('agc', chan.logfile_if)
+ else:
+ chan.demod.connect_complex('if_out', chan.logfile_if)
+ if 'log_symbols' in cfg.keys():
+ chan.logfile = blocks.file_sink(gr.sizeof_char, cfg['log_symbols'])
+ self.connect(chan.demod, chan.logfile)
+
+ def find_audio_channel(self):
+ for chan in self.channels: # pass1 - look for 'vc'
+ if chan.role == 'vc' and chan.audio_port:
+ return chan
+ for chan in self.channels: # pass2 - any chan with audio port specified
+ if chan.audio_port:
+ return chan
+ return self.channels[0]
+
+ def scan_channels(self):
+ for chan in self.channels:
+ sys.stderr.write('scan %s: error %d\n' % (chan.config['frequency'], chan.demod.get_freq_error()))
+
+class rx_main(object):
+ def __init__(self):
+ self.keep_running = True
+
+ # command line argument parsing
+ parser = OptionParser(option_class=eng_option)
+ parser.add_option("-c", "--config-file", type="string", default=None, help="specify config file name")
+ parser.add_option("-v", "--verbosity", type="int", default=0, help="message debug level")
+ parser.add_option("-p", "--pause", action="store_true", default=False, help="block on startup")
+ parser.add_option("-M", "--monitor-stdin", action="store_false", default=True, help="enable press ENTER to quit")
+ parser.add_option("-T", "--trunk-conf-file", type="string", default=None, help="trunking config file name")
+ parser.add_option("-l", "--terminal-type", type="string", default="curses", help="'curses' or udp port or 'http:host:port'")
+ parser.add_option("-X", "--freq-error-tracking", action="store_true", default=False, help="enable experimental frequency error tracking")
+ parser.add_option("-U", "--udp-player", action="store_true", default=False, help="enable built-in udp audio player")
+ (options, args) = parser.parse_args()
+
+ self.options = options
+
+ # wait for gdb
+ if options.pause:
+ print ('Ready for GDB to attach (pid = %d)' % (os.getpid(),))
+ raw_input("Press 'Enter' to continue...")
+
+ if options.config_file == '-':
+ config = json.loads(sys.stdin.read())
+ else:
+ config = json.loads(open(options.config_file).read())
+ self.tb = rx_block(options.verbosity, config = byteify(config), trunk_conf_file=options.trunk_conf_file, terminal_type=options.terminal_type, track_errors=options.freq_error_tracking, udp_player = options.udp_player)
+ sys.stderr.write('python version detected: %s\n' % sys.version)
+ sys.stderr.flush()
+
+ def run(self):
+ self.tb.start()
+ if self.options.monitor_stdin:
+ print("Running. press ENTER to quit")
+ while self.keep_running:
+ if self.options.monitor_stdin and select.select([sys.stdin,],[],[],0.0)[0]:
+ c = sys.stdin.read(1)
+ self.keep_running = False
+ break
+ msg = self.tb.output_q.delete_head()
+ if self.tb.process_msg(msg):
+ self.keep_running = False
+ break
+ print('Quitting - now stopping top block')
+ self.tb.stop()
+
+if __name__ == "__main__":
+ rx = rx_main()
+ try:
+ rx.run()
+ except KeyboardInterrupt:
+ rx.keep_running = False
+ print('Program ending')
+ time.sleep(1)
diff --git a/op25/gr-op25_repeater/apps/nxdn_trunking.py b/op25/gr-op25_repeater/apps/nxdn_trunking.py
new file mode 100644
index 0000000..b18f98b
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/nxdn_trunking.py
@@ -0,0 +1,316 @@
+#!/usr/bin/env python
+
+#
+# (C) Copyright 2020 Max H. Parke, KA1RBI
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+#
+# nxdn trunking:
+# - CAC decoding
+#
+
+import sys
+import os
+
+sys.path.append('tdma')
+from bit_utils import *
+
+def locid(id):
+ save_id = mk_int(id)
+ cat = mk_int(id[:2])
+ if cat == 0:
+ ssize = 10
+ elif cat == 2:
+ ssize = 14
+ elif cat == 1:
+ ssize = 17
+ else:
+ return {'category': -1, 'system': -1, 'site': -1, 'id': '0x%x' % save_id}
+ id = id[2:]
+ syscode = mk_int(id[:ssize])
+ id = id[ssize:]
+ sitecode = mk_int(id)
+ return {'category': cat, 'system': syscode, 'site': sitecode, 'id': '0x%x' % save_id}
+
+def mk_freq(f):
+ ### todo: UHF currently untested; may fail at 400 MHz
+ return int(f * 1250 + 100000000) # frequency in Hz
+
+def cac_message(s):
+ d = {}
+ bits = []
+ for c in s:
+ for i in range(8):
+ bits.append((c >> (7-i)) & 1)
+ d['structure'] = mk_int(bits[:2])
+ d['ran'] = mk_int(bits[2:8])
+ bits = bits[8:]
+ msg_type = mk_int(bits[2:8])
+ d['msg_typeid'] = msg_type
+ if msg_type == 0x18: # SITE_INFO
+ assert len(bits) == 144
+ d['msg_type'] = 'SITE_INFO'
+ bits = bits[8:]
+ d['location_id'] = locid(bits[:24])
+ bits = bits[24:]
+ d['channel_info'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['service_info'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['restr_info'] = mk_int(bits[:24])
+ bits = bits[24:]
+ d['access_info'] = mk_int(bits[:24])
+ bits = bits[24:]
+ d['version_no'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['adjacent_alloc'] = mk_int(bits[:4])
+ bits = bits[4:]
+ d['cc1'] = mk_int(bits[:10])
+ bits = bits[10:]
+ d['cc2'] = mk_int(bits[:10])
+ elif msg_type == 0x19: # SRV_INFO
+ assert len(bits) >= 72
+ d['msg_type'] = 'SRV_INFO'
+ bits = bits[8:]
+ d['location_id'] = locid(bits[:24])
+ bits = bits[24:]
+ d['service_info'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['restr_info'] = mk_int(bits[:24])
+ elif msg_type == 0x1a: # CCH_INFO
+ assert len(bits) >= 72
+ d['msg_type'] = 'CCH_INFO'
+ bits = bits[8:]
+ d['location_id'] = locid(bits[:24])
+ bits = bits[24:]
+ d['flags1'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['cc1'] = mk_freq(mk_int(bits[:16]))
+ bits = bits[16:]
+ d['cc2'] = mk_freq(mk_int(bits[:16]))
+ elif msg_type == 0x1b: # ADJ_SITE_INFO
+ assert len(bits) >= 72
+ d['msg_type'] = 'ADJ_SITE_INFO'
+ d1 = {}
+ d2 = {}
+ bits = bits[8:]
+ d1['location'] = locid(bits[:24])
+ bits = bits[24:]
+ d1['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d1['cc'] = mk_freq(mk_int(bits[:16]))
+ bits = bits[16:]
+ d2['location'] = locid(bits[:24])
+ bits = bits[24:]
+ d2['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d2['cc'] = mk_freq(mk_int(bits[:16]))
+ bits = bits[16:]
+ d['sites'] = [d1, d2]
+ #d['location_3'] = locid(bits[:24])
+ #bits = bits[24:]
+ #d['option_3'] = mk_int(bits[:6])
+ #bits = bits[6:]
+ #d['cc_3'] = mk_int(bits[:10])
+ elif msg_type == 0x01: # VCALL_RESP
+ assert len(bits) >= 64
+ d['msg_type'] = 'VCALL_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ bits = bits[8:]
+ elif msg_type == 0x09: # DCALL_RESP
+ assert len(bits) >= 64
+ d['msg_type'] = 'DCALL_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ bits = bits[8:]
+ elif msg_type == 0x04: # VCALL_ASSGN
+ assert len(bits) >= 72
+ bits2 = bits
+ s = ''
+ while len(bits2):
+ s += '%02x' % mk_int(bits2[:8])
+ bits2 = bits2[8:]
+ d['hexdata'] = s
+ d['msg_type'] = 'VCALL_ASSGN'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['group_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['timer'] = mk_int(bits[:8])
+ d['channel'] = mk_int(bits[6:16])
+ bits = bits[8:]
+ d['f1'] = mk_freq(mk_int(bits[:16]))
+ bits = bits[16:]
+ d['f2'] = mk_freq(mk_int(bits[:16]))
+ elif msg_type == 0x0e: # DCALL_ASSGN
+ assert len(bits) >= 104
+ d['msg_type'] = 'DCALL_ASSGN'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['group_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['timer'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['f1'] = mk_freq(mk_int(bits[:16]))
+ bits = bits[16:]
+ d['f2'] = mk_freq(mk_int(bits[:16]))
+ elif msg_type == 0x20: # REG_RESP
+ assert len(bits) >= 72
+ d['msg_type'] = 'REG_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['location id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['unit_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['group_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['visitor_unit'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['visitor_group'] = mk_int(bits[:16])
+ elif msg_type == 0x22: # REG_C_RESP
+ assert len(bits) >= 56
+ d['msg_type'] = 'REG_C_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['location id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['unit_id'] = mk_int(bits[:16])
+ elif msg_type == 0x24: # GRP_REG_RESP
+ assert len(bits) >= 72
+ d['msg_type'] = 'GRP_REG_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['destination id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['group_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['visitor_group_id'] = mk_int(bits[:16])
+ elif msg_type == 0x32: # STAT_REQ
+ assert len(bits) >= 72
+ d['msg_type'] = 'STAT_REQ'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[8:]
+ d['spare'] = mk_int(bits[:8])
+ status = bits[8:]
+ elif msg_type == 0x33: # STAT_RESP
+ assert len(bits) >= 64
+ d['msg_type'] = 'STAT_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ elif msg_type == 0x38: # SDCALL_REQ_HEADER
+ assert len(bits) >= 64
+ d['msg_type'] = 'SDCALL_REQ_HEADER'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cipher_type'] = mk_int(bits[:2])
+ d['key_id'] = mk_int(bits[2:8])
+ elif msg_type == 0x39: # SDCALL_REQ_USERDATA
+ assert len(bits) >= 64
+ d['msg_type'] = 'SDCALL_REQ_USERDATA'
+ bits = bits[8:]
+ d['packet_frame'] = mk_int(bits[:4])
+ d['block_number'] = mk_int(bits[4:8])
+ bits = bits[8:]
+ s = ''
+ while len(bits):
+ s += '%02x' % mk_int(bits[:8])
+ bits = bits[8:]
+ d['hexdata'] = s
+ elif msg_type == 0x3b: # SDCALL_RESP
+ assert len(bits) >= 64
+ d['msg_type'] = 'SDCALL_RESP'
+ bits = bits[8:]
+ d['option'] = mk_int(bits[:8])
+ bits = bits[8:]
+ d['call_type'] = mk_int(bits[:3])
+ d['call_option'] = mk_int(bits[3:8])
+ bits = bits[8:]
+ d['source id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['destination_id'] = mk_int(bits[:16])
+ bits = bits[16:]
+ d['cause'] = mk_int(bits[:8])
+ bits = bits[8:]
+ else: # msg type unhandled
+ d['msg_type'] = 'UNSUPPORTED 0x%x' % (msg_type)
+ return d
diff --git a/op25/gr-op25_repeater/apps/op25-liq.service b/op25/gr-op25_repeater/apps/op25-liq.service
new file mode 100644
index 0000000..de485b6
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/op25-liq.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=op25-liq
+After=syslog.target network.target nss-lookup.target network-online.target
+Requires=network-online.target
+
+[Service]
+User=1000
+Group=1000
+WorkingDirectory=/home/pi/op25/op25/gr-op25_repeater/apps
+ExecStart=/usr/bin/liquidsoap op25.liq
+RestartSec=5
+Restart=on-failure
+
+[Install]
+WantedBy=multi-user.target
diff --git a/op25/gr-op25_repeater/apps/op25.liq b/op25/gr-op25_repeater/apps/op25.liq
new file mode 100755
index 0000000..b8fc31e
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/op25.liq
@@ -0,0 +1,54 @@
+#!/usr/bin/liquidsoap
+
+# Example liquidsoap streaming from op25 to icecast
+# (c) 2019, 2020 gnorbury@bondcar.com, wllmbecks@gmail.com
+#
+
+set("log.stdout", true)
+set("log.file", false)
+set("log.level", 1)
+
+# Make the native sample rate compatible with op25
+set("frame.audio.samplerate", 8000)
+
+input = mksafe(input.external(buffer=0.02, channels=2, samplerate=8000, restart_on_error=false, "./audio.py -x 2 -s"))
+# Consider increasing the buffer value on slow systems such as RPi3. e.g. buffer=0.25
+# Longer buffer results in less choppy audio but at the expense of increased latency.
+
+
+
+# OPTIONAL AUDIO SIGNAL PROCESSING BLOCKS
+# Uncomment to enable
+#
+# High pass filter
+#input = filter.iir.butterworth.high(frequency = 200.0, order = 4, input)
+
+# Low pass filter
+#input = filter.iir.butterworth.low(frequency = 3250.0, order = 4, input)
+
+# Normalization
+#input = normalize(input, gain_max = 3.0, gain_min = -3.0, target = -16.0, threshold = -40.0)
+
+
+
+# LOCAL AUDIO OUTPUT
+# Uncomment the appropriate line below to enable local sound
+#
+# Default audio subsystem
+out (input)
+#
+# PulseAudio
+#output.pulseaudio(input)
+#
+# ALSA
+#output.alsa(input)
+
+
+
+# ICECAST STREAMING
+# Uncomment to enable output to an icecast server
+# Change the "host", "password", and "mount" strings appropriately first!
+# For metadata to work properly, the host address given here MUST MATCH the address in op25's meta.json file
+#
+#output.icecast(%mp3(bitrate=16, samplerate=22050, stereo=false), description="op25", genre="Public Safety", url="", fallible=false, icy_metadata="false", host="localhost", port=8000, mount="mountpoint", password="hackme", mean(input))
+
diff --git a/op25/gr-op25_repeater/apps/oplog/app.cfg b/op25/gr-op25_repeater/apps/oplog/app.cfg
new file mode 100644
index 0000000..23c026c
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/app.cfg
@@ -0,0 +1,4 @@
+import os
+
+SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/../op25-data.db' % (os.path.dirname(__file__))
+SQLALCHEMY_TRACK_MODIFICATIONS = False
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/__init__.py b/op25/gr-op25_repeater/apps/oplog/op25/__init__.py
new file mode 100644
index 0000000..a0ddf99
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/__init__.py
@@ -0,0 +1,844 @@
+#! /usr/bin/env python
+
+# Copyright 2021 Max H. Parke KA1RBI, Michael Rose
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import time
+from time import sleep
+from time import gmtime, strftime
+import os
+from os import listdir
+from os.path import isfile, join
+import sys
+import traceback
+import math
+import json
+import click
+import datetime
+from datatables import ColumnDT, DataTables
+from flask import Flask, jsonify, render_template, request, redirect, session
+from flask_sqlalchemy import SQLAlchemy
+from sqlalchemy import func, desc, and_, or_, case, delete, insert, update, exc
+from sqlalchemy.orm import Query
+from sqlalchemy.exc import OperationalError
+import sqlalchemy.types as types
+from shutil import copyfile
+
+sys.path.append('..') # for emap
+from emap import oplog_map, cc_events, cc_desc
+
+app = Flask(__name__)
+app.config.from_pyfile("../app.cfg")
+app.config['SQLALCHEMY_ECHO'] = False # set to True to send sql statements to the console
+
+# enables session variables to be used
+app.secret_key = b'kH8HT0ucrh' # random bytes - this key not used anywhere else
+
+db = SQLAlchemy(app)
+# db.init_app(app)
+
+with app.app_context():
+ try:
+ db.reflect()
+ except OperationalError as e:
+ raise(e) # database is locked by another process
+
+class MyDateType(types.TypeDecorator):
+ impl = types.REAL
+ def process_result_value(self, value, dialect):
+ return datetime.datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')
+
+class column_helper(object):
+ # convenience class - enables columns to be referenced as
+ # for example, Foo.bar instead of Foo['bar']
+ def __init__(self, table):
+ self.table_ = db.metadata.tables[table]
+ cols = self.table_.columns
+ for k in cols.keys():
+ setattr(self, k, cols[k])
+
+def dbstate():
+ database = app.config['SQLALCHEMY_DATABASE_URI'][10:]
+ if not os.path.isfile(database):
+ return 1 # db file does not exist
+ fs = os.path.getsize(database)
+ if fs < 1024:
+ return 2 # file size too small
+ DataStore = column_helper('data_store')
+ rows = db.session.query(DataStore.id).count()
+ if rows < 1:
+ return 4 # no rows present
+ return 0
+
+# clears the sm (successMessage) after being used in jinja
+def clear_sm():
+ session['sm'] = 0
+ return '' #must be an empty string or 'None' is displayed in the template
+
+def t_gmt():
+ t = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())
+ return t
+
+def t_loc():
+ t = strftime("%a, %d %b %Y %H:%M:%S %Z")
+ return t
+
+# make these functions available to jinja
+app.jinja_env.globals.update(t_gmt=t_gmt)
+app.jinja_env.globals.update(t_loc=t_loc)
+app.jinja_env.globals.update(clear_sm=clear_sm)
+
+# for displaying the db file size, shamelessly stolen from SO
+def convert_size(size_bytes):
+ if size_bytes == 0:
+ return "0 B"
+ size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
+ i = int(math.floor(math.log(size_bytes, 1024)))
+ p = math.pow(1024, i)
+ s = round(size_bytes / p, 2)
+ return "%s %s" % (s, size_name[i])
+
+def dbStats():
+ DataStore = column_helper('data_store')
+ DataStore = column_helper('data_store')
+ SysIDTags = column_helper('sysid_tags')
+ DataStore.time.type = MyDateType()
+ rows = db.session.query(func.count(DataStore.id)).scalar()
+ if rows == 0:
+ return(0, 0, 0, 0, 0, 0, 0)
+
+ sys_count = db.session.query(DataStore.sysid) \
+ .distinct(DataStore.sysid) \
+ .group_by(DataStore.sysid) \
+ .filter(DataStore.sysid != 0) \
+ .count()
+
+ # TODO: talkgroups and subs should be distinct by system
+ talkgroups = db.session.query(DataStore.tgid) \
+ .distinct(DataStore.tgid) \
+ .group_by(DataStore.tgid) \
+ .count()
+
+ subs = db.session.query(DataStore.suid) \
+ .distinct(DataStore.suid) \
+ .group_by(DataStore.suid) \
+ .count()
+
+ firstRec = db.session.query(DataStore.time, func.min(DataStore.time)).scalar()
+ lastRec = db.session.query(DataStore.time, func.max(DataStore.time)).scalar()
+ f = app.config['SQLALCHEMY_DATABASE_URI'][10:] # db file name
+ dbsize = convert_size(os.path.getsize(f))
+ return(rows, sys_count, talkgroups, subs, firstRec, lastRec, dbsize, f)
+
+def sysList():
+ DataStore = column_helper('data_store')
+ rows = db.session.query(func.count(DataStore.id)).scalar()
+ if rows == 0:
+ return []
+ SysIDTags = column_helper('sysid_tags')
+ sysList = db.session.query(DataStore.sysid, SysIDTags.tag.label('tag')) \
+ .distinct(DataStore.sysid) \
+ .outerjoin(SysIDTags.table_, SysIDTags.sysid == DataStore.sysid) \
+ .filter(DataStore.sysid != 0)
+ return sysList
+
+def read_tsv(filename): # used by import_tsv and inspect_tsv, careful w/ changes
+ rows = []
+ with open(filename, 'r') as f:
+ lines = f.read().rstrip().split('\n')
+ for i in range(len(lines)):
+ a = lines[i].split('\t')
+ if i == 0: # check hdr
+ if not a[0].strip().isdigit():
+ continue
+ if not a[0].strip().isdigit(): # check each a[0] for wildcards and skip (continue) if wildcards found
+ continue
+ rid = int(a[0])
+ tag = a[1]
+ priority = 0 if len(a) < 3 else int(a[2])
+ s = (rid, tag, priority)
+ rows.append(s)
+ return rows
+
+def import_tsv(argv):
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ cmd = argv[1]
+ filename = argv[2]
+ sysid = int(argv[3])
+ if cmd == 'import_tgid':
+ tbl = TGIDTags
+ elif cmd == 'import_unit':
+ tbl = UnitIDTags
+ else:
+ print('%s unsupported' % (cmd))
+ return
+ rows = read_tsv(filename)
+ rm = 0 # records matched
+ nr = 0 # new records
+ dr = 0 # duplicate records
+ if len(rows):
+ for i in rows:
+ recCount = db.session.query(tbl.table_).where(and_(tbl.rid == i[0], tbl.sysid == argv[3])).count()
+ if recCount == 1:
+ # update record
+ q = update(tbl.table_) \
+ .where(and_(tbl.rid == i[0], tbl.sysid == argv[3])) \
+ .values(rid = int(i[0]), sysid = int(argv[3]), tag = i[1], priority = int(i[2]))
+ db.session.execute(q)
+ db.session.commit()
+ rm +=1
+ elif recCount == 0:
+ # insert record
+ q = insert(tbl.table_).values(rid = int(i[0]), sysid = int(argv[3]), tag = i[1], priority = int(i[2]))
+ db.session.execute(q)
+ db.session.commit()
+ nr += 1
+ else:
+ # delete all of the duplicates and insert new (duplicates break things)
+ print('command %s - db error - %s records for %s %s' % (cmd, recCount, i[0], i[1]))
+ delRec = delete(TGIDTags.table_).where(and_(tbl.rid == i[0], tbl.sysid == argv[3]))
+ db.session.execute(delRec)
+ db.session.commit()
+ q = insert(tbl.table_).values(rid = int(i[0]), sysid = int(argv[3]), tag = i[1], priority = int(i[2]))
+ db.session.execute(q)
+ db.session.commit()
+ dr += 1
+ return(rm, nr, dr)
+
+@app.route("/")
+def home():
+ ds = dbstate()
+ if ds != 0:
+ return redirect('error?code=%s' % ds)
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ params['cc_desc'] = cc_desc
+ return render_template("home.html", project="op25", params=params, dbstats=dbStats(), sysList=sysList())
+
+@app.route("/about")
+def about():
+ ds = dbstate()
+ if ds != 0:
+ return redirect('error?code=%s' % ds)
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ params['cc_desc'] = cc_desc
+ return render_template("about.html", project="op25", params=params, sysList=sysList())
+
+# error page for database errors
+@app.route("/error")
+def error_page():
+ params = request.args.to_dict()
+ params['file'] = app.config['SQLALCHEMY_DATABASE_URI'][10:]
+ return render_template("error.html", params=params, file=params['file'], code=int(params['code']))
+
+# Inspect TSV (import) - returns a table of the tsv for display in a div, accessed by ajax
+@app.route("/inspect")
+def inspect():
+ params = request.args.to_dict()
+ f = os.getcwd() + '/../' + params['file']
+ i = read_tsv(f)
+ return render_template("inspect.html", i=i)
+
+# edit and import tags
+@app.route("/edit_tags")
+def edit_tags():
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ SysIDTags = column_helper('sysid_tags')
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ if 'cmd' not in params.keys(): # render talkgroup by default
+ params['cmd'] = 'tgid'
+ cmd = params['cmd']
+ session['cmd'] = cmd
+ systems = db.session.query(SysIDTags.sysid, SysIDTags.tag)
+ p = os.getcwd() + '/..'
+ tsvs = []
+ for root, dirs, files in os.walk(p, topdown=True):
+ for file in files:
+ if file.endswith(".tsv") and not file.startswith("._"):
+ print(os.path.join(root, file))
+ tsvs.append(os.path.join(root, file))
+ tsvs.sort()
+ return render_template("edit_tags.html", params=params, systems=systems, sysList=sysList(), p=p, cmd=cmd, tsvs=tsvs)
+
+# data for tags table editor
+@app.route("/edittg")
+def edittg():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ cmd = params['cmd']
+ sysid = int(params['sysid'])
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ SysIDTags = column_helper('sysid_tags')
+ if cmd == 'tgid':
+ tbl = TGIDTags
+ if cmd == 'unit':
+ tbl = UnitIDTags
+ column_d = {
+ 'tgid': [
+ ColumnDT(TGIDTags.id),
+ ColumnDT(TGIDTags.sysid),
+ ColumnDT(TGIDTags.rid),
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(TGIDTags.id)
+ ],
+ 'unit': [
+ ColumnDT(UnitIDTags.id),
+ ColumnDT(UnitIDTags.sysid),
+ ColumnDT(UnitIDTags.rid),
+ ColumnDT(UnitIDTags.tag),
+ ColumnDT(UnitIDTags.id)
+ ]
+ }
+ q = db.session.query(tbl.id, tbl.sysid, tbl.rid, tbl.tag).order_by(tbl.rid)
+ if sysid != 0:
+ q = q.filter(tbl.sysid == sysid)
+ rowTable = DataTables(params, q, column_d[cmd])
+ js = jsonify(rowTable.output_result())
+ return js
+
+#dtd = delete tag data
+@app.route("/dtd")
+def dtd():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ cmd = params['cmd']
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ SysIDTags = column_helper('sysid_tags')
+ recId = params['id']
+ if cmd == 'tgid':
+ tbl = TGIDTags
+ if cmd == 'unit':
+ tbl = UnitIDTags
+ delRec = delete(tbl.table_).where(tbl.id == recId)
+ db.session.execute(delRec)
+ db.session.commit()
+ session['sm'] = 2
+ return redirect('/edit_tags?cmd=' + cmd)
+
+#utd = update tag data
+@app.route("/utd")
+def utd():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ cmd = params['cmd']
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ SysIDTags = column_helper('sysid_tags')
+ recId = params['id']
+ tag = params['tag']
+ if cmd == 'tgid':
+ tbl = TGIDTags
+ if cmd == 'unit':
+ tbl = UnitIDTags
+ upRec = update(tbl.table_).where(tbl.id == recId).values(tag=tag)
+ db.session.execute(upRec)
+ db.session.commit()
+ session['sm'] = 1
+ return redirect('/edit_tags?cmd=' + cmd)
+
+# import tags
+@app.route("/itt")
+def itt():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ cmd = params['cmd']
+ argv = [ None, 'import_' + cmd, os.getcwd() + '/../' + params['file'], params['sysid'] ]
+ session['imp_results'] = import_tsv(argv)
+ session['sm'] = 3
+ return redirect('/edit_tags?cmd=' + cmd)
+
+# delete all talkgroup/subscriber tags
+@app.route("/delTags")
+def delTags():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ cmd = params['cmd']
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ SysIDTags = column_helper('sysid_tags')
+ sysid = params['sysid']
+ if cmd == 'tgid':
+ tbl = TGIDTags
+ if cmd == 'unit':
+ tbl = UnitIDTags
+ delRec = delete(tbl.table_).where(tbl.sysid == sysid)
+ db.session.execute(delRec)
+ db.session.commit()
+ db.session.execute("VACUUM") # sqlite3 clean up -- reduces file size
+ session['sm'] = 4
+ return redirect('/edit_tags?cmd=' + cmd)
+
+# system tag editor functions (entirely separate from the tags editor above)
+@app.route("/editsys")
+def editsys():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ params['cc_desc'] = cc_desc
+ SysIDTags = column_helper('sysid_tags')
+ systems = db.session.query(SysIDTags.sysid, SysIDTags.tag)
+ return render_template("editsys.html", params=params, systems=systems, sysList=sysList())
+
+#dsd = delete system data
+@app.route("/dsd")
+def dsd():
+ params = request.args.to_dict()
+ SysIDTags = column_helper('sysid_tags')
+ recId = params['id']
+ delRec = delete(SysIDTags.table_).where(SysIDTags.id == recId)
+ db.session.execute(delRec)
+ db.session.commit()
+ return redirect('/editsys')
+
+#usd = update system data
+@app.route("/usd")
+def usd():
+ params = request.args.to_dict()
+ SysIDTags = column_helper('sysid_tags')
+ recId = params['id']
+ tag = params['tag']
+ upRec = update(SysIDTags.table_).where(SysIDTags.id == recId).values(tag=tag)
+ db.session.execute(upRec)
+ db.session.commit()
+ return redirect('/editsys')
+
+#esd = edit system data (system tags)
+@app.route("/esd")
+def esd():
+ params = request.args.to_dict()
+ SysIDTags = column_helper('sysid_tags')
+ column_d = {
+ 's': [
+ ColumnDT(SysIDTags.id),
+ ColumnDT(SysIDTags.sysid),
+ ColumnDT(SysIDTags.tag),
+ ColumnDT(SysIDTags.id)
+ ]
+ }
+ q = db.session.query(SysIDTags.id, SysIDTags.sysid, SysIDTags.tag)
+ rowTable = DataTables(params, q, column_d['s'])
+ js = jsonify(rowTable.output_result())
+ return js
+
+#asd = add system data
+@app.route("/asd")
+def asd():
+ params = request.args.to_dict()
+ ns = params['id']
+ nt = params['tag']
+ #todo: validate input
+ SysIDTags = column_helper('sysid_tags')
+ insRec = insert(SysIDTags.table_).values(sysid=ns, tag=nt)
+ db.session.execute(insRec)
+ db.session.commit()
+ return redirect('/editsys')
+
+# purge database functions
+@app.route("/purge")
+def purge():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ DataStore = column_helper('data_store')
+ destfile = ''
+ b = False
+ if 'bu' in params.keys():
+ if params['bu'] == 'true':
+ b = True
+ t = strftime("%Y%m%d_%H%M%S")
+ destfile = 'op25-backup-%s.db' % t
+ src = app.config['SQLALCHEMY_DATABASE_URI'][10:]
+ s = src.split('/')
+ f = s[-1]
+ dst = src.replace(f, destfile)
+ if 'simulate' in params.keys():
+ simulate = params['simulate']
+ if 'action' in params.keys():
+ if params['action'] == 'purge':
+ sd = params['sd']
+ ed = params['ed']
+ sysid = int(params['sysid'])
+ delRec = delete(DataStore.table_).where(DataStore.time >= int(sd), DataStore.time <= int(ed))
+ recCount = db.session.query(DataStore.id).filter(and_(DataStore.time >= int(sd), DataStore.time <= int(ed)))
+ if sysid != 0:
+ recCount = recCount.filter(DataStore.sysid == sysid)
+ delRec = delRec.where(DataStore.sysid == sysid)
+ if 'kv' in params.keys(): # keep voice calls
+ if params['kv'] == 'true':
+ recCount = recCount.where(and_(DataStore.opcode != 0, DataStore.opcode != 2))
+ delRec = delRec.where(and_(DataStore.opcode != 0, DataStore.opcode != 2))
+ recCount = recCount.count()
+ dispQuery = delRec.compile(compile_kwargs={"literal_binds": True})
+ if simulate == 'false':
+ if b == True:
+ copyfile(src, dst)
+ db.session.execute(delRec)
+ db.session.commit()
+ db.session.execute("VACUUM") # sqlite3 clean up -- reduces file size
+ successMessage = 1
+ else:
+ successMessage = 2
+ else:
+ recCount = 0
+ successMessage = 0
+ dispQuery = ''
+
+ return render_template("purge.html", \
+ project="op25", \
+ params=params, \
+ dbstats=dbStats(), \
+ sysList=sysList(), \
+ successMessage=successMessage, \
+ recCount=recCount, \
+ dispQuery=dispQuery, \
+ destfile=destfile )
+
+# displays all logs w/ datatables
+@app.route("/logs")
+def logs():
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ tag = ''
+ params = request.args.to_dict()
+ params['ekeys'] = oplog_map.keys()
+ params['cc_desc'] = cc_desc
+ t = None if 'q' not in params.keys() else params['q']
+ sysid = 0 if 'sysid' not in params.keys() else int(params['sysid'])
+ if sysid != 0:
+ if t is not None and params['r'] == 'tgid':
+ q = db.session.query(TGIDTags.tag).where(and_(TGIDTags.rid == t, TGIDTags.sysid == sysid))
+ if t is not None and params['r'] == 'su':
+ q = db.session.query(UnitIDTags.tag).where(and_(UnitIDTags.rid == t, UnitIDTags.sysid == sysid))
+ if q.count() > 0:
+ tg = (db.session.execute(q).one())
+ tag = (' - %s' % tg.tag)
+ if params['r'] == 'cc_event':
+ mapl = oplog_map[params['p'].strip()]
+ params['ckeys'] = [s[1] for s in mapl if s[0] != 'opcode' and s[0] != 'cc_event']
+
+ return render_template("logs.html", \
+ project="logs", \
+ params=params, \
+ sysList=sysList(), \
+ tag=tag )
+
+# data for /logs
+@app.route("/data")
+def data():
+ """Return server side data."""
+ # GET parameters
+ params = request.args.to_dict()
+
+ host_rid = None if 'host_rid' not in params.keys() else params['host_rid']
+ host_function_type = None if 'host_function_type' not in params.keys() else params['host_function_type']
+ host_function_param = None if 'host_function_param' not in params.keys() else params['host_function_param'].strip()
+
+ filter_tgid = None if 'tgid' not in params.keys() else int(params['tgid'].strip())
+ filter_suid = None if 'suid' not in params.keys() else int(params['suid'].strip())
+
+ start_time = None if 'sdate' not in params.keys() else datetime.datetime.utcfromtimestamp(float(params['sdate']))
+ end_time = None if 'edate' not in params.keys() else datetime.datetime.utcfromtimestamp(float(params['edate']))
+ print(params)
+ sysid = None if 'sysid' not in params.keys() else int(params['sysid'])
+
+ stime = int(params['sdate']) #used in the queries
+ etime = int(params['edate']) #used in the queries
+
+ DataStore = column_helper('data_store')
+ EventKeys = column_helper('event_keys')
+ SysIDTags = column_helper('sysid_tags')
+ UnitIDTags = column_helper('unit_id_tags')
+ TGIDTags = column_helper('tgid_tags')
+ LocRegResp = column_helper('loc_reg_resp_rv')
+
+ DataStore.time.type = MyDateType()
+
+ k = 'logs'
+ if host_function_type:
+ k = '%s_%s' % (k, host_function_type)
+
+ column_d = {
+ 'logs_su': [
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(DataStore.tgid),
+ ColumnDT(DataStore.tgid),
+ ],
+ 'logs_tgid': [
+ ColumnDT(DataStore.suid),
+ ColumnDT(UnitIDTags.tag),
+ ColumnDT(DataStore.suid),
+ ColumnDT(DataStore.time)
+ ],
+
+ 'logs_calls': [
+ ColumnDT(DataStore.time),
+ ColumnDT(SysIDTags.tag),
+ ColumnDT(DataStore.tgid),
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(DataStore.frequency),
+ ColumnDT(DataStore.suid)
+ ],
+ 'logs_joins': [
+ ColumnDT(DataStore.time),
+ ColumnDT(DataStore.opcode),
+ ColumnDT(DataStore.sysid),
+ ColumnDT(SysIDTags.tag),
+ ColumnDT(LocRegResp.tag),
+ ColumnDT(DataStore.tgid),
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(DataStore.suid),
+ ColumnDT(UnitIDTags.tag)
+ ],
+ 'logs_total_tgid': [
+ ColumnDT(DataStore.sysid),
+ ColumnDT(SysIDTags.tag),
+ ColumnDT(DataStore.tgid),
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(DataStore.tgid)
+ ],
+ 'logs_call_detail': [
+ ColumnDT(DataStore.time),
+ ColumnDT(DataStore.opcode),
+ ColumnDT(SysIDTags.sysid),
+ ColumnDT(SysIDTags.tag),
+ ColumnDT(DataStore.tgid),
+ ColumnDT(TGIDTags.tag),
+ ColumnDT(DataStore.suid),
+ ColumnDT(UnitIDTags.tag),
+ ColumnDT(DataStore.frequency)
+ ]
+ }
+
+ """or_( EventKeys.tag == 'grp_v_ch_grant', EventKeys.tag == 'grp_v_ch_grant_exp'),"""
+
+ query_d = {
+ 'logs_total_tgid': db.session.query(DataStore.sysid, \
+ SysIDTags.tag, \
+ DataStore.tgid, \
+ TGIDTags.tag, \
+ func.count(DataStore.tgid).label('count'))
+ .group_by(DataStore.tgid)
+ .outerjoin(SysIDTags.table_, DataStore.sysid == SysIDTags.sysid)
+ .outerjoin(TGIDTags.table_, DataStore.tgid == TGIDTags.rid)
+ .filter(and_(DataStore.tgid != 0), (DataStore.frequency != None) ),
+
+ 'logs_call_detail': db.session.query(DataStore.time, \
+ DataStore.opcode, \
+ DataStore.sysid, \
+ SysIDTags.tag, \
+ DataStore.tgid, \
+ TGIDTags.tag, \
+ DataStore.suid, \
+ UnitIDTags.tag, \
+ DataStore.frequency )
+ .outerjoin(SysIDTags.table_, DataStore.sysid == SysIDTags.sysid)
+ .outerjoin(TGIDTags.table_, and_(DataStore.tgid == TGIDTags.rid, DataStore.sysid == TGIDTags.sysid))
+ .outerjoin(UnitIDTags.table_, and_(DataStore.suid == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid))
+ .filter(and_(DataStore.tgid != 0), (DataStore.frequency != None) )
+ .filter(or_(DataStore.opcode == 0, and_(DataStore.opcode == 2, DataStore.mfrid == 144)) ),
+
+
+ 'logs_tgid': db.session.query(DataStore.suid, \
+ UnitIDTags.tag, \
+ func.count(DataStore.suid).label('count'), func.max(DataStore.time).label('last') )
+ .outerjoin(UnitIDTags.table_, and_(DataStore.suid == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid)),
+
+ 'logs_su': db.session.query(TGIDTags.tag, \
+ DataStore.tgid, \
+ func.count(DataStore.tgid).label('count') )
+ .outerjoin(TGIDTags.table_, DataStore.tgid == TGIDTags.rid),
+
+ 'logs_calls': db.session.query(DataStore.time, \
+ SysIDTags.tag, \
+ DataStore.tgid, \
+ TGIDTags.tag, \
+ DataStore.frequency, \
+ DataStore.suid )
+ .join(EventKeys.table_, and_(or_( EventKeys.tag == 'grp_v_ch_grant', EventKeys.tag == 'grp_v_ch_grant_mbt'),EventKeys.id == DataStore.cc_event))
+ .outerjoin(TGIDTags.table_, and_(TGIDTags.rid == DataStore.tgid, TGIDTags.sysid == DataStore.sysid))
+ .outerjoin(SysIDTags.table_, DataStore.sysid == SysIDTags.sysid),
+
+ 'logs_joins': db.session.query(DataStore.time, \
+ DataStore.opcode, \
+ DataStore.sysid, \
+ SysIDTags.tag, \
+ LocRegResp.tag, \
+ DataStore.tgid, \
+ TGIDTags.tag, \
+ DataStore.suid, \
+ UnitIDTags.tag )
+ .join(LocRegResp.table_, DataStore.p == LocRegResp.rv)
+ .outerjoin(SysIDTags.table_, DataStore.sysid == SysIDTags.sysid)
+ .outerjoin(TGIDTags.table_, and_(DataStore.tgid == TGIDTags.rid, DataStore.sysid == TGIDTags.sysid))
+ .outerjoin(UnitIDTags.table_, and_(DataStore.suid == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid))
+ .filter(or_(DataStore.opcode == 40, DataStore.opcode == 43)) # joins
+ } # end query_d
+
+ if host_function_type != 'cc_event':
+ q = query_d[k]
+
+ if host_function_type in 'su tgid'.split():
+ filter_col = {'su': DataStore.suid, 'tgid': DataStore.tgid}
+ group_col = {'su': DataStore.tgid, 'tgid': DataStore.suid}
+ if '?' in host_rid:
+ id_start = int(host_rid.replace('?', '0'))
+ id_end = int(host_rid.replace('?', '9'))
+ q = q.filter(filter_col[host_function_type] >= id_start, filter_col[host_function_type] <= id_end)
+ elif '-' in host_rid:
+ id_start, id_end = host_rid.split('-')
+ id_start = int(id_start)
+ id_end = int(id_end)
+ q = q.filter(filter_col[host_function_type] >= id_start, filter_col[host_function_type] <= id_end)
+ else:
+ q = q.filter(filter_col[host_function_type] == int(host_rid))
+ q = q.group_by(group_col[host_function_type])
+ q = q.filter(DataStore.suid != None)
+
+ dt_cols = {
+ 'logs_tgid' : [ DataStore.suid, UnitIDTags.tag, 'count' ],
+ 'logs_su' : [ TGIDTags.tag, DataStore.tgid, 'count' ],
+ 'logs_calls' : [ DataStore.time, SysIDTags.tag, DataStore.tgid, TGIDTags.tag, DataStore.frequency, DataStore.suid ],
+ 'logs_joins' : [ DataStore.time, SysIDTags.tag, LocRegResp.tag, TGIDTags.tag, DataStore.suid ],
+ 'logs_total_tgid' : [ DataStore.sysid, SysIDTags.tag, DataStore.tgid, TGIDTags.tag, 'count' ]
+ }
+
+ if host_function_type == 'cc_event':
+ mapl = oplog_map[host_function_param]
+ columns = []
+ for row in mapl:
+ col = getattr(DataStore, row[0])
+ if row[0] == 'sysid':
+ col = SysIDTags.tag
+ elif row[1] == 'Talkgroup':
+ col = TGIDTags.tag
+ elif row[1] == 'Source' or row[1] == 'Target':
+ col = UnitIDTags.tag
+ elif row[0] == 'cc_event':
+ continue
+ #col = EventKeys.tag
+ elif row[0] == 'opcode':
+ continue
+ elif host_function_param == 'loc_reg_resp' and row[0] == 'p':
+ col = LocRegResp.tag
+ columns.append(col)
+
+ column_dt = [ColumnDT(s) for s in columns]
+
+ q = db.session.query(*columns
+ ).join(
+ EventKeys.table_, and_( EventKeys.tag == host_function_param, EventKeys.id == DataStore.cc_event)
+ ).outerjoin(
+ SysIDTags.table_, DataStore.sysid == SysIDTags.sysid
+ )
+ if host_function_param == 'grp_aff_resp':
+ q = q.outerjoin(
+ TGIDTags.table_, and_(DataStore.tgid2 == TGIDTags.rid, DataStore.sysid == TGIDTags.sysid)
+ ).outerjoin(
+ UnitIDTags.table_, and_(DataStore.suid == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid)
+ )
+
+ elif host_function_param == 'ack_resp_fne' or host_function_param == 'grp_aff_q' or host_function_param == 'u_reg_cmd':
+ q = q.outerjoin(
+ TGIDTags.table_, and_(DataStore.tgid2 == TGIDTags.rid, DataStore.sysid == TGIDTags.sysid)
+ ).outerjoin(
+ UnitIDTags.table_, and_(DataStore.suid2 == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid)
+ )
+ else:
+ q = q.outerjoin(
+ TGIDTags.table_, and_(DataStore.tgid == TGIDTags.rid, DataStore.sysid == TGIDTags.sysid)
+ ).outerjoin(
+ UnitIDTags.table_, and_(DataStore.suid == UnitIDTags.rid, DataStore.sysid == UnitIDTags.sysid)
+ )
+
+ if host_function_param == 'loc_reg_resp':
+ q = q.join(LocRegResp.table_, LocRegResp.rv == DataStore.p)
+
+ if host_function_type == 'cc_event':
+ cl = columns
+ elif k in dt_cols:
+ cl = dt_cols[k]
+ else:
+ cl = None
+
+ # apply tgid and suid filters if present
+ if host_function_type == 'cc_event':
+ if filter_tgid is not None and int(filter_tgid) != 0:
+ q = q.filter(DataStore.tgid == filter_tgid)
+ if filter_suid is not None and int(filter_suid) != 0:
+ q = q.filter(DataStore.suid == filter_suid)
+
+ if cl:
+ c = int(params['order[0][column]'])
+ d = params['order[0][dir]'] # asc or desc
+ if d == 'asc':
+ q = q.order_by(cl[c])
+ else:
+ q = q.order_by(desc(cl[c]))
+
+ q = q.filter(and_(DataStore.time >= int(stime), DataStore.time <= int(etime)))
+
+ if sysid != 0:
+ q = q.filter(DataStore.sysid == sysid)
+
+ if host_function_type == 'cc_event':
+ rowTable = DataTables(params, q, column_dt)
+ else:
+ rowTable = DataTables(params, q, column_d[k])
+
+ js = jsonify(rowTable.output_result())
+# j= 'skipped' # json.dumps(rowTable.output_result(), indent=4, separators=[',', ':'], sort_keys=True)
+# with open('data-log', 'a') as logf:
+# s = '\n\t'.join(['%s:%s' % (k, params[k]) for k in params.keys()])
+# logf.write('keys: %s\n' % (' '.join(params.keys())))
+# logf.write('params:\n\t%s\nrequest: %s\n' % (s, function_req))
+# logf.write('%s\n' % j)
+ return js
+
+# switch and backup database file
+@app.route("/switch_db")
+def switch_db():
+ params = request.args.to_dict()
+ params['ekeys'] = sorted(oplog_map.keys())
+ p = os.getcwd() + '/..'
+ files = [f for f in listdir(p) if isfile(join(p, f))]
+ files.sort()
+ if 'cmd' not in params.keys():
+ curr_file = app.config['SQLALCHEMY_DATABASE_URI'].split('/')[-1]
+ return render_template("switch_db.html", params=params, files=files, curr_file=curr_file)
+ if params['cmd'] == 'backup':
+ t = strftime("%Y-%m-%d_%H%M%S")
+ destfile = 'op25-backup-%s.db' % t
+ src = app.config['SQLALCHEMY_DATABASE_URI'][10:]
+ s = src.split('/')
+ curr_file = s[-1]
+ dst = src.replace(curr_file, destfile)
+ copyfile(src, dst)
+ return render_template("switch_db.html", params=params, destfile=destfile, curr_file=curr_file, files=files, sm=1)
+ if params['cmd'] == 'switch':
+ new_f = params['file']
+ database = app.config['SQLALCHEMY_DATABASE_URI']
+ f = database.split('/')[-1]
+ new_db = database.replace(f, new_f)
+ print('switching database to: %s' % new_db)
+ app.config['SQLALCHEMY_DATABASE_URI'] = new_db
+ return redirect('/')
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap-darkly.css b/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap-darkly.css
new file mode 100644
index 0000000..b03944b
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap-darkly.css
@@ -0,0 +1,11038 @@
+/*!
+ * Bootswatch v5.0.1
+ * Homepage: https://bootswatch.com
+ * Copyright 2012-2021 Thomas Park
+ * Licensed under MIT
+ * Based on Bootstrap
+*/
+/*!
+ * Bootstrap v5.0.1 (https://getbootstrap.com/)
+ * Copyright 2011-2021 The Bootstrap Authors
+ * Copyright 2011-2021 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ */
+/* @import url("https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400&display=swap"); */
+:root {
+ --bs-blue: #375a7f;
+ --bs-indigo: #6610f2;
+ --bs-purple: #6f42c1;
+ --bs-pink: #e83e8c;
+ --bs-red: #e74c3c;
+ --bs-orange: #fd7e14;
+ --bs-yellow: #f39c12;
+ --bs-green: #00bc8c;
+ --bs-teal: #20c997;
+ --bs-cyan: #3498db;
+ --bs-white: #fff;
+ --bs-gray: #888;
+ --bs-gray-dark: #303030;
+ --bs-primary: #375a7f;
+ --bs-secondary: #444;
+ --bs-success: #00bc8c;
+ --bs-info: #3498db;
+ --bs-warning: #f39c12;
+ --bs-danger: #e74c3c;
+ --bs-light: #adb5bd;
+ --bs-dark: #303030;
+ --bs-font-sans-serif: Lato, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
+ --bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
+ --bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));
+}
+
+*,
+*::before,
+*::after {
+ box-sizing: border-box;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ :root {
+ scroll-behavior: smooth;
+ }
+}
+
+body {
+ margin: 0;
+ font-family: var(--bs-font-sans-serif);
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #fff;
+ background-color: #060606;
+ -webkit-text-size-adjust: 100%;
+ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
+}
+
+
+.navbar-right {
+ float: right !important;
+ margin-right: -15px;
+ }
+
+
+hr {
+ margin: 1rem 0;
+ color: inherit;
+ background-color: currentColor;
+ border: 0;
+ opacity: 0.25;
+}
+
+hr:not([size]) {
+ height: 1px;
+}
+
+h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
+ margin-top: 0;
+ margin-bottom: 0.5rem;
+ font-weight: 500;
+ line-height: 1.2;
+}
+
+h1, .h1 {
+ font-size: calc(1.425rem + 2.1vw);
+}
+
+@media (min-width: 1200px) {
+ h1, .h1 {
+ font-size: 3rem;
+ }
+}
+
+h2, .h2 {
+ font-size: calc(1.375rem + 1.5vw);
+}
+
+@media (min-width: 1200px) {
+ h2, .h2 {
+ font-size: 2.5rem;
+ }
+}
+
+h3, .h3 {
+ font-size: calc(1.325rem + 0.9vw);
+}
+
+@media (min-width: 1200px) {
+ h3, .h3 {
+ font-size: 2rem;
+ }
+}
+
+h4, .h4 {
+ font-size: calc(1.275rem + 0.3vw);
+}
+
+@media (min-width: 1200px) {
+ h4, .h4 {
+ font-size: 1.5rem;
+ }
+}
+
+h5, .h5 {
+ font-size: 1.25rem;
+}
+
+h6, .h6 {
+ font-size: 1rem;
+}
+
+p {
+ margin-top: 0;
+ margin-bottom: 1rem;
+}
+
+abbr[title],
+abbr[data-bs-original-title] {
+ -webkit-text-decoration: underline dotted;
+ text-decoration: underline dotted;
+ cursor: help;
+ -webkit-text-decoration-skip-ink: none;
+ text-decoration-skip-ink: none;
+}
+
+address {
+ margin-bottom: 1rem;
+ font-style: normal;
+ line-height: inherit;
+}
+
+ol,
+ul {
+ padding-left: 2rem;
+}
+
+ol,
+ul,
+dl {
+ margin-top: 0;
+ margin-bottom: 1rem;
+}
+
+ol ol,
+ul ul,
+ol ul,
+ul ol {
+ margin-bottom: 0;
+}
+
+dt {
+ font-weight: 700;
+}
+
+dd {
+ margin-bottom: .5rem;
+ margin-left: 0;
+}
+
+blockquote {
+ margin: 0 0 1rem;
+}
+
+b,
+strong {
+ font-weight: bolder;
+}
+
+small, .small {
+ font-size: 0.875em;
+}
+
+mark, .mark {
+ padding: 0.2em;
+ background-color: #fcf8e3;
+}
+
+sub,
+sup {
+ position: relative;
+ font-size: 0.75em;
+ line-height: 0;
+ vertical-align: baseline;
+}
+
+sub {
+ bottom: -.25em;
+}
+
+sup {
+ top: -.5em;
+}
+
+a {
+ color: #00bc8c;
+ text-decoration: underline;
+}
+
+a:hover {
+ color: #009670;
+}
+
+a:not([href]):not([class]), a:not([href]):not([class]):hover {
+ color: inherit;
+ text-decoration: none;
+}
+
+pre,
+code,
+kbd,
+samp {
+ font-family: var(--bs-font-monospace);
+ font-size: 1em;
+ direction: ltr /* rtl:ignore */;
+ unicode-bidi: bidi-override;
+}
+
+pre {
+ display: block;
+ margin-top: 0;
+ margin-bottom: 1rem;
+ overflow: auto;
+ font-size: 0.875em;
+ color: inherit;
+}
+
+pre code {
+ font-size: inherit;
+ color: inherit;
+ word-break: normal;
+}
+
+code {
+ font-size: 0.875em;
+ color: #e83e8c;
+ word-wrap: break-word;
+}
+
+a > code {
+ color: inherit;
+}
+
+kbd {
+ padding: 0.2rem 0.4rem;
+ font-size: 0.875em;
+ color: #fff;
+ background-color: #222;
+ border-radius: 0.2rem;
+}
+
+kbd kbd {
+ padding: 0;
+ font-size: 1em;
+ font-weight: 700;
+}
+
+figure {
+ margin: 0 0 1rem;
+}
+
+img,
+svg {
+ vertical-align: middle;
+}
+
+table {
+ caption-side: bottom;
+ border-collapse: collapse;
+}
+
+caption {
+ padding-top: 0.5rem;
+ padding-bottom: 0.5rem;
+ color: #888;
+ text-align: left;
+}
+
+th {
+ text-align: inherit;
+ text-align: -webkit-match-parent;
+}
+
+thead,
+tbody,
+tfoot,
+tr,
+td,
+th {
+ border-color: inherit;
+ border-style: solid;
+ border-width: 0;
+}
+
+label {
+ display: inline-block;
+}
+
+button {
+ border-radius: 0;
+}
+
+button:focus:not(:focus-visible) {
+ outline: 0;
+}
+
+input,
+button,
+select,
+optgroup,
+textarea {
+ margin: 0;
+ font-family: inherit;
+ font-size: inherit;
+ line-height: inherit;
+}
+
+button,
+select {
+ text-transform: none;
+}
+
+[role="button"] {
+ cursor: pointer;
+}
+
+select {
+ word-wrap: normal;
+}
+
+select:disabled {
+ opacity: 1;
+}
+
+[list]::-webkit-calendar-picker-indicator {
+ display: none;
+}
+
+button,
+[type="button"],
+[type="reset"],
+[type="submit"] {
+ -webkit-appearance: button;
+}
+
+button:not(:disabled),
+[type="button"]:not(:disabled),
+[type="reset"]:not(:disabled),
+[type="submit"]:not(:disabled) {
+ cursor: pointer;
+}
+
+::-moz-focus-inner {
+ padding: 0;
+ border-style: none;
+}
+
+textarea {
+ resize: vertical;
+}
+
+fieldset {
+ min-width: 0;
+ padding: 0;
+ margin: 0;
+ border: 0;
+}
+
+legend {
+ float: left;
+ width: 100%;
+ padding: 0;
+ margin-bottom: 0.5rem;
+ font-size: calc(1.275rem + 0.3vw);
+ line-height: inherit;
+}
+
+@media (min-width: 1200px) {
+ legend {
+ font-size: 1.5rem;
+ }
+}
+
+legend + * {
+ clear: left;
+}
+
+::-webkit-datetime-edit-fields-wrapper,
+::-webkit-datetime-edit-text,
+::-webkit-datetime-edit-minute,
+::-webkit-datetime-edit-hour-field,
+::-webkit-datetime-edit-day-field,
+::-webkit-datetime-edit-month-field,
+::-webkit-datetime-edit-year-field {
+ padding: 0;
+}
+
+::-webkit-inner-spin-button {
+ height: auto;
+}
+
+[type="search"] {
+ outline-offset: -2px;
+ -webkit-appearance: textfield;
+}
+
+/* rtl:raw:
+[type="tel"],
+[type="url"],
+[type="email"],
+[type="number"] {
+ direction: ltr;
+}
+*/
+::-webkit-search-decoration {
+ -webkit-appearance: none;
+}
+
+::-webkit-color-swatch-wrapper {
+ padding: 0;
+}
+
+::file-selector-button {
+ font: inherit;
+}
+
+::-webkit-file-upload-button {
+ font: inherit;
+ -webkit-appearance: button;
+}
+
+output {
+ display: inline-block;
+}
+
+iframe {
+ border: 0;
+}
+
+summary {
+ display: list-item;
+ cursor: pointer;
+}
+
+progress {
+ vertical-align: baseline;
+}
+
+[hidden] {
+ display: none !important;
+}
+
+.lead {
+ font-size: 1.25rem;
+ font-weight: 300;
+}
+
+.display-1 {
+ font-size: calc(1.625rem + 4.5vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-1 {
+ font-size: 5rem;
+ }
+}
+
+.display-2 {
+ font-size: calc(1.575rem + 3.9vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-2 {
+ font-size: 4.5rem;
+ }
+}
+
+.display-3 {
+ font-size: calc(1.525rem + 3.3vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-3 {
+ font-size: 4rem;
+ }
+}
+
+.display-4 {
+ font-size: calc(1.475rem + 2.7vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-4 {
+ font-size: 3.5rem;
+ }
+}
+
+.display-5 {
+ font-size: calc(1.425rem + 2.1vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-5 {
+ font-size: 3rem;
+ }
+}
+
+.display-6 {
+ font-size: calc(1.375rem + 1.5vw);
+ font-weight: 300;
+ line-height: 1.2;
+}
+
+@media (min-width: 1200px) {
+ .display-6 {
+ font-size: 2.5rem;
+ }
+}
+
+.list-unstyled {
+ padding-left: 0;
+ list-style: none;
+}
+
+.list-inline {
+ padding-left: 0;
+ list-style: none;
+}
+
+.list-inline-item {
+ display: inline-block;
+}
+
+.list-inline-item:not(:last-child) {
+ margin-right: 0.5rem;
+}
+
+.initialism {
+ font-size: 0.875em;
+ text-transform: uppercase;
+}
+
+.blockquote {
+ margin-bottom: 1rem;
+ font-size: 1.25rem;
+}
+
+.blockquote > :last-child {
+ margin-bottom: 0;
+}
+
+.blockquote-footer {
+ margin-top: -1rem;
+ margin-bottom: 1rem;
+ font-size: 0.875em;
+ color: #888;
+}
+
+.blockquote-footer::before {
+ content: "\2014\00A0";
+}
+
+.img-fluid {
+ max-width: 100%;
+ height: auto;
+}
+
+.img-thumbnail {
+ padding: 0.25rem;
+ background-color: #222;
+ border: 1px solid #dee2e6;
+ border-radius: 0.25rem;
+ max-width: 100%;
+ height: auto;
+}
+
+.figure {
+ display: inline-block;
+}
+
+.figure-img {
+ margin-bottom: 0.5rem;
+ line-height: 1;
+}
+
+.figure-caption {
+ font-size: 0.875em;
+ color: #888;
+}
+
+.container,
+.container-fluid,
+.container-sm,
+.container-md,
+.container-lg,
+.container-xl,
+.container-xxl {
+ width: 100%;
+ padding-right: var(--bs-gutter-x, 0.75rem);
+ padding-left: var(--bs-gutter-x, 0.75rem);
+ margin-right: auto;
+ margin-left: auto;
+}
+
+@media (min-width: 576px) {
+ .container, .container-sm {
+ max-width: 540px;
+ }
+}
+
+@media (min-width: 768px) {
+ .container, .container-sm, .container-md {
+ max-width: 720px;
+ }
+}
+
+@media (min-width: 992px) {
+ .container, .container-sm, .container-md, .container-lg {
+ max-width: 960px;
+ }
+}
+
+@media (min-width: 1200px) {
+ .container, .container-sm, .container-md, .container-lg, .container-xl {
+ max-width: 1140px;
+ }
+}
+
+@media (min-width: 1400px) {
+ .container, .container-sm, .container-md, .container-lg, .container-xl, .container-xxl {
+ max-width: 1320px;
+ }
+}
+
+.row {
+ --bs-gutter-x: 1.5rem;
+ --bs-gutter-y: 0;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ margin-top: calc(var(--bs-gutter-y) * -1);
+ margin-right: calc(var(--bs-gutter-x) / -2);
+ margin-left: calc(var(--bs-gutter-x) / -2);
+}
+
+.row > * {
+ -ms-flex-negative: 0;
+ flex-shrink: 0;
+ width: 100%;
+ max-width: 100%;
+ padding-right: calc(var(--bs-gutter-x) / 2);
+ padding-left: calc(var(--bs-gutter-x) / 2);
+ margin-top: var(--bs-gutter-y);
+}
+
+.col {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+}
+
+.row-cols-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+}
+
+.row-cols-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+}
+
+.row-cols-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+}
+
+.row-cols-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+}
+
+.row-cols-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+}
+
+.row-cols-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+}
+
+.row-cols-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+}
+
+.col-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+}
+
+.col-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+}
+
+.col-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+}
+
+.col-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+}
+
+.col-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+}
+
+.col-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+}
+
+.col-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+}
+
+.col-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+}
+
+.col-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+}
+
+.col-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+}
+
+.col-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+}
+
+.col-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+}
+
+.col-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+}
+
+.offset-1 {
+ margin-left: 8.333333%;
+}
+
+.offset-2 {
+ margin-left: 16.666667%;
+}
+
+.offset-3 {
+ margin-left: 25%;
+}
+
+.offset-4 {
+ margin-left: 33.333333%;
+}
+
+.offset-5 {
+ margin-left: 41.666667%;
+}
+
+.offset-6 {
+ margin-left: 50%;
+}
+
+.offset-7 {
+ margin-left: 58.333333%;
+}
+
+.offset-8 {
+ margin-left: 66.666667%;
+}
+
+.offset-9 {
+ margin-left: 75%;
+}
+
+.offset-10 {
+ margin-left: 83.333333%;
+}
+
+.offset-11 {
+ margin-left: 91.666667%;
+}
+
+.g-0,
+.gx-0 {
+ --bs-gutter-x: 0;
+}
+
+.g-0,
+.gy-0 {
+ --bs-gutter-y: 0;
+}
+
+.g-1,
+.gx-1 {
+ --bs-gutter-x: 0.25rem;
+}
+
+.g-1,
+.gy-1 {
+ --bs-gutter-y: 0.25rem;
+}
+
+.g-2,
+.gx-2 {
+ --bs-gutter-x: 0.5rem;
+}
+
+.g-2,
+.gy-2 {
+ --bs-gutter-y: 0.5rem;
+}
+
+.g-3,
+.gx-3 {
+ --bs-gutter-x: 1rem;
+}
+
+.g-3,
+.gy-3 {
+ --bs-gutter-y: 1rem;
+}
+
+.g-4,
+.gx-4 {
+ --bs-gutter-x: 1.5rem;
+}
+
+.g-4,
+.gy-4 {
+ --bs-gutter-y: 1.5rem;
+}
+
+.g-5,
+.gx-5 {
+ --bs-gutter-x: 3rem;
+}
+
+.g-5,
+.gy-5 {
+ --bs-gutter-y: 3rem;
+}
+
+@media (min-width: 576px) {
+ .col-sm {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ }
+ .row-cols-sm-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .row-cols-sm-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .row-cols-sm-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .row-cols-sm-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .row-cols-sm-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .row-cols-sm-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+ }
+ .row-cols-sm-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-sm-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .col-sm-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+ }
+ .col-sm-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-sm-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .col-sm-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .col-sm-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+ }
+ .col-sm-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .col-sm-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+ }
+ .col-sm-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+ }
+ .col-sm-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+ }
+ .col-sm-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+ }
+ .col-sm-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+ }
+ .col-sm-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .offset-sm-0 {
+ margin-left: 0;
+ }
+ .offset-sm-1 {
+ margin-left: 8.333333%;
+ }
+ .offset-sm-2 {
+ margin-left: 16.666667%;
+ }
+ .offset-sm-3 {
+ margin-left: 25%;
+ }
+ .offset-sm-4 {
+ margin-left: 33.333333%;
+ }
+ .offset-sm-5 {
+ margin-left: 41.666667%;
+ }
+ .offset-sm-6 {
+ margin-left: 50%;
+ }
+ .offset-sm-7 {
+ margin-left: 58.333333%;
+ }
+ .offset-sm-8 {
+ margin-left: 66.666667%;
+ }
+ .offset-sm-9 {
+ margin-left: 75%;
+ }
+ .offset-sm-10 {
+ margin-left: 83.333333%;
+ }
+ .offset-sm-11 {
+ margin-left: 91.666667%;
+ }
+ .g-sm-0,
+ .gx-sm-0 {
+ --bs-gutter-x: 0;
+ }
+ .g-sm-0,
+ .gy-sm-0 {
+ --bs-gutter-y: 0;
+ }
+ .g-sm-1,
+ .gx-sm-1 {
+ --bs-gutter-x: 0.25rem;
+ }
+ .g-sm-1,
+ .gy-sm-1 {
+ --bs-gutter-y: 0.25rem;
+ }
+ .g-sm-2,
+ .gx-sm-2 {
+ --bs-gutter-x: 0.5rem;
+ }
+ .g-sm-2,
+ .gy-sm-2 {
+ --bs-gutter-y: 0.5rem;
+ }
+ .g-sm-3,
+ .gx-sm-3 {
+ --bs-gutter-x: 1rem;
+ }
+ .g-sm-3,
+ .gy-sm-3 {
+ --bs-gutter-y: 1rem;
+ }
+ .g-sm-4,
+ .gx-sm-4 {
+ --bs-gutter-x: 1.5rem;
+ }
+ .g-sm-4,
+ .gy-sm-4 {
+ --bs-gutter-y: 1.5rem;
+ }
+ .g-sm-5,
+ .gx-sm-5 {
+ --bs-gutter-x: 3rem;
+ }
+ .g-sm-5,
+ .gy-sm-5 {
+ --bs-gutter-y: 3rem;
+ }
+}
+
+@media (min-width: 768px) {
+ .col-md {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ }
+ .row-cols-md-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .row-cols-md-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .row-cols-md-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .row-cols-md-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .row-cols-md-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .row-cols-md-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+ }
+ .row-cols-md-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-md-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .col-md-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+ }
+ .col-md-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-md-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .col-md-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .col-md-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+ }
+ .col-md-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .col-md-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+ }
+ .col-md-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+ }
+ .col-md-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+ }
+ .col-md-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+ }
+ .col-md-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+ }
+ .col-md-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .offset-md-0 {
+ margin-left: 0;
+ }
+ .offset-md-1 {
+ margin-left: 8.333333%;
+ }
+ .offset-md-2 {
+ margin-left: 16.666667%;
+ }
+ .offset-md-3 {
+ margin-left: 25%;
+ }
+ .offset-md-4 {
+ margin-left: 33.333333%;
+ }
+ .offset-md-5 {
+ margin-left: 41.666667%;
+ }
+ .offset-md-6 {
+ margin-left: 50%;
+ }
+ .offset-md-7 {
+ margin-left: 58.333333%;
+ }
+ .offset-md-8 {
+ margin-left: 66.666667%;
+ }
+ .offset-md-9 {
+ margin-left: 75%;
+ }
+ .offset-md-10 {
+ margin-left: 83.333333%;
+ }
+ .offset-md-11 {
+ margin-left: 91.666667%;
+ }
+ .g-md-0,
+ .gx-md-0 {
+ --bs-gutter-x: 0;
+ }
+ .g-md-0,
+ .gy-md-0 {
+ --bs-gutter-y: 0;
+ }
+ .g-md-1,
+ .gx-md-1 {
+ --bs-gutter-x: 0.25rem;
+ }
+ .g-md-1,
+ .gy-md-1 {
+ --bs-gutter-y: 0.25rem;
+ }
+ .g-md-2,
+ .gx-md-2 {
+ --bs-gutter-x: 0.5rem;
+ }
+ .g-md-2,
+ .gy-md-2 {
+ --bs-gutter-y: 0.5rem;
+ }
+ .g-md-3,
+ .gx-md-3 {
+ --bs-gutter-x: 1rem;
+ }
+ .g-md-3,
+ .gy-md-3 {
+ --bs-gutter-y: 1rem;
+ }
+ .g-md-4,
+ .gx-md-4 {
+ --bs-gutter-x: 1.5rem;
+ }
+ .g-md-4,
+ .gy-md-4 {
+ --bs-gutter-y: 1.5rem;
+ }
+ .g-md-5,
+ .gx-md-5 {
+ --bs-gutter-x: 3rem;
+ }
+ .g-md-5,
+ .gy-md-5 {
+ --bs-gutter-y: 3rem;
+ }
+}
+
+@media (min-width: 992px) {
+ .col-lg {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ }
+ .row-cols-lg-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .row-cols-lg-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .row-cols-lg-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .row-cols-lg-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .row-cols-lg-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .row-cols-lg-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+ }
+ .row-cols-lg-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-lg-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .col-lg-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+ }
+ .col-lg-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-lg-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .col-lg-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .col-lg-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+ }
+ .col-lg-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .col-lg-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+ }
+ .col-lg-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+ }
+ .col-lg-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+ }
+ .col-lg-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+ }
+ .col-lg-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+ }
+ .col-lg-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .offset-lg-0 {
+ margin-left: 0;
+ }
+ .offset-lg-1 {
+ margin-left: 8.333333%;
+ }
+ .offset-lg-2 {
+ margin-left: 16.666667%;
+ }
+ .offset-lg-3 {
+ margin-left: 25%;
+ }
+ .offset-lg-4 {
+ margin-left: 33.333333%;
+ }
+ .offset-lg-5 {
+ margin-left: 41.666667%;
+ }
+ .offset-lg-6 {
+ margin-left: 50%;
+ }
+ .offset-lg-7 {
+ margin-left: 58.333333%;
+ }
+ .offset-lg-8 {
+ margin-left: 66.666667%;
+ }
+ .offset-lg-9 {
+ margin-left: 75%;
+ }
+ .offset-lg-10 {
+ margin-left: 83.333333%;
+ }
+ .offset-lg-11 {
+ margin-left: 91.666667%;
+ }
+ .g-lg-0,
+ .gx-lg-0 {
+ --bs-gutter-x: 0;
+ }
+ .g-lg-0,
+ .gy-lg-0 {
+ --bs-gutter-y: 0;
+ }
+ .g-lg-1,
+ .gx-lg-1 {
+ --bs-gutter-x: 0.25rem;
+ }
+ .g-lg-1,
+ .gy-lg-1 {
+ --bs-gutter-y: 0.25rem;
+ }
+ .g-lg-2,
+ .gx-lg-2 {
+ --bs-gutter-x: 0.5rem;
+ }
+ .g-lg-2,
+ .gy-lg-2 {
+ --bs-gutter-y: 0.5rem;
+ }
+ .g-lg-3,
+ .gx-lg-3 {
+ --bs-gutter-x: 1rem;
+ }
+ .g-lg-3,
+ .gy-lg-3 {
+ --bs-gutter-y: 1rem;
+ }
+ .g-lg-4,
+ .gx-lg-4 {
+ --bs-gutter-x: 1.5rem;
+ }
+ .g-lg-4,
+ .gy-lg-4 {
+ --bs-gutter-y: 1.5rem;
+ }
+ .g-lg-5,
+ .gx-lg-5 {
+ --bs-gutter-x: 3rem;
+ }
+ .g-lg-5,
+ .gy-lg-5 {
+ --bs-gutter-y: 3rem;
+ }
+}
+
+@media (min-width: 1200px) {
+ .col-xl {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ }
+ .row-cols-xl-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .row-cols-xl-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .row-cols-xl-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .row-cols-xl-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .row-cols-xl-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .row-cols-xl-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+ }
+ .row-cols-xl-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-xl-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .col-xl-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+ }
+ .col-xl-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-xl-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .col-xl-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .col-xl-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+ }
+ .col-xl-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .col-xl-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+ }
+ .col-xl-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+ }
+ .col-xl-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+ }
+ .col-xl-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+ }
+ .col-xl-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+ }
+ .col-xl-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .offset-xl-0 {
+ margin-left: 0;
+ }
+ .offset-xl-1 {
+ margin-left: 8.333333%;
+ }
+ .offset-xl-2 {
+ margin-left: 16.666667%;
+ }
+ .offset-xl-3 {
+ margin-left: 25%;
+ }
+ .offset-xl-4 {
+ margin-left: 33.333333%;
+ }
+ .offset-xl-5 {
+ margin-left: 41.666667%;
+ }
+ .offset-xl-6 {
+ margin-left: 50%;
+ }
+ .offset-xl-7 {
+ margin-left: 58.333333%;
+ }
+ .offset-xl-8 {
+ margin-left: 66.666667%;
+ }
+ .offset-xl-9 {
+ margin-left: 75%;
+ }
+ .offset-xl-10 {
+ margin-left: 83.333333%;
+ }
+ .offset-xl-11 {
+ margin-left: 91.666667%;
+ }
+ .g-xl-0,
+ .gx-xl-0 {
+ --bs-gutter-x: 0;
+ }
+ .g-xl-0,
+ .gy-xl-0 {
+ --bs-gutter-y: 0;
+ }
+ .g-xl-1,
+ .gx-xl-1 {
+ --bs-gutter-x: 0.25rem;
+ }
+ .g-xl-1,
+ .gy-xl-1 {
+ --bs-gutter-y: 0.25rem;
+ }
+ .g-xl-2,
+ .gx-xl-2 {
+ --bs-gutter-x: 0.5rem;
+ }
+ .g-xl-2,
+ .gy-xl-2 {
+ --bs-gutter-y: 0.5rem;
+ }
+ .g-xl-3,
+ .gx-xl-3 {
+ --bs-gutter-x: 1rem;
+ }
+ .g-xl-3,
+ .gy-xl-3 {
+ --bs-gutter-y: 1rem;
+ }
+ .g-xl-4,
+ .gx-xl-4 {
+ --bs-gutter-x: 1.5rem;
+ }
+ .g-xl-4,
+ .gy-xl-4 {
+ --bs-gutter-y: 1.5rem;
+ }
+ .g-xl-5,
+ .gx-xl-5 {
+ --bs-gutter-x: 3rem;
+ }
+ .g-xl-5,
+ .gy-xl-5 {
+ --bs-gutter-y: 3rem;
+ }
+}
+
+@media (min-width: 1400px) {
+ .col-xxl {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ }
+ .row-cols-xxl-auto > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .row-cols-xxl-1 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .row-cols-xxl-2 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .row-cols-xxl-3 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .row-cols-xxl-4 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .row-cols-xxl-5 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 20%;
+ }
+ .row-cols-xxl-6 > * {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-xxl-auto {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: auto;
+ }
+ .col-xxl-1 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 8.333333%;
+ }
+ .col-xxl-2 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 16.666667%;
+ }
+ .col-xxl-3 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 25%;
+ }
+ .col-xxl-4 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 33.333333%;
+ }
+ .col-xxl-5 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 41.666667%;
+ }
+ .col-xxl-6 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 50%;
+ }
+ .col-xxl-7 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 58.333333%;
+ }
+ .col-xxl-8 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 66.666667%;
+ }
+ .col-xxl-9 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 75%;
+ }
+ .col-xxl-10 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 83.333333%;
+ }
+ .col-xxl-11 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 91.666667%;
+ }
+ .col-xxl-12 {
+ -ms-flex: 0 0 auto;
+ flex: 0 0 auto;
+ width: 100%;
+ }
+ .offset-xxl-0 {
+ margin-left: 0;
+ }
+ .offset-xxl-1 {
+ margin-left: 8.333333%;
+ }
+ .offset-xxl-2 {
+ margin-left: 16.666667%;
+ }
+ .offset-xxl-3 {
+ margin-left: 25%;
+ }
+ .offset-xxl-4 {
+ margin-left: 33.333333%;
+ }
+ .offset-xxl-5 {
+ margin-left: 41.666667%;
+ }
+ .offset-xxl-6 {
+ margin-left: 50%;
+ }
+ .offset-xxl-7 {
+ margin-left: 58.333333%;
+ }
+ .offset-xxl-8 {
+ margin-left: 66.666667%;
+ }
+ .offset-xxl-9 {
+ margin-left: 75%;
+ }
+ .offset-xxl-10 {
+ margin-left: 83.333333%;
+ }
+ .offset-xxl-11 {
+ margin-left: 91.666667%;
+ }
+ .g-xxl-0,
+ .gx-xxl-0 {
+ --bs-gutter-x: 0;
+ }
+ .g-xxl-0,
+ .gy-xxl-0 {
+ --bs-gutter-y: 0;
+ }
+ .g-xxl-1,
+ .gx-xxl-1 {
+ --bs-gutter-x: 0.25rem;
+ }
+ .g-xxl-1,
+ .gy-xxl-1 {
+ --bs-gutter-y: 0.25rem;
+ }
+ .g-xxl-2,
+ .gx-xxl-2 {
+ --bs-gutter-x: 0.5rem;
+ }
+ .g-xxl-2,
+ .gy-xxl-2 {
+ --bs-gutter-y: 0.5rem;
+ }
+ .g-xxl-3,
+ .gx-xxl-3 {
+ --bs-gutter-x: 1rem;
+ }
+ .g-xxl-3,
+ .gy-xxl-3 {
+ --bs-gutter-y: 1rem;
+ }
+ .g-xxl-4,
+ .gx-xxl-4 {
+ --bs-gutter-x: 1.5rem;
+ }
+ .g-xxl-4,
+ .gy-xxl-4 {
+ --bs-gutter-y: 1.5rem;
+ }
+ .g-xxl-5,
+ .gx-xxl-5 {
+ --bs-gutter-x: 3rem;
+ }
+ .g-xxl-5,
+ .gy-xxl-5 {
+ --bs-gutter-y: 3rem;
+ }
+}
+
+.table {
+ --bs-table-bg: transparent;
+ --bs-table-accent-bg: transparent;
+ --bs-table-striped-color: #fff;
+ --bs-table-striped-bg: rgba(0, 0, 0, 0.05);
+ --bs-table-active-color: #fff;
+ --bs-table-active-bg: rgba(0, 0, 0, 0.1);
+ --bs-table-hover-color: #fff;
+ --bs-table-hover-bg: rgba(0, 0, 0, 0.075);
+ width: 100%;
+ margin-bottom: 1rem;
+ color: #fff;
+ vertical-align: top;
+ border-color: #444;
+}
+
+.table > :not(caption) > * > * {
+ padding: 0.5rem 0.5rem;
+ background-color: var(--bs-table-bg);
+ border-bottom-width: 1px;
+ box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg);
+}
+
+.table > tbody {
+ vertical-align: inherit;
+}
+
+.table > thead {
+ vertical-align: bottom;
+}
+
+.table > :not(:last-child) > :last-child > * {
+ border-bottom-color: currentColor;
+}
+
+.caption-top {
+ caption-side: top;
+}
+
+.table-sm > :not(caption) > * > * {
+ padding: 0.25rem 0.25rem;
+}
+
+.table-bordered > :not(caption) > * {
+ border-width: 1px 0;
+}
+
+.table-bordered > :not(caption) > * > * {
+ border-width: 0 1px;
+}
+
+.table-borderless > :not(caption) > * > * {
+ border-bottom-width: 0;
+}
+
+.table-striped > tbody > tr:nth-of-type(odd) {
+ --bs-table-accent-bg: var(--bs-table-striped-bg);
+ color: var(--bs-table-striped-color);
+}
+
+.table-active {
+ --bs-table-accent-bg: var(--bs-table-active-bg);
+ color: var(--bs-table-active-color);
+}
+
+.table-hover > tbody > tr:hover {
+ --bs-table-accent-bg: var(--bs-table-hover-bg);
+ color: var(--bs-table-hover-color);
+}
+
+.table-primary {
+ --bs-table-bg: #375a7f;
+ --bs-table-striped-bg: #416285;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #4b6b8c;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #466689;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #4b6b8c;
+}
+
+.table-secondary {
+ --bs-table-bg: #444444;
+ --bs-table-striped-bg: #4d4d4d;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #575757;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #525252;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #575757;
+}
+
+.table-success {
+ --bs-table-bg: #00bc8c;
+ --bs-table-striped-bg: #0dbf92;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #1ac398;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #13c195;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #1ac398;
+}
+
+.table-info {
+ --bs-table-bg: #3498db;
+ --bs-table-striped-bg: #3e9ddd;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #48a2df;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #43a0de;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #48a2df;
+}
+
+.table-warning {
+ --bs-table-bg: #f39c12;
+ --bs-table-striped-bg: #f4a11e;
+ --bs-table-striped-color: #000;
+ --bs-table-active-bg: #f4a62a;
+ --bs-table-active-color: #000;
+ --bs-table-hover-bg: #f4a324;
+ --bs-table-hover-color: #000;
+ color: #fff;
+ border-color: #f4a62a;
+}
+
+.table-danger {
+ --bs-table-bg: #e74c3c;
+ --bs-table-striped-bg: #e85546;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #e95e50;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #e9594b;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #e95e50;
+}
+
+.table-light {
+ --bs-table-bg: #adb5bd;
+ --bs-table-striped-bg: #a4acb4;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #9ca3aa;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #a0a7af;
+ --bs-table-hover-color: #fff;
+ color: #000;
+ border-color: #9ca3aa;
+}
+
+.table-dark {
+ --bs-table-bg: #303030;
+ --bs-table-striped-bg: #3a3a3a;
+ --bs-table-striped-color: #fff;
+ --bs-table-active-bg: #454545;
+ --bs-table-active-color: #fff;
+ --bs-table-hover-bg: #404040;
+ --bs-table-hover-color: #fff;
+ color: #fff;
+ border-color: #454545;
+}
+
+.table-responsive {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+}
+
+@media (max-width: 575.98px) {
+ .table-responsive-sm {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+}
+
+@media (max-width: 767.98px) {
+ .table-responsive-md {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+}
+
+@media (max-width: 991.98px) {
+ .table-responsive-lg {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+}
+
+@media (max-width: 1199.98px) {
+ .table-responsive-xl {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+}
+
+@media (max-width: 1399.98px) {
+ .table-responsive-xxl {
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+}
+
+.form-label {
+ margin-bottom: 0.5rem;
+}
+
+.col-form-label {
+ padding-top: calc(0.375rem + 1px);
+ padding-bottom: calc(0.375rem + 1px);
+ margin-bottom: 0;
+ font-size: inherit;
+ line-height: 1.5;
+}
+
+.col-form-label-lg {
+ padding-top: calc(0.5rem + 1px);
+ padding-bottom: calc(0.5rem + 1px);
+ font-size: 1.25rem;
+}
+
+.col-form-label-sm {
+ padding-top: calc(0.25rem + 1px);
+ padding-bottom: calc(0.25rem + 1px);
+ font-size: 0.875rem;
+}
+
+.form-text {
+ margin-top: 0.25rem;
+ font-size: 0.875em;
+ color: #888;
+}
+
+.form-control {
+ display: block;
+ width: 100%;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #303030;
+ background-color: #fff;
+ background-clip: padding-box;
+ border: 1px solid #222;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+ border-radius: 0.25rem;
+ transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-control {
+ transition: none;
+ }
+}
+
+.form-control[type="file"] {
+ overflow: hidden;
+}
+
+.form-control[type="file"]:not(:disabled):not([readonly]) {
+ cursor: pointer;
+}
+
+.form-control:focus {
+ color: #303030;
+ background-color: #fff;
+ border-color: #9badbf;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.form-control::-webkit-date-and-time-value {
+ height: 1.5em;
+}
+
+.form-control::-webkit-input-placeholder {
+ color: #888;
+ opacity: 1;
+}
+
+.form-control::-moz-placeholder {
+ color: #888;
+ opacity: 1;
+}
+
+.form-control:-ms-input-placeholder {
+ color: #888;
+ opacity: 1;
+}
+
+.form-control::-ms-input-placeholder {
+ color: #888;
+ opacity: 1;
+}
+
+.form-control::placeholder {
+ color: #888;
+ opacity: 1;
+}
+
+.form-control:disabled, .form-control[readonly] {
+ background-color: #ebebeb;
+ opacity: 1;
+}
+
+.form-control::file-selector-button {
+ padding: 0.375rem 0.75rem;
+ margin: -0.375rem -0.75rem;
+ -webkit-margin-end: 0.75rem;
+ -moz-margin-end: 0.75rem;
+ margin-inline-end: 0.75rem;
+ color: #fff;
+ background-color: #444;
+ pointer-events: none;
+ border-color: inherit;
+ border-style: solid;
+ border-width: 0;
+ border-inline-end-width: 1px;
+ border-radius: 0;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-control::file-selector-button {
+ transition: none;
+ }
+}
+
+.form-control:hover:not(:disabled):not([readonly])::file-selector-button {
+ background-color: #414141;
+}
+
+.form-control::-webkit-file-upload-button {
+ padding: 0.375rem 0.75rem;
+ margin: -0.375rem -0.75rem;
+ -webkit-margin-end: 0.75rem;
+ margin-inline-end: 0.75rem;
+ color: #fff;
+ background-color: #444;
+ pointer-events: none;
+ border-color: inherit;
+ border-style: solid;
+ border-width: 0;
+ border-inline-end-width: 1px;
+ border-radius: 0;
+ -webkit-transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-control::-webkit-file-upload-button {
+ -webkit-transition: none;
+ transition: none;
+ }
+}
+
+.form-control:hover:not(:disabled):not([readonly])::-webkit-file-upload-button {
+ background-color: #414141;
+}
+
+.form-control-plaintext {
+ display: block;
+ width: 100%;
+ padding: 0.375rem 0;
+ margin-bottom: 0;
+ line-height: 1.5;
+ color: #fff;
+ background-color: transparent;
+ border: solid transparent;
+ border-width: 1px 0;
+}
+
+.form-control-plaintext.form-control-sm, .form-control-plaintext.form-control-lg {
+ padding-right: 0;
+ padding-left: 0;
+}
+
+.form-control-sm {
+ min-height: calc(1.5em + 0.5rem + 2px);
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+ border-radius: 0.2rem;
+}
+
+.form-control-sm::file-selector-button {
+ padding: 0.25rem 0.5rem;
+ margin: -0.25rem -0.5rem;
+ -webkit-margin-end: 0.5rem;
+ -moz-margin-end: 0.5rem;
+ margin-inline-end: 0.5rem;
+}
+
+.form-control-sm::-webkit-file-upload-button {
+ padding: 0.25rem 0.5rem;
+ margin: -0.25rem -0.5rem;
+ -webkit-margin-end: 0.5rem;
+ margin-inline-end: 0.5rem;
+}
+
+.form-control-lg {
+ min-height: calc(1.5em + 1rem + 2px);
+ padding: 0.5rem 1rem;
+ font-size: 1.25rem;
+ border-radius: 0.3rem;
+}
+
+.form-control-lg::file-selector-button {
+ padding: 0.5rem 1rem;
+ margin: -0.5rem -1rem;
+ -webkit-margin-end: 1rem;
+ -moz-margin-end: 1rem;
+ margin-inline-end: 1rem;
+}
+
+.form-control-lg::-webkit-file-upload-button {
+ padding: 0.5rem 1rem;
+ margin: -0.5rem -1rem;
+ -webkit-margin-end: 1rem;
+ margin-inline-end: 1rem;
+}
+
+textarea.form-control {
+ min-height: calc(1.5em + 0.75rem + 2px);
+}
+
+textarea.form-control-sm {
+ min-height: calc(1.5em + 0.5rem + 2px);
+}
+
+textarea.form-control-lg {
+ min-height: calc(1.5em + 1rem + 2px);
+}
+
+.form-control-color {
+ max-width: 3rem;
+ height: auto;
+ padding: 0.375rem;
+}
+
+.form-control-color:not(:disabled):not([readonly]) {
+ cursor: pointer;
+}
+
+.form-control-color::-moz-color-swatch {
+ height: 1.5em;
+ border-radius: 0.25rem;
+}
+
+.form-control-color::-webkit-color-swatch {
+ height: 1.5em;
+ border-radius: 0.25rem;
+}
+
+.form-select {
+ display: block;
+ width: 100%;
+ padding: 0.375rem 2.25rem 0.375rem 0.75rem;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #303030;
+ background-color: #fff;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23303030' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-position: right 0.75rem center;
+ background-size: 16px 12px;
+ border: 1px solid #222;
+ border-radius: 0.25rem;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+}
+
+.form-select:focus {
+ border-color: #9badbf;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.form-select[multiple], .form-select[size]:not([size="1"]) {
+ padding-right: 0.75rem;
+ background-image: none;
+}
+
+.form-select:disabled {
+ background-color: #ebebeb;
+}
+
+.form-select:-moz-focusring {
+ color: transparent;
+ text-shadow: 0 0 0 #303030;
+}
+
+.form-select-sm {
+ padding-top: 0.25rem;
+ padding-bottom: 0.25rem;
+ padding-left: 0.5rem;
+ font-size: 0.875rem;
+}
+
+.form-select-lg {
+ padding-top: 0.5rem;
+ padding-bottom: 0.5rem;
+ padding-left: 1rem;
+ font-size: 1.25rem;
+}
+
+.form-check {
+ display: block;
+ min-height: 1.5rem;
+ padding-left: 1.5em;
+ margin-bottom: 0.125rem;
+}
+
+.form-check .form-check-input {
+ float: left;
+ margin-left: -1.5em;
+}
+
+.form-check-input {
+ width: 1em;
+ height: 1em;
+ margin-top: 0.25em;
+ vertical-align: top;
+ background-color: #fff;
+ background-repeat: no-repeat;
+ background-position: center;
+ background-size: contain;
+ border: none;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+ -webkit-print-color-adjust: exact;
+ color-adjust: exact;
+}
+
+.form-check-input[type="checkbox"] {
+ border-radius: 0.25em;
+}
+
+.form-check-input[type="radio"] {
+ border-radius: 50%;
+}
+
+.form-check-input:active {
+ -webkit-filter: brightness(90%);
+ filter: brightness(90%);
+}
+
+.form-check-input:focus {
+ border-color: #9badbf;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.form-check-input:checked {
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.form-check-input:checked[type="checkbox"] {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10l3 3l6-6'/%3e%3c/svg%3e");
+}
+
+.form-check-input:checked[type="radio"] {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='2' fill='%23fff'/%3e%3c/svg%3e");
+}
+
+.form-check-input[type="checkbox"]:indeterminate {
+ background-color: #375a7f;
+ border-color: #375a7f;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/%3e%3c/svg%3e");
+}
+
+.form-check-input:disabled {
+ pointer-events: none;
+ -webkit-filter: none;
+ filter: none;
+ opacity: 0.5;
+}
+
+.form-check-input[disabled] ~ .form-check-label, .form-check-input:disabled ~ .form-check-label {
+ opacity: 0.5;
+}
+
+.form-switch {
+ padding-left: 2.5em;
+}
+
+.form-switch .form-check-input {
+ width: 2em;
+ margin-left: -2.5em;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");
+ background-position: left center;
+ border-radius: 2em;
+ transition: background-position 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-switch .form-check-input {
+ transition: none;
+ }
+}
+
+.form-switch .form-check-input:focus {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%239badbf'/%3e%3c/svg%3e");
+}
+
+.form-switch .form-check-input:checked {
+ background-position: right center;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
+}
+
+.form-check-inline {
+ display: inline-block;
+ margin-right: 1rem;
+}
+
+.btn-check {
+ position: absolute;
+ clip: rect(0, 0, 0, 0);
+ pointer-events: none;
+}
+
+.btn-check[disabled] + .btn, .btn-check:disabled + .btn {
+ pointer-events: none;
+ -webkit-filter: none;
+ filter: none;
+ opacity: 0.65;
+}
+
+.form-range {
+ width: 100%;
+ height: 1.5rem;
+ padding: 0;
+ background-color: transparent;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+}
+
+.form-range:focus {
+ outline: 0;
+}
+
+.form-range:focus::-webkit-slider-thumb {
+ box-shadow: 0 0 0 1px #222, 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.form-range:focus::-moz-range-thumb {
+ box-shadow: 0 0 0 1px #222, 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.form-range::-moz-focus-outer {
+ border: 0;
+}
+
+.form-range::-webkit-slider-thumb {
+ width: 1rem;
+ height: 1rem;
+ margin-top: -0.25rem;
+ background-color: #375a7f;
+ border: 0;
+ border-radius: 1rem;
+ -webkit-transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ -webkit-appearance: none;
+ appearance: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-range::-webkit-slider-thumb {
+ -webkit-transition: none;
+ transition: none;
+ }
+}
+
+.form-range::-webkit-slider-thumb:active {
+ background-color: #c3ced9;
+}
+
+.form-range::-webkit-slider-runnable-track {
+ width: 100%;
+ height: 0.5rem;
+ color: transparent;
+ cursor: pointer;
+ background-color: #dee2e6;
+ border-color: transparent;
+ border-radius: 1rem;
+}
+
+.form-range::-moz-range-thumb {
+ width: 1rem;
+ height: 1rem;
+ background-color: #375a7f;
+ border: 0;
+ border-radius: 1rem;
+ -moz-transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ -moz-appearance: none;
+ appearance: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-range::-moz-range-thumb {
+ -moz-transition: none;
+ transition: none;
+ }
+}
+
+.form-range::-moz-range-thumb:active {
+ background-color: #c3ced9;
+}
+
+.form-range::-moz-range-track {
+ width: 100%;
+ height: 0.5rem;
+ color: transparent;
+ cursor: pointer;
+ background-color: #dee2e6;
+ border-color: transparent;
+ border-radius: 1rem;
+}
+
+.form-range:disabled {
+ pointer-events: none;
+}
+
+.form-range:disabled::-webkit-slider-thumb {
+ background-color: #adb5bd;
+}
+
+.form-range:disabled::-moz-range-thumb {
+ background-color: #adb5bd;
+}
+
+.form-floating {
+ position: relative;
+}
+
+.form-floating > .form-control,
+.form-floating > .form-select {
+ height: calc(3.5rem + 2px);
+ padding: 1rem 0.75rem;
+}
+
+.form-floating > label {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ padding: 1rem 0.75rem;
+ pointer-events: none;
+ border: 1px solid transparent;
+ -webkit-transform-origin: 0 0;
+ transform-origin: 0 0;
+ transition: opacity 0.1s ease-in-out, -webkit-transform 0.1s ease-in-out;
+ transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out;
+ transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out, -webkit-transform 0.1s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .form-floating > label {
+ transition: none;
+ }
+}
+
+.form-floating > .form-control::-webkit-input-placeholder {
+ color: transparent;
+}
+
+.form-floating > .form-control::-moz-placeholder {
+ color: transparent;
+}
+
+.form-floating > .form-control:-ms-input-placeholder {
+ color: transparent;
+}
+
+.form-floating > .form-control::-ms-input-placeholder {
+ color: transparent;
+}
+
+.form-floating > .form-control::placeholder {
+ color: transparent;
+}
+
+.form-floating > .form-control:not(:-moz-placeholder-shown) {
+ padding-top: 1.625rem;
+ padding-bottom: 0.625rem;
+}
+
+.form-floating > .form-control:not(:-ms-input-placeholder) {
+ padding-top: 1.625rem;
+ padding-bottom: 0.625rem;
+}
+
+.form-floating > .form-control:focus, .form-floating > .form-control:not(:placeholder-shown) {
+ padding-top: 1.625rem;
+ padding-bottom: 0.625rem;
+}
+
+.form-floating > .form-control:-webkit-autofill {
+ padding-top: 1.625rem;
+ padding-bottom: 0.625rem;
+}
+
+.form-floating > .form-select {
+ padding-top: 1.625rem;
+ padding-bottom: 0.625rem;
+}
+
+.form-floating > .form-control:not(:-moz-placeholder-shown) ~ label {
+ opacity: 0.65;
+ transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+}
+
+.form-floating > .form-control:not(:-ms-input-placeholder) ~ label {
+ opacity: 0.65;
+ transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+}
+
+.form-floating > .form-control:focus ~ label,
+.form-floating > .form-control:not(:placeholder-shown) ~ label,
+.form-floating > .form-select ~ label {
+ opacity: 0.65;
+ -webkit-transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+ transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+}
+
+.form-floating > .form-control:-webkit-autofill ~ label {
+ opacity: 0.65;
+ -webkit-transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+ transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
+}
+
+.input-group {
+ position: relative;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ -ms-flex-align: stretch;
+ align-items: stretch;
+ width: 100%;
+}
+
+.input-group > .form-control,
+.input-group > .form-select {
+ position: relative;
+ -ms-flex: 1 1 auto;
+ flex: 1 1 auto;
+ width: 1%;
+ min-width: 0;
+}
+
+.input-group > .form-control:focus,
+.input-group > .form-select:focus {
+ z-index: 3;
+}
+
+.input-group .btn {
+ position: relative;
+ z-index: 2;
+}
+
+.input-group .btn:focus {
+ z-index: 3;
+}
+
+.input-group-text {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #adb5bd;
+ text-align: center;
+ white-space: nowrap;
+ background-color: #444;
+ border: 1px solid #222;
+ border-radius: 0.25rem;
+}
+
+.input-group-lg > .form-control,
+.input-group-lg > .form-select,
+.input-group-lg > .input-group-text,
+.input-group-lg > .btn {
+ padding: 0.5rem 1rem;
+ font-size: 1.25rem;
+ border-radius: 0.3rem;
+}
+
+.input-group-sm > .form-control,
+.input-group-sm > .form-select,
+.input-group-sm > .input-group-text,
+.input-group-sm > .btn {
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+ border-radius: 0.2rem;
+}
+
+.input-group-lg > .form-select,
+.input-group-sm > .form-select {
+ padding-right: 3rem;
+}
+
+.input-group:not(.has-validation) > :not(:last-child):not(.dropdown-toggle):not(.dropdown-menu),
+.input-group:not(.has-validation) > .dropdown-toggle:nth-last-child(n + 3) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+.input-group.has-validation > :nth-last-child(n + 3):not(.dropdown-toggle):not(.dropdown-menu),
+.input-group.has-validation > .dropdown-toggle:nth-last-child(n + 4) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+.input-group > :not(:first-child):not(.dropdown-menu):not(.valid-tooltip):not(.valid-feedback):not(.invalid-tooltip):not(.invalid-feedback) {
+ margin-left: -1px;
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+
+.valid-feedback {
+ display: none;
+ width: 100%;
+ margin-top: 0.25rem;
+ font-size: 0.875em;
+ color: #00bc8c;
+}
+
+.valid-tooltip {
+ position: absolute;
+ top: 100%;
+ z-index: 5;
+ display: none;
+ max-width: 100%;
+ padding: 0.25rem 0.5rem;
+ margin-top: .1rem;
+ font-size: 0.875rem;
+ color: #fff;
+ background-color: rgba(0, 188, 140, 0.9);
+ border-radius: 0.25rem;
+}
+
+.was-validated :valid ~ .valid-feedback,
+.was-validated :valid ~ .valid-tooltip,
+.is-valid ~ .valid-feedback,
+.is-valid ~ .valid-tooltip {
+ display: block;
+}
+
+.was-validated .form-control:valid, .form-control.is-valid {
+ border-color: #00bc8c;
+ padding-right: calc(1.5em + 0.75rem);
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2300bc8c' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-position: right calc(0.375em + 0.1875rem) center;
+ background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
+}
+
+.was-validated .form-control:valid:focus, .form-control.is-valid:focus {
+ border-color: #00bc8c;
+ box-shadow: 0 0 0 0.25rem rgba(0, 188, 140, 0.25);
+}
+
+.was-validated textarea.form-control:valid, textarea.form-control.is-valid {
+ padding-right: calc(1.5em + 0.75rem);
+ background-position: top calc(0.375em + 0.1875rem) right calc(0.375em + 0.1875rem);
+}
+
+.was-validated .form-select:valid, .form-select.is-valid {
+ border-color: #00bc8c;
+}
+
+.was-validated .form-select:valid:not([multiple]):not([size]), .was-validated .form-select:valid:not([multiple])[size="1"], .form-select.is-valid:not([multiple]):not([size]), .form-select.is-valid:not([multiple])[size="1"] {
+ padding-right: 4.125rem;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23303030' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e"), url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2300bc8c' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
+ background-position: right 0.75rem center, center right 2.25rem;
+ background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
+}
+
+.was-validated .form-select:valid:focus, .form-select.is-valid:focus {
+ border-color: #00bc8c;
+ box-shadow: 0 0 0 0.25rem rgba(0, 188, 140, 0.25);
+}
+
+.was-validated .form-check-input:valid, .form-check-input.is-valid {
+ border-color: #00bc8c;
+}
+
+.was-validated .form-check-input:valid:checked, .form-check-input.is-valid:checked {
+ background-color: #00bc8c;
+}
+
+.was-validated .form-check-input:valid:focus, .form-check-input.is-valid:focus {
+ box-shadow: 0 0 0 0.25rem rgba(0, 188, 140, 0.25);
+}
+
+.was-validated .form-check-input:valid ~ .form-check-label, .form-check-input.is-valid ~ .form-check-label {
+ color: #00bc8c;
+}
+
+.form-check-inline .form-check-input ~ .valid-feedback {
+ margin-left: .5em;
+}
+
+.was-validated .input-group .form-control:valid, .input-group .form-control.is-valid, .was-validated
+.input-group .form-select:valid,
+.input-group .form-select.is-valid {
+ z-index: 1;
+}
+
+.was-validated .input-group .form-control:valid:focus, .input-group .form-control.is-valid:focus, .was-validated
+.input-group .form-select:valid:focus,
+.input-group .form-select.is-valid:focus {
+ z-index: 3;
+}
+
+.invalid-feedback {
+ display: none;
+ width: 100%;
+ margin-top: 0.25rem;
+ font-size: 0.875em;
+ color: #e74c3c;
+}
+
+.invalid-tooltip {
+ position: absolute;
+ top: 100%;
+ z-index: 5;
+ display: none;
+ max-width: 100%;
+ padding: 0.25rem 0.5rem;
+ margin-top: .1rem;
+ font-size: 0.875rem;
+ color: #fff;
+ background-color: rgba(231, 76, 60, 0.9);
+ border-radius: 0.25rem;
+}
+
+.was-validated :invalid ~ .invalid-feedback,
+.was-validated :invalid ~ .invalid-tooltip,
+.is-invalid ~ .invalid-feedback,
+.is-invalid ~ .invalid-tooltip {
+ display: block;
+}
+
+.was-validated .form-control:invalid, .form-control.is-invalid {
+ border-color: #e74c3c;
+ padding-right: calc(1.5em + 0.75rem);
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23e74c3c'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23e74c3c' stroke='none'/%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-position: right calc(0.375em + 0.1875rem) center;
+ background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
+}
+
+.was-validated .form-control:invalid:focus, .form-control.is-invalid:focus {
+ border-color: #e74c3c;
+ box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.25);
+}
+
+.was-validated textarea.form-control:invalid, textarea.form-control.is-invalid {
+ padding-right: calc(1.5em + 0.75rem);
+ background-position: top calc(0.375em + 0.1875rem) right calc(0.375em + 0.1875rem);
+}
+
+.was-validated .form-select:invalid, .form-select.is-invalid {
+ border-color: #e74c3c;
+}
+
+.was-validated .form-select:invalid:not([multiple]):not([size]), .was-validated .form-select:invalid:not([multiple])[size="1"], .form-select.is-invalid:not([multiple]):not([size]), .form-select.is-invalid:not([multiple])[size="1"] {
+ padding-right: 4.125rem;
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23303030' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e"), url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23e74c3c'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23e74c3c' stroke='none'/%3e%3c/svg%3e");
+ background-position: right 0.75rem center, center right 2.25rem;
+ background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
+}
+
+.was-validated .form-select:invalid:focus, .form-select.is-invalid:focus {
+ border-color: #e74c3c;
+ box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.25);
+}
+
+.was-validated .form-check-input:invalid, .form-check-input.is-invalid {
+ border-color: #e74c3c;
+}
+
+.was-validated .form-check-input:invalid:checked, .form-check-input.is-invalid:checked {
+ background-color: #e74c3c;
+}
+
+.was-validated .form-check-input:invalid:focus, .form-check-input.is-invalid:focus {
+ box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.25);
+}
+
+.was-validated .form-check-input:invalid ~ .form-check-label, .form-check-input.is-invalid ~ .form-check-label {
+ color: #e74c3c;
+}
+
+.form-check-inline .form-check-input ~ .invalid-feedback {
+ margin-left: .5em;
+}
+
+.was-validated .input-group .form-control:invalid, .input-group .form-control.is-invalid, .was-validated
+.input-group .form-select:invalid,
+.input-group .form-select.is-invalid {
+ z-index: 2;
+}
+
+.was-validated .input-group .form-control:invalid:focus, .input-group .form-control.is-invalid:focus, .was-validated
+.input-group .form-select:invalid:focus,
+.input-group .form-select.is-invalid:focus {
+ z-index: 3;
+}
+
+.btn {
+ display: inline-block;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #fff;
+ text-align: center;
+ text-decoration: none;
+ vertical-align: middle;
+ cursor: pointer;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ background-color: transparent;
+ border: 1px solid transparent;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ border-radius: 0.25rem;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .btn {
+ transition: none;
+ }
+}
+
+.btn:hover {
+ color: #fff;
+}
+
+.btn-check:focus + .btn, .btn:focus {
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.btn:disabled, .btn.disabled,
+fieldset:disabled .btn {
+ pointer-events: none;
+ opacity: 0.65;
+}
+
+.btn-primary {
+ color: #fff;
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.btn-primary:hover {
+ color: #fff;
+ background-color: #2f4d6c;
+ border-color: #2c4866;
+}
+
+.btn-check:focus + .btn-primary, .btn-primary:focus {
+ color: #fff;
+ background-color: #2f4d6c;
+ border-color: #2c4866;
+ box-shadow: 0 0 0 0.25rem rgba(85, 115, 146, 0.5);
+}
+
+.btn-check:checked + .btn-primary,
+.btn-check:active + .btn-primary, .btn-primary:active, .btn-primary.active,
+.show > .btn-primary.dropdown-toggle {
+ color: #fff;
+ background-color: #2c4866;
+ border-color: #29445f;
+}
+
+.btn-check:checked + .btn-primary:focus,
+.btn-check:active + .btn-primary:focus, .btn-primary:active:focus, .btn-primary.active:focus,
+.show > .btn-primary.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(85, 115, 146, 0.5);
+}
+
+.btn-primary:disabled, .btn-primary.disabled {
+ color: #fff;
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.btn-secondary {
+ color: #fff;
+ background-color: #444;
+ border-color: #444;
+}
+
+.btn-secondary:hover {
+ color: #fff;
+ background-color: #3a3a3a;
+ border-color: #363636;
+}
+
+.btn-check:focus + .btn-secondary, .btn-secondary:focus {
+ color: #fff;
+ background-color: #3a3a3a;
+ border-color: #363636;
+ box-shadow: 0 0 0 0.25rem rgba(96, 96, 96, 0.5);
+}
+
+.btn-check:checked + .btn-secondary,
+.btn-check:active + .btn-secondary, .btn-secondary:active, .btn-secondary.active,
+.show > .btn-secondary.dropdown-toggle {
+ color: #fff;
+ background-color: #363636;
+ border-color: #333333;
+}
+
+.btn-check:checked + .btn-secondary:focus,
+.btn-check:active + .btn-secondary:focus, .btn-secondary:active:focus, .btn-secondary.active:focus,
+.show > .btn-secondary.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(96, 96, 96, 0.5);
+}
+
+.btn-secondary:disabled, .btn-secondary.disabled {
+ color: #fff;
+ background-color: #444;
+ border-color: #444;
+}
+
+.btn-success {
+ color: #fff;
+ background-color: #00bc8c;
+ border-color: #00bc8c;
+}
+
+.btn-success:hover {
+ color: #fff;
+ background-color: #00a077;
+ border-color: #009670;
+}
+
+.btn-check:focus + .btn-success, .btn-success:focus {
+ color: #fff;
+ background-color: #00a077;
+ border-color: #009670;
+ box-shadow: 0 0 0 0.25rem rgba(38, 198, 157, 0.5);
+}
+
+.btn-check:checked + .btn-success,
+.btn-check:active + .btn-success, .btn-success:active, .btn-success.active,
+.show > .btn-success.dropdown-toggle {
+ color: #fff;
+ background-color: #009670;
+ border-color: #008d69;
+}
+
+.btn-check:checked + .btn-success:focus,
+.btn-check:active + .btn-success:focus, .btn-success:active:focus, .btn-success.active:focus,
+.show > .btn-success.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(38, 198, 157, 0.5);
+}
+
+.btn-success:disabled, .btn-success.disabled {
+ color: #fff;
+ background-color: #00bc8c;
+ border-color: #00bc8c;
+}
+
+.btn-info {
+ color: #fff;
+ background-color: #3498db;
+ border-color: #3498db;
+}
+
+.btn-info:hover {
+ color: #fff;
+ background-color: #2c81ba;
+ border-color: #2a7aaf;
+}
+
+.btn-check:focus + .btn-info, .btn-info:focus {
+ color: #fff;
+ background-color: #2c81ba;
+ border-color: #2a7aaf;
+ box-shadow: 0 0 0 0.25rem rgba(82, 167, 224, 0.5);
+}
+
+.btn-check:checked + .btn-info,
+.btn-check:active + .btn-info, .btn-info:active, .btn-info.active,
+.show > .btn-info.dropdown-toggle {
+ color: #fff;
+ background-color: #2a7aaf;
+ border-color: #2772a4;
+}
+
+.btn-check:checked + .btn-info:focus,
+.btn-check:active + .btn-info:focus, .btn-info:active:focus, .btn-info.active:focus,
+.show > .btn-info.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(82, 167, 224, 0.5);
+}
+
+.btn-info:disabled, .btn-info.disabled {
+ color: #fff;
+ background-color: #3498db;
+ border-color: #3498db;
+}
+
+.btn-warning {
+ color: #fff;
+ background-color: #f39c12;
+ border-color: #f39c12;
+}
+
+.btn-warning:hover {
+ color: #fff;
+ background-color: #cf850f;
+ border-color: #c27d0e;
+}
+
+.btn-check:focus + .btn-warning, .btn-warning:focus {
+ color: #fff;
+ background-color: #cf850f;
+ border-color: #c27d0e;
+ box-shadow: 0 0 0 0.25rem rgba(245, 171, 54, 0.5);
+}
+
+.btn-check:checked + .btn-warning,
+.btn-check:active + .btn-warning, .btn-warning:active, .btn-warning.active,
+.show > .btn-warning.dropdown-toggle {
+ color: #fff;
+ background-color: #c27d0e;
+ border-color: #b6750e;
+}
+
+.btn-check:checked + .btn-warning:focus,
+.btn-check:active + .btn-warning:focus, .btn-warning:active:focus, .btn-warning.active:focus,
+.show > .btn-warning.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(245, 171, 54, 0.5);
+}
+
+.btn-warning:disabled, .btn-warning.disabled {
+ color: #fff;
+ background-color: #f39c12;
+ border-color: #f39c12;
+}
+
+.btn-danger {
+ color: #fff;
+ background-color: #e74c3c;
+ border-color: #e74c3c;
+}
+
+.btn-danger:hover {
+ color: #fff;
+ background-color: #c44133;
+ border-color: #b93d30;
+}
+
+.btn-check:focus + .btn-danger, .btn-danger:focus {
+ color: #fff;
+ background-color: #c44133;
+ border-color: #b93d30;
+ box-shadow: 0 0 0 0.25rem rgba(235, 103, 89, 0.5);
+}
+
+.btn-check:checked + .btn-danger,
+.btn-check:active + .btn-danger, .btn-danger:active, .btn-danger.active,
+.show > .btn-danger.dropdown-toggle {
+ color: #fff;
+ background-color: #b93d30;
+ border-color: #ad392d;
+}
+
+.btn-check:checked + .btn-danger:focus,
+.btn-check:active + .btn-danger:focus, .btn-danger:active:focus, .btn-danger.active:focus,
+.show > .btn-danger.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(235, 103, 89, 0.5);
+}
+
+.btn-danger:disabled, .btn-danger.disabled {
+ color: #fff;
+ background-color: #e74c3c;
+ border-color: #e74c3c;
+}
+
+.btn-light {
+ color: #000;
+ background-color: #adb5bd;
+ border-color: #adb5bd;
+}
+
+.btn-light:hover {
+ color: #000;
+ background-color: #b9c0c7;
+ border-color: #b5bcc4;
+}
+
+.btn-check:focus + .btn-light, .btn-light:focus {
+ color: #000;
+ background-color: #b9c0c7;
+ border-color: #b5bcc4;
+ box-shadow: 0 0 0 0.25rem rgba(147, 154, 161, 0.5);
+}
+
+.btn-check:checked + .btn-light,
+.btn-check:active + .btn-light, .btn-light:active, .btn-light.active,
+.show > .btn-light.dropdown-toggle {
+ color: #000;
+ background-color: #bdc4ca;
+ border-color: #b5bcc4;
+}
+
+.btn-check:checked + .btn-light:focus,
+.btn-check:active + .btn-light:focus, .btn-light:active:focus, .btn-light.active:focus,
+.show > .btn-light.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(147, 154, 161, 0.5);
+}
+
+.btn-light:disabled, .btn-light.disabled {
+ color: #000;
+ background-color: #adb5bd;
+ border-color: #adb5bd;
+}
+
+.btn-dark {
+ color: #fff;
+ background-color: #303030;
+ border-color: #303030;
+}
+
+.btn-dark:hover {
+ color: #fff;
+ background-color: #292929;
+ border-color: #262626;
+}
+
+.btn-check:focus + .btn-dark, .btn-dark:focus {
+ color: #fff;
+ background-color: #292929;
+ border-color: #262626;
+ box-shadow: 0 0 0 0.25rem rgba(79, 79, 79, 0.5);
+}
+
+.btn-check:checked + .btn-dark,
+.btn-check:active + .btn-dark, .btn-dark:active, .btn-dark.active,
+.show > .btn-dark.dropdown-toggle {
+ color: #fff;
+ background-color: #262626;
+ border-color: #242424;
+}
+
+.btn-check:checked + .btn-dark:focus,
+.btn-check:active + .btn-dark:focus, .btn-dark:active:focus, .btn-dark.active:focus,
+.show > .btn-dark.dropdown-toggle:focus {
+ box-shadow: 0 0 0 0.25rem rgba(79, 79, 79, 0.5);
+}
+
+.btn-dark:disabled, .btn-dark.disabled {
+ color: #fff;
+ background-color: #303030;
+ border-color: #303030;
+}
+
+.btn-outline-primary {
+ color: #375a7f;
+ border-color: #375a7f;
+}
+
+.btn-outline-primary:hover {
+ color: #fff;
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.btn-check:focus + .btn-outline-primary, .btn-outline-primary:focus {
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.5);
+}
+
+.btn-check:checked + .btn-outline-primary,
+.btn-check:active + .btn-outline-primary, .btn-outline-primary:active, .btn-outline-primary.active, .btn-outline-primary.dropdown-toggle.show {
+ color: #fff;
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.btn-check:checked + .btn-outline-primary:focus,
+.btn-check:active + .btn-outline-primary:focus, .btn-outline-primary:active:focus, .btn-outline-primary.active:focus, .btn-outline-primary.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.5);
+}
+
+.btn-outline-primary:disabled, .btn-outline-primary.disabled {
+ color: #375a7f;
+ background-color: transparent;
+}
+
+.btn-outline-secondary {
+ color: #444;
+ border-color: #444;
+}
+
+.btn-outline-secondary:hover {
+ color: #fff;
+ background-color: #444;
+ border-color: #444;
+}
+
+.btn-check:focus + .btn-outline-secondary, .btn-outline-secondary:focus {
+ box-shadow: 0 0 0 0.25rem rgba(68, 68, 68, 0.5);
+}
+
+.btn-check:checked + .btn-outline-secondary,
+.btn-check:active + .btn-outline-secondary, .btn-outline-secondary:active, .btn-outline-secondary.active, .btn-outline-secondary.dropdown-toggle.show {
+ color: #fff;
+ background-color: #444;
+ border-color: #444;
+}
+
+.btn-check:checked + .btn-outline-secondary:focus,
+.btn-check:active + .btn-outline-secondary:focus, .btn-outline-secondary:active:focus, .btn-outline-secondary.active:focus, .btn-outline-secondary.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(68, 68, 68, 0.5);
+}
+
+.btn-outline-secondary:disabled, .btn-outline-secondary.disabled {
+ color: #444;
+ background-color: transparent;
+}
+
+.btn-outline-success {
+ color: #00bc8c;
+ border-color: #00bc8c;
+}
+
+.btn-outline-success:hover {
+ color: #fff;
+ background-color: #00bc8c;
+ border-color: #00bc8c;
+}
+
+.btn-check:focus + .btn-outline-success, .btn-outline-success:focus {
+ box-shadow: 0 0 0 0.25rem rgba(0, 188, 140, 0.5);
+}
+
+.btn-check:checked + .btn-outline-success,
+.btn-check:active + .btn-outline-success, .btn-outline-success:active, .btn-outline-success.active, .btn-outline-success.dropdown-toggle.show {
+ color: #fff;
+ background-color: #00bc8c;
+ border-color: #00bc8c;
+}
+
+.btn-check:checked + .btn-outline-success:focus,
+.btn-check:active + .btn-outline-success:focus, .btn-outline-success:active:focus, .btn-outline-success.active:focus, .btn-outline-success.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(0, 188, 140, 0.5);
+}
+
+.btn-outline-success:disabled, .btn-outline-success.disabled {
+ color: #00bc8c;
+ background-color: transparent;
+}
+
+.btn-outline-info {
+ color: #3498db;
+ border-color: #3498db;
+}
+
+.btn-outline-info:hover {
+ color: #fff;
+ background-color: #3498db;
+ border-color: #3498db;
+}
+
+.btn-check:focus + .btn-outline-info, .btn-outline-info:focus {
+ box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.5);
+}
+
+.btn-check:checked + .btn-outline-info,
+.btn-check:active + .btn-outline-info, .btn-outline-info:active, .btn-outline-info.active, .btn-outline-info.dropdown-toggle.show {
+ color: #fff;
+ background-color: #3498db;
+ border-color: #3498db;
+}
+
+.btn-check:checked + .btn-outline-info:focus,
+.btn-check:active + .btn-outline-info:focus, .btn-outline-info:active:focus, .btn-outline-info.active:focus, .btn-outline-info.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.5);
+}
+
+.btn-outline-info:disabled, .btn-outline-info.disabled {
+ color: #3498db;
+ background-color: transparent;
+}
+
+.btn-outline-warning {
+ color: #f39c12;
+ border-color: #f39c12;
+}
+
+.btn-outline-warning:hover {
+ color: #fff;
+ background-color: #f39c12;
+ border-color: #f39c12;
+}
+
+.btn-check:focus + .btn-outline-warning, .btn-outline-warning:focus {
+ box-shadow: 0 0 0 0.25rem rgba(243, 156, 18, 0.5);
+}
+
+.btn-check:checked + .btn-outline-warning,
+.btn-check:active + .btn-outline-warning, .btn-outline-warning:active, .btn-outline-warning.active, .btn-outline-warning.dropdown-toggle.show {
+ color: #fff;
+ background-color: #f39c12;
+ border-color: #f39c12;
+}
+
+.btn-check:checked + .btn-outline-warning:focus,
+.btn-check:active + .btn-outline-warning:focus, .btn-outline-warning:active:focus, .btn-outline-warning.active:focus, .btn-outline-warning.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(243, 156, 18, 0.5);
+}
+
+.btn-outline-warning:disabled, .btn-outline-warning.disabled {
+ color: #f39c12;
+ background-color: transparent;
+}
+
+.btn-outline-danger {
+ color: #e74c3c;
+ border-color: #e74c3c;
+}
+
+.btn-outline-danger:hover {
+ color: #fff;
+ background-color: #e74c3c;
+ border-color: #e74c3c;
+}
+
+.btn-check:focus + .btn-outline-danger, .btn-outline-danger:focus {
+ box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.5);
+}
+
+.btn-check:checked + .btn-outline-danger,
+.btn-check:active + .btn-outline-danger, .btn-outline-danger:active, .btn-outline-danger.active, .btn-outline-danger.dropdown-toggle.show {
+ color: #fff;
+ background-color: #e74c3c;
+ border-color: #e74c3c;
+}
+
+.btn-check:checked + .btn-outline-danger:focus,
+.btn-check:active + .btn-outline-danger:focus, .btn-outline-danger:active:focus, .btn-outline-danger.active:focus, .btn-outline-danger.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.5);
+}
+
+.btn-outline-danger:disabled, .btn-outline-danger.disabled {
+ color: #e74c3c;
+ background-color: transparent;
+}
+
+.btn-outline-light {
+ color: #adb5bd;
+ border-color: #adb5bd;
+}
+
+.btn-outline-light:hover {
+ color: #000;
+ background-color: #adb5bd;
+ border-color: #adb5bd;
+}
+
+.btn-check:focus + .btn-outline-light, .btn-outline-light:focus {
+ box-shadow: 0 0 0 0.25rem rgba(173, 181, 189, 0.5);
+}
+
+.btn-check:checked + .btn-outline-light,
+.btn-check:active + .btn-outline-light, .btn-outline-light:active, .btn-outline-light.active, .btn-outline-light.dropdown-toggle.show {
+ color: #000;
+ background-color: #adb5bd;
+ border-color: #adb5bd;
+}
+
+.btn-check:checked + .btn-outline-light:focus,
+.btn-check:active + .btn-outline-light:focus, .btn-outline-light:active:focus, .btn-outline-light.active:focus, .btn-outline-light.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(173, 181, 189, 0.5);
+}
+
+.btn-outline-light:disabled, .btn-outline-light.disabled {
+ color: #adb5bd;
+ background-color: transparent;
+}
+
+.btn-outline-dark {
+ color: #303030;
+ border-color: #303030;
+}
+
+.btn-outline-dark:hover {
+ color: #fff;
+ background-color: #303030;
+ border-color: #303030;
+}
+
+.btn-check:focus + .btn-outline-dark, .btn-outline-dark:focus {
+ box-shadow: 0 0 0 0.25rem rgba(48, 48, 48, 0.5);
+}
+
+.btn-check:checked + .btn-outline-dark,
+.btn-check:active + .btn-outline-dark, .btn-outline-dark:active, .btn-outline-dark.active, .btn-outline-dark.dropdown-toggle.show {
+ color: #fff;
+ background-color: #303030;
+ border-color: #303030;
+}
+
+.btn-check:checked + .btn-outline-dark:focus,
+.btn-check:active + .btn-outline-dark:focus, .btn-outline-dark:active:focus, .btn-outline-dark.active:focus, .btn-outline-dark.dropdown-toggle.show:focus {
+ box-shadow: 0 0 0 0.25rem rgba(48, 48, 48, 0.5);
+}
+
+.btn-outline-dark:disabled, .btn-outline-dark.disabled {
+ color: #303030;
+ background-color: transparent;
+}
+
+.btn-link {
+ font-weight: 400;
+ color: #00bc8c;
+ text-decoration: underline;
+}
+
+.btn-link:hover {
+ color: #009670;
+}
+
+.btn-link:disabled, .btn-link.disabled {
+ color: #888;
+}
+
+.btn-lg, .btn-group-lg > .btn {
+ padding: 0.5rem 1rem;
+ font-size: 1.25rem;
+ border-radius: 0.3rem;
+}
+
+.btn-sm, .btn-group-sm > .btn {
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+ border-radius: 0.2rem;
+}
+
+.fade {
+ transition: opacity 0.15s linear;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .fade {
+ transition: none;
+ }
+}
+
+.fade:not(.show) {
+ opacity: 0;
+}
+
+.collapse:not(.show) {
+ display: none;
+}
+
+.collapsing {
+ height: 0;
+ overflow: hidden;
+ transition: height 0.35s ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .collapsing {
+ transition: none;
+ }
+}
+
+.dropup,
+.dropend,
+.dropdown,
+.dropstart {
+ position: relative;
+}
+
+.dropdown-toggle {
+ white-space: nowrap;
+}
+
+.dropdown-toggle::after {
+ display: inline-block;
+ margin-left: 0.255em;
+ vertical-align: 0.255em;
+ content: "";
+ border-top: 0.3em solid;
+ border-right: 0.3em solid transparent;
+ border-bottom: 0;
+ border-left: 0.3em solid transparent;
+}
+
+.dropdown-toggle:empty::after {
+ margin-left: 0;
+}
+
+.dropdown-menu {
+ position: absolute;
+ z-index: 1000;
+ display: none;
+ min-width: 10rem;
+ padding: 0.5rem 0;
+ margin: 0;
+ font-size: 1rem;
+ color: #fff;
+ text-align: left;
+ list-style: none;
+ background-color: #222;
+ background-clip: padding-box;
+ border: 1px solid #444;
+ border-radius: 0.25rem;
+}
+
+.dropdown-menu[data-bs-popper] {
+ top: 100%;
+ left: 0;
+ margin-top: 0.125rem;
+}
+
+.dropdown-menu-start {
+ --bs-position: start;
+}
+
+.dropdown-menu-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+}
+
+.dropdown-menu-end {
+ --bs-position: end;
+}
+
+.dropdown-menu-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+}
+
+@media (min-width: 576px) {
+ .dropdown-menu-sm-start {
+ --bs-position: start;
+ }
+ .dropdown-menu-sm-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+ }
+ .dropdown-menu-sm-end {
+ --bs-position: end;
+ }
+ .dropdown-menu-sm-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+ }
+}
+
+@media (min-width: 768px) {
+ .dropdown-menu-md-start {
+ --bs-position: start;
+ }
+ .dropdown-menu-md-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+ }
+ .dropdown-menu-md-end {
+ --bs-position: end;
+ }
+ .dropdown-menu-md-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+ }
+}
+
+@media (min-width: 992px) {
+ .dropdown-menu-lg-start {
+ --bs-position: start;
+ }
+ .dropdown-menu-lg-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+ }
+ .dropdown-menu-lg-end {
+ --bs-position: end;
+ }
+ .dropdown-menu-lg-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+ }
+}
+
+@media (min-width: 1200px) {
+ .dropdown-menu-xl-start {
+ --bs-position: start;
+ }
+ .dropdown-menu-xl-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+ }
+ .dropdown-menu-xl-end {
+ --bs-position: end;
+ }
+ .dropdown-menu-xl-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+ }
+}
+
+@media (min-width: 1400px) {
+ .dropdown-menu-xxl-start {
+ --bs-position: start;
+ }
+ .dropdown-menu-xxl-start[data-bs-popper] {
+ right: auto /* rtl:ignore */;
+ left: 0 /* rtl:ignore */;
+ }
+ .dropdown-menu-xxl-end {
+ --bs-position: end;
+ }
+ .dropdown-menu-xxl-end[data-bs-popper] {
+ right: 0 /* rtl:ignore */;
+ left: auto /* rtl:ignore */;
+ }
+}
+
+.dropup .dropdown-menu[data-bs-popper] {
+ top: auto;
+ bottom: 100%;
+ margin-top: 0;
+ margin-bottom: 0.125rem;
+}
+
+.dropup .dropdown-toggle::after {
+ display: inline-block;
+ margin-left: 0.255em;
+ vertical-align: 0.255em;
+ content: "";
+ border-top: 0;
+ border-right: 0.3em solid transparent;
+ border-bottom: 0.3em solid;
+ border-left: 0.3em solid transparent;
+}
+
+.dropup .dropdown-toggle:empty::after {
+ margin-left: 0;
+}
+
+.dropend .dropdown-menu[data-bs-popper] {
+ top: 0;
+ right: auto;
+ left: 100%;
+ margin-top: 0;
+ margin-left: 0.125rem;
+}
+
+.dropend .dropdown-toggle::after {
+ display: inline-block;
+ margin-left: 0.255em;
+ vertical-align: 0.255em;
+ content: "";
+ border-top: 0.3em solid transparent;
+ border-right: 0;
+ border-bottom: 0.3em solid transparent;
+ border-left: 0.3em solid;
+}
+
+.dropend .dropdown-toggle:empty::after {
+ margin-left: 0;
+}
+
+.dropend .dropdown-toggle::after {
+ vertical-align: 0;
+}
+
+.dropstart .dropdown-menu[data-bs-popper] {
+ top: 0;
+ right: 100%;
+ left: auto;
+ margin-top: 0;
+ margin-right: 0.125rem;
+}
+
+.dropstart .dropdown-toggle::after {
+ display: inline-block;
+ margin-left: 0.255em;
+ vertical-align: 0.255em;
+ content: "";
+}
+
+.dropstart .dropdown-toggle::after {
+ display: none;
+}
+
+.dropstart .dropdown-toggle::before {
+ display: inline-block;
+ margin-right: 0.255em;
+ vertical-align: 0.255em;
+ content: "";
+ border-top: 0.3em solid transparent;
+ border-right: 0.3em solid;
+ border-bottom: 0.3em solid transparent;
+}
+
+.dropstart .dropdown-toggle:empty::after {
+ margin-left: 0;
+}
+
+.dropstart .dropdown-toggle::before {
+ vertical-align: 0;
+}
+
+.dropdown-divider {
+ height: 0;
+ margin: 0.5rem 0;
+ overflow: hidden;
+ border-top: 1px solid #444;
+}
+
+.dropdown-item {
+ display: block;
+ width: 100%;
+ padding: 0.25rem 1rem;
+ clear: both;
+ font-weight: 400;
+ color: #fff;
+ text-align: inherit;
+ text-decoration: none;
+ white-space: nowrap;
+ background-color: transparent;
+ border: 0;
+}
+
+.dropdown-item:hover, .dropdown-item:focus {
+ color: #fff;
+ background-color: #375a7f;
+}
+
+.dropdown-item.active, .dropdown-item:active {
+ color: #fff;
+ text-decoration: none;
+ background-color: #375a7f;
+}
+
+.dropdown-item.disabled, .dropdown-item:disabled {
+ color: #adb5bd;
+ pointer-events: none;
+ background-color: transparent;
+}
+
+.dropdown-menu.show {
+ display: block;
+}
+
+.dropdown-header {
+ display: block;
+ padding: 0.5rem 1rem;
+ margin-bottom: 0;
+ font-size: 0.875rem;
+ color: #888;
+ white-space: nowrap;
+}
+
+.dropdown-item-text {
+ display: block;
+ padding: 0.25rem 1rem;
+ color: #fff;
+}
+
+.dropdown-menu-dark {
+ color: #dee2e6;
+ background-color: #303030;
+ border-color: #444;
+}
+
+.dropdown-menu-dark .dropdown-item {
+ color: #dee2e6;
+}
+
+.dropdown-menu-dark .dropdown-item:hover, .dropdown-menu-dark .dropdown-item:focus {
+ color: #fff;
+ background-color: rgba(255, 255, 255, 0.15);
+}
+
+.dropdown-menu-dark .dropdown-item.active, .dropdown-menu-dark .dropdown-item:active {
+ color: #fff;
+ background-color: #375a7f;
+}
+
+.dropdown-menu-dark .dropdown-item.disabled, .dropdown-menu-dark .dropdown-item:disabled {
+ color: #adb5bd;
+}
+
+.dropdown-menu-dark .dropdown-divider {
+ border-color: #444;
+}
+
+.dropdown-menu-dark .dropdown-item-text {
+ color: #dee2e6;
+}
+
+.dropdown-menu-dark .dropdown-header {
+ color: #adb5bd;
+}
+
+.btn-group,
+.btn-group-vertical {
+ position: relative;
+ display: -ms-inline-flexbox;
+ display: inline-flex;
+ vertical-align: middle;
+}
+
+.btn-group > .btn,
+.btn-group-vertical > .btn {
+ position: relative;
+ -ms-flex: 1 1 auto;
+ flex: 1 1 auto;
+}
+
+.btn-group > .btn-check:checked + .btn,
+.btn-group > .btn-check:focus + .btn,
+.btn-group > .btn:hover,
+.btn-group > .btn:focus,
+.btn-group > .btn:active,
+.btn-group > .btn.active,
+.btn-group-vertical > .btn-check:checked + .btn,
+.btn-group-vertical > .btn-check:focus + .btn,
+.btn-group-vertical > .btn:hover,
+.btn-group-vertical > .btn:focus,
+.btn-group-vertical > .btn:active,
+.btn-group-vertical > .btn.active {
+ z-index: 1;
+}
+
+.btn-toolbar {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+}
+
+.btn-toolbar .input-group {
+ width: auto;
+}
+
+.btn-group > .btn:not(:first-child),
+.btn-group > .btn-group:not(:first-child) {
+ margin-left: -1px;
+}
+
+.btn-group > .btn:not(:last-child):not(.dropdown-toggle),
+.btn-group > .btn-group:not(:last-child) > .btn {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+.btn-group > .btn:nth-child(n + 3),
+.btn-group > :not(.btn-check) + .btn,
+.btn-group > .btn-group:not(:first-child) > .btn {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+
+.dropdown-toggle-split {
+ padding-right: 0.5625rem;
+ padding-left: 0.5625rem;
+}
+
+.dropdown-toggle-split::after,
+.dropup .dropdown-toggle-split::after,
+.dropend .dropdown-toggle-split::after {
+ margin-left: 0;
+}
+
+.dropstart .dropdown-toggle-split::before {
+ margin-right: 0;
+}
+
+.btn-sm + .dropdown-toggle-split, .btn-group-sm > .btn + .dropdown-toggle-split {
+ padding-right: 0.375rem;
+ padding-left: 0.375rem;
+}
+
+.btn-lg + .dropdown-toggle-split, .btn-group-lg > .btn + .dropdown-toggle-split {
+ padding-right: 0.75rem;
+ padding-left: 0.75rem;
+}
+
+.btn-group-vertical {
+ -ms-flex-direction: column;
+ flex-direction: column;
+ -ms-flex-align: start;
+ align-items: flex-start;
+ -ms-flex-pack: center;
+ justify-content: center;
+}
+
+.btn-group-vertical > .btn,
+.btn-group-vertical > .btn-group {
+ width: 100%;
+}
+
+.btn-group-vertical > .btn:not(:first-child),
+.btn-group-vertical > .btn-group:not(:first-child) {
+ margin-top: -1px;
+}
+
+.btn-group-vertical > .btn:not(:last-child):not(.dropdown-toggle),
+.btn-group-vertical > .btn-group:not(:last-child) > .btn {
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+
+.btn-group-vertical > .btn ~ .btn,
+.btn-group-vertical > .btn-group:not(:first-child) > .btn {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+
+.nav {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ padding-left: 0;
+ margin-bottom: 0;
+ list-style: none;
+}
+
+.nav-link {
+ display: block;
+ padding: 0.5rem 2rem;
+ color: #00bc8c;
+ text-decoration: none;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .nav-link {
+ transition: none;
+ }
+}
+
+.nav-link:hover, .nav-link:focus {
+ color: #009670;
+}
+
+.nav-link.disabled {
+ color: #adb5bd;
+ pointer-events: none;
+ cursor: default;
+}
+
+.nav-tabs {
+ border-bottom: 1px solid #444;
+}
+
+.nav-tabs .nav-link {
+ margin-bottom: -1px;
+ background: none;
+ border: 1px solid transparent;
+ border-top-left-radius: 0.25rem;
+ border-top-right-radius: 0.25rem;
+}
+
+.nav-tabs .nav-link:hover, .nav-tabs .nav-link:focus {
+ border-color: #444 #444 transparent;
+ isolation: isolate;
+}
+
+.nav-tabs .nav-link.disabled {
+ color: #adb5bd;
+ background-color: transparent;
+ border-color: transparent;
+}
+
+.nav-tabs .nav-link.active,
+.nav-tabs .nav-item.show .nav-link {
+ color: #fff;
+ background-color: #222;
+ border-color: #444 #444 transparent;
+}
+
+.nav-tabs .dropdown-menu {
+ margin-top: -1px;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+
+.nav-pills .nav-link {
+ background: none;
+ border: 0;
+ border-radius: 0.25rem;
+}
+
+.nav-pills .nav-link.active,
+.nav-pills .show > .nav-link {
+ color: #fff;
+ background-color: #375a7f;
+}
+
+.nav-fill > .nav-link,
+.nav-fill .nav-item {
+ -ms-flex: 1 1 auto;
+ flex: 1 1 auto;
+ text-align: center;
+}
+
+.nav-justified > .nav-link,
+.nav-justified .nav-item {
+ -ms-flex-preferred-size: 0;
+ flex-basis: 0;
+ -ms-flex-positive: 1;
+ flex-grow: 1;
+ text-align: center;
+}
+
+.nav-fill .nav-item .nav-link,
+.nav-justified .nav-item .nav-link {
+ width: 100%;
+}
+
+.tab-content > .tab-pane {
+ display: none;
+}
+
+.tab-content > .active {
+ display: block;
+}
+
+.navbar {
+ position: relative;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: justify;
+ justify-content: space-between;
+ padding-top: 1rem;
+ padding-bottom: 1rem;
+}
+
+.navbar > .container,
+.navbar > .container-fluid, .navbar > .container-sm, .navbar > .container-md, .navbar > .container-lg, .navbar > .container-xl, .navbar > .container-xxl {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: inherit;
+ flex-wrap: inherit;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: justify;
+ justify-content: space-between;
+}
+
+.navbar-brand {
+ padding-top: 0.3125rem;
+ padding-bottom: 0.3125rem;
+ margin-right: 1rem;
+ font-size: 1.25rem;
+ text-decoration: none;
+ white-space: nowrap;
+}
+
+.navbar-nav {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ padding-left: 0;
+ margin-bottom: 0;
+ list-style: none;
+}
+
+.navbar-nav .nav-link {
+ padding-right: 0;
+ padding-left: 0;
+}
+
+.navbar-nav .dropdown-menu {
+ position: static;
+}
+
+.navbar-text {
+ padding-top: 0.5rem;
+ padding-bottom: 0.5rem;
+}
+
+.navbar-collapse {
+ -ms-flex-preferred-size: 100%;
+ flex-basis: 100%;
+ -ms-flex-positive: 1;
+ flex-grow: 1;
+ -ms-flex-align: center;
+ align-items: center;
+}
+
+.navbar-toggler {
+ padding: 0.25rem 0.75rem;
+ font-size: 1.25rem;
+ line-height: 1;
+ background-color: transparent;
+ border: 1px solid transparent;
+ border-radius: 0.25rem;
+ transition: box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .navbar-toggler {
+ transition: none;
+ }
+}
+
+.navbar-toggler:hover {
+ text-decoration: none;
+}
+
+.navbar-toggler:focus {
+ text-decoration: none;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem;
+}
+
+.navbar-toggler-icon {
+ display: inline-block;
+ width: 1.5em;
+ height: 1.5em;
+ vertical-align: middle;
+ background-repeat: no-repeat;
+ background-position: center;
+ background-size: 100%;
+}
+
+.navbar-nav-scroll {
+ max-height: var(--bs-scroll-height, 75vh);
+ overflow-y: auto;
+}
+
+@media (min-width: 576px) {
+ .navbar-expand-sm {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+ }
+ .navbar-expand-sm .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .navbar-expand-sm .navbar-nav .dropdown-menu {
+ position: absolute;
+ }
+ .navbar-expand-sm .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+ }
+ .navbar-expand-sm .navbar-nav-scroll {
+ overflow: visible;
+ }
+ .navbar-expand-sm .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+ }
+ .navbar-expand-sm .navbar-toggler {
+ display: none;
+ }
+}
+
+@media (min-width: 768px) {
+ .navbar-expand-md {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+ }
+ .navbar-expand-md .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .navbar-expand-md .navbar-nav .dropdown-menu {
+ position: absolute;
+ }
+ .navbar-expand-md .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+ }
+ .navbar-expand-md .navbar-nav-scroll {
+ overflow: visible;
+ }
+ .navbar-expand-md .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+ }
+ .navbar-expand-md .navbar-toggler {
+ display: none;
+ }
+}
+
+@media (min-width: 992px) {
+ .navbar-expand-lg {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+ }
+ .navbar-expand-lg .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .navbar-expand-lg .navbar-nav .dropdown-menu {
+ position: absolute;
+ }
+ .navbar-expand-lg .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+ }
+ .navbar-expand-lg .navbar-nav-scroll {
+ overflow: visible;
+ }
+ .navbar-expand-lg .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+ }
+ .navbar-expand-lg .navbar-toggler {
+ display: none;
+ }
+}
+
+@media (min-width: 1200px) {
+ .navbar-expand-xl {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+ }
+ .navbar-expand-xl .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .navbar-expand-xl .navbar-nav .dropdown-menu {
+ position: absolute;
+ }
+ .navbar-expand-xl .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+ }
+ .navbar-expand-xl .navbar-nav-scroll {
+ overflow: visible;
+ }
+ .navbar-expand-xl .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+ }
+ .navbar-expand-xl .navbar-toggler {
+ display: none;
+ }
+}
+
+@media (min-width: 1400px) {
+ .navbar-expand-xxl {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+ }
+ .navbar-expand-xxl .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .navbar-expand-xxl .navbar-nav .dropdown-menu {
+ position: absolute;
+ }
+ .navbar-expand-xxl .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+ }
+ .navbar-expand-xxl .navbar-nav-scroll {
+ overflow: visible;
+ }
+ .navbar-expand-xxl .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+ }
+ .navbar-expand-xxl .navbar-toggler {
+ display: none;
+ }
+}
+
+.navbar-expand {
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-pack: start;
+ justify-content: flex-start;
+}
+
+.navbar-expand .navbar-nav {
+ -ms-flex-direction: row;
+ flex-direction: row;
+}
+
+.navbar-expand .navbar-nav .dropdown-menu {
+ position: absolute;
+}
+
+.navbar-expand .navbar-nav .nav-link {
+ padding-right: 0.5rem;
+ padding-left: 0.5rem;
+}
+
+.navbar-expand .navbar-nav-scroll {
+ overflow: visible;
+}
+
+.navbar-expand .navbar-collapse {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ -ms-flex-preferred-size: auto;
+ flex-basis: auto;
+}
+
+.navbar-expand .navbar-toggler {
+ display: none;
+}
+
+.navbar-light .navbar-brand {
+ color: #222;
+}
+
+.navbar-light .navbar-brand:hover, .navbar-light .navbar-brand:focus {
+ color: #222;
+}
+
+.navbar-light .navbar-nav .nav-link {
+ color: rgba(34, 34, 34, 0.7);
+}
+
+.navbar-light .navbar-nav .nav-link:hover, .navbar-light .navbar-nav .nav-link:focus {
+ color: #222;
+}
+
+.navbar-light .navbar-nav .nav-link.disabled {
+ color: rgba(0, 0, 0, 0.3);
+}
+
+.navbar-light .navbar-nav .show > .nav-link,
+.navbar-light .navbar-nav .nav-link.active {
+ color: #222;
+}
+
+.navbar-light .navbar-toggler {
+ color: rgba(34, 34, 34, 0.7);
+ border-color: rgba(34, 34, 34, 0.1);
+}
+
+.navbar-light .navbar-toggler-icon {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2834, 34, 34, 0.7%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
+}
+
+.navbar-light .navbar-text {
+ color: rgba(34, 34, 34, 0.7);
+}
+
+.navbar-light .navbar-text a,
+.navbar-light .navbar-text a:hover,
+.navbar-light .navbar-text a:focus {
+ color: #222;
+}
+
+.navbar-dark .navbar-brand {
+ color: #fff;
+}
+
+.navbar-dark .navbar-brand:hover, .navbar-dark .navbar-brand:focus {
+ color: #fff;
+}
+
+.navbar-dark .navbar-nav .nav-link {
+ color: rgba(255, 255, 255, 0.6);
+}
+
+.navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .nav-link:focus {
+ color: #fff;
+}
+
+.navbar-dark .navbar-nav .nav-link.disabled {
+ color: rgba(255, 255, 255, 0.25);
+}
+
+.navbar-dark .navbar-nav .show > .nav-link,
+.navbar-dark .navbar-nav .nav-link.active {
+ color: #fff;
+}
+
+.navbar-dark .navbar-toggler {
+ color: rgba(255, 255, 255, 0.6);
+ border-color: rgba(255, 255, 255, 0.1);
+}
+
+.navbar-dark .navbar-toggler-icon {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.6%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
+}
+
+.navbar-dark .navbar-text {
+ color: rgba(255, 255, 255, 0.6);
+}
+
+.navbar-dark .navbar-text a,
+.navbar-dark .navbar-text a:hover,
+.navbar-dark .navbar-text a:focus {
+ color: #fff;
+}
+
+.card {
+ position: relative;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ min-width: 0;
+ word-wrap: break-word;
+ background-color: #303030;
+ background-clip: border-box;
+ border: 1px solid rgba(0, 0, 0, 0.125);
+ border-radius: 0.25rem;
+}
+
+.card > hr {
+ margin-right: 0;
+ margin-left: 0;
+}
+
+.card > .list-group {
+ border-top: inherit;
+ border-bottom: inherit;
+}
+
+.card > .list-group:first-child {
+ border-top-width: 0;
+ border-top-left-radius: calc(0.25rem - 1px);
+ border-top-right-radius: calc(0.25rem - 1px);
+}
+
+.card > .list-group:last-child {
+ border-bottom-width: 0;
+ border-bottom-right-radius: calc(0.25rem - 1px);
+ border-bottom-left-radius: calc(0.25rem - 1px);
+}
+
+.card > .card-header + .list-group,
+.card > .list-group + .card-footer {
+ border-top: 0;
+}
+
+.card-body {
+ -ms-flex: 1 1 auto;
+ flex: 1 1 auto;
+ padding: 1rem 1rem;
+}
+
+.card-title {
+ margin-bottom: 0.5rem;
+}
+
+.card-subtitle {
+ margin-top: -0.25rem;
+ margin-bottom: 0;
+}
+
+.card-text:last-child {
+ margin-bottom: 0;
+}
+
+.card-link:hover {
+ text-decoration: none;
+}
+
+.card-link + .card-link {
+ margin-left: 1rem;
+}
+
+.card-header {
+ padding: 0.5rem 1rem;
+ margin-bottom: 0;
+ background-color: #444;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.125);
+}
+
+.card-header:first-child {
+ border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0;
+}
+
+.card-footer {
+ padding: 0.5rem 1rem;
+ background-color: #444;
+ border-top: 1px solid rgba(0, 0, 0, 0.125);
+}
+
+.card-footer:last-child {
+ border-radius: 0 0 calc(0.25rem - 1px) calc(0.25rem - 1px);
+}
+
+.card-header-tabs {
+ margin-right: -0.5rem;
+ margin-bottom: -0.5rem;
+ margin-left: -0.5rem;
+ border-bottom: 0;
+}
+
+.card-header-tabs .nav-link.active {
+ background-color: #303030;
+ border-bottom-color: #303030;
+}
+
+.card-header-pills {
+ margin-right: -0.5rem;
+ margin-left: -0.5rem;
+}
+
+.card-img-overlay {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ padding: 1rem;
+ border-radius: calc(0.25rem - 1px);
+}
+
+.card-img,
+.card-img-top,
+.card-img-bottom {
+ width: 100%;
+}
+
+.card-img,
+.card-img-top {
+ border-top-left-radius: calc(0.25rem - 1px);
+ border-top-right-radius: calc(0.25rem - 1px);
+}
+
+.card-img,
+.card-img-bottom {
+ border-bottom-right-radius: calc(0.25rem - 1px);
+ border-bottom-left-radius: calc(0.25rem - 1px);
+}
+
+.card-group > .card {
+ margin-bottom: 0.75rem;
+}
+
+@media (min-width: 576px) {
+ .card-group {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-flow: row wrap;
+ flex-flow: row wrap;
+ }
+ .card-group > .card {
+ -ms-flex: 1 0 0%;
+ flex: 1 0 0%;
+ margin-bottom: 0;
+ }
+ .card-group > .card + .card {
+ margin-left: 0;
+ border-left: 0;
+ }
+ .card-group > .card:not(:last-child) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+ .card-group > .card:not(:last-child) .card-img-top,
+ .card-group > .card:not(:last-child) .card-header {
+ border-top-right-radius: 0;
+ }
+ .card-group > .card:not(:last-child) .card-img-bottom,
+ .card-group > .card:not(:last-child) .card-footer {
+ border-bottom-right-radius: 0;
+ }
+ .card-group > .card:not(:first-child) {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ }
+ .card-group > .card:not(:first-child) .card-img-top,
+ .card-group > .card:not(:first-child) .card-header {
+ border-top-left-radius: 0;
+ }
+ .card-group > .card:not(:first-child) .card-img-bottom,
+ .card-group > .card:not(:first-child) .card-footer {
+ border-bottom-left-radius: 0;
+ }
+}
+
+.accordion-button {
+ position: relative;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ width: 100%;
+ padding: 1rem 1.25rem;
+ font-size: 1rem;
+ color: #fff;
+ text-align: left;
+ background-color: #222;
+ border: 0;
+ border-radius: 0;
+ overflow-anchor: none;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, border-radius 0.15s ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .accordion-button {
+ transition: none;
+ }
+}
+
+.accordion-button:not(.collapsed) {
+ color: #325172;
+ background-color: #ebeff2;
+ box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.125);
+}
+
+.accordion-button:not(.collapsed)::after {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23325172'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
+ -webkit-transform: rotate(-180deg);
+ transform: rotate(-180deg);
+}
+
+.accordion-button::after {
+ -ms-flex-negative: 0;
+ flex-shrink: 0;
+ width: 1.25rem;
+ height: 1.25rem;
+ margin-left: auto;
+ content: "";
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-size: 1.25rem;
+ transition: -webkit-transform 0.2s ease-in-out;
+ transition: transform 0.2s ease-in-out;
+ transition: transform 0.2s ease-in-out, -webkit-transform 0.2s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .accordion-button::after {
+ transition: none;
+ }
+}
+
+.accordion-button:hover {
+ z-index: 2;
+}
+
+.accordion-button:focus {
+ z-index: 3;
+ border-color: #9badbf;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.accordion-header {
+ margin-bottom: 0;
+}
+
+.accordion-item {
+ background-color: #222;
+ border: 1px solid rgba(0, 0, 0, 0.125);
+}
+
+.accordion-item:first-of-type {
+ border-top-left-radius: 0.25rem;
+ border-top-right-radius: 0.25rem;
+}
+
+.accordion-item:first-of-type .accordion-button {
+ border-top-left-radius: calc(0.25rem - 1px);
+ border-top-right-radius: calc(0.25rem - 1px);
+}
+
+.accordion-item:not(:first-of-type) {
+ border-top: 0;
+}
+
+.accordion-item:last-of-type {
+ border-bottom-right-radius: 0.25rem;
+ border-bottom-left-radius: 0.25rem;
+}
+
+.accordion-item:last-of-type .accordion-button.collapsed {
+ border-bottom-right-radius: calc(0.25rem - 1px);
+ border-bottom-left-radius: calc(0.25rem - 1px);
+}
+
+.accordion-item:last-of-type .accordion-collapse {
+ border-bottom-right-radius: 0.25rem;
+ border-bottom-left-radius: 0.25rem;
+}
+
+.accordion-body {
+ padding: 1rem 1.25rem;
+}
+
+.accordion-flush .accordion-collapse {
+ border-width: 0;
+}
+
+.accordion-flush .accordion-item {
+ border-right: 0;
+ border-left: 0;
+ border-radius: 0;
+}
+
+.accordion-flush .accordion-item:first-child {
+ border-top: 0;
+}
+
+.accordion-flush .accordion-item:last-child {
+ border-bottom: 0;
+}
+
+.accordion-flush .accordion-item .accordion-button {
+ border-radius: 0;
+}
+
+.breadcrumb {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ padding: 0.375rem 0.75rem;
+ margin-bottom: 1rem;
+ list-style: none;
+ background-color: #444;
+ border-radius: 0.25rem;
+}
+
+.breadcrumb-item + .breadcrumb-item {
+ padding-left: 0.5rem;
+}
+
+.breadcrumb-item + .breadcrumb-item::before {
+ float: left;
+ padding-right: 0.5rem;
+ color: #888;
+ content: var(--bs-breadcrumb-divider, "/") /* rtl: var(--bs-breadcrumb-divider, "/") */;
+}
+
+.breadcrumb-item.active {
+ color: #888;
+}
+
+.pagination {
+ display: -ms-flexbox;
+ display: flex;
+ padding-left: 0;
+ list-style: none;
+}
+
+.page-link {
+ position: relative;
+ display: block;
+ color: #fff;
+ text-decoration: none;
+ background-color: #00bc8c;
+ border: 0 solid transparent;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .page-link {
+ transition: none;
+ }
+}
+
+.page-link:hover {
+ z-index: 2;
+ color: #fff;
+ background-color: #00efb2;
+ border-color: transparent;
+}
+
+.page-link:focus {
+ z-index: 3;
+ color: #009670;
+ background-color: #ebebeb;
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+}
+
+.page-item:not(:first-child) .page-link {
+ margin-left: 0;
+}
+
+.page-item.active .page-link {
+ z-index: 3;
+ color: #fff;
+ background-color: #00efb2;
+ border-color: transparent;
+}
+
+.page-item.disabled .page-link {
+ color: #fff;
+ pointer-events: none;
+ background-color: #007053;
+ border-color: transparent;
+}
+
+.page-link {
+ padding: 0.375rem 0.75rem;
+}
+
+.page-item:first-child .page-link {
+ border-top-left-radius: 0.25rem;
+ border-bottom-left-radius: 0.25rem;
+}
+
+.page-item:last-child .page-link {
+ border-top-right-radius: 0.25rem;
+ border-bottom-right-radius: 0.25rem;
+}
+
+.pagination-lg .page-link {
+ padding: 0.75rem 1.5rem;
+ font-size: 1.25rem;
+}
+
+.pagination-lg .page-item:first-child .page-link {
+ border-top-left-radius: 0.3rem;
+ border-bottom-left-radius: 0.3rem;
+}
+
+.pagination-lg .page-item:last-child .page-link {
+ border-top-right-radius: 0.3rem;
+ border-bottom-right-radius: 0.3rem;
+}
+
+.pagination-sm .page-link {
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+}
+
+.pagination-sm .page-item:first-child .page-link {
+ border-top-left-radius: 0.2rem;
+ border-bottom-left-radius: 0.2rem;
+}
+
+.pagination-sm .page-item:last-child .page-link {
+ border-top-right-radius: 0.2rem;
+ border-bottom-right-radius: 0.2rem;
+}
+
+.badge {
+ display: inline-block;
+ padding: 0.35em 0.65em;
+ font-size: 0.75em;
+ font-weight: 700;
+ line-height: 1;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: baseline;
+ border-radius: 0.25rem;
+}
+
+.badge:empty {
+ display: none;
+}
+
+.btn .badge {
+ position: relative;
+ top: -1px;
+}
+
+.alert {
+ position: relative;
+ padding: 1rem 1rem;
+ margin-bottom: 1rem;
+ border: 1px solid transparent;
+ border-radius: 0.25rem;
+}
+
+.alert-heading {
+ color: inherit;
+}
+
+.alert-link {
+ font-weight: 700;
+}
+
+.alert-dismissible {
+ padding-right: 3rem;
+}
+
+.alert-dismissible .btn-close {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 2;
+ padding: 1.25rem 1rem;
+}
+
+.alert-primary {
+ color: #21364c;
+ background-color: #d7dee5;
+ border-color: #c3ced9;
+}
+
+.alert-primary .alert-link {
+ color: #1a2b3d;
+}
+
+.alert-secondary {
+ color: #292929;
+ background-color: #dadada;
+ border-color: #c7c7c7;
+}
+
+.alert-secondary .alert-link {
+ color: #212121;
+}
+
+.alert-success {
+ color: #007154;
+ background-color: #ccf2e8;
+ border-color: #b3ebdd;
+}
+
+.alert-success .alert-link {
+ color: #005a43;
+}
+
+.alert-info {
+ color: #1f5b83;
+ background-color: #d6eaf8;
+ border-color: #c2e0f4;
+}
+
+.alert-info .alert-link {
+ color: #194969;
+}
+
+.alert-warning {
+ color: #925e0b;
+ background-color: #fdebd0;
+ border-color: #fbe1b8;
+}
+
+.alert-warning .alert-link {
+ color: #754b09;
+}
+
+.alert-danger {
+ color: #8b2e24;
+ background-color: #fadbd8;
+ border-color: #f8c9c5;
+}
+
+.alert-danger .alert-link {
+ color: #6f251d;
+}
+
+.alert-light {
+ color: #686d71;
+ background-color: #eff0f2;
+ border-color: #e6e9eb;
+}
+
+.alert-light .alert-link {
+ color: #53575a;
+}
+
+.alert-dark {
+ color: #1d1d1d;
+ background-color: #d6d6d6;
+ border-color: #c1c1c1;
+}
+
+.alert-dark .alert-link {
+ color: #171717;
+}
+
+@-webkit-keyframes progress-bar-stripes {
+ 0% {
+ background-position-x: 1rem;
+ }
+}
+
+@keyframes progress-bar-stripes {
+ 0% {
+ background-position-x: 1rem;
+ }
+}
+
+.progress {
+ display: -ms-flexbox;
+ display: flex;
+ height: 1rem;
+ overflow: hidden;
+ font-size: 0.75rem;
+ background-color: #444;
+ border-radius: 0.25rem;
+}
+
+.progress-bar {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ -ms-flex-pack: center;
+ justify-content: center;
+ overflow: hidden;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ background-color: #375a7f;
+ transition: width 0.6s ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .progress-bar {
+ transition: none;
+ }
+}
+
+.progress-bar-striped {
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+ background-size: 1rem 1rem;
+}
+
+.progress-bar-animated {
+ -webkit-animation: 1s linear infinite progress-bar-stripes;
+ animation: 1s linear infinite progress-bar-stripes;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .progress-bar-animated {
+ -webkit-animation: none;
+ animation: none;
+ }
+}
+
+.list-group {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ padding-left: 0;
+ margin-bottom: 0;
+ border-radius: 0.25rem;
+}
+
+.list-group-numbered {
+ list-style-type: none;
+ counter-reset: section;
+}
+
+.list-group-numbered > li::before {
+ content: counters(section, ".") ". ";
+ counter-increment: section;
+}
+
+.list-group-item-action {
+ width: 100%;
+ color: #444;
+ text-align: inherit;
+}
+
+.list-group-item-action:hover, .list-group-item-action:focus {
+ z-index: 1;
+ color: #fff;
+ text-decoration: none;
+ background-color: #444;
+}
+
+.list-group-item-action:active {
+ color: #fff;
+ background-color: #222;
+}
+
+.list-group-item {
+ position: relative;
+ display: block;
+ padding: 0.5rem 1rem;
+ color: #fff;
+ text-decoration: none;
+ background-color: #303030;
+ border: 1px solid #444;
+}
+
+.list-group-item:first-child {
+ border-top-left-radius: inherit;
+ border-top-right-radius: inherit;
+}
+
+.list-group-item:last-child {
+ border-bottom-right-radius: inherit;
+ border-bottom-left-radius: inherit;
+}
+
+.list-group-item.disabled, .list-group-item:disabled {
+ color: #888;
+ pointer-events: none;
+ background-color: #303030;
+}
+
+.list-group-item.active {
+ z-index: 2;
+ color: #fff;
+ background-color: #375a7f;
+ border-color: #375a7f;
+}
+
+.list-group-item + .list-group-item {
+ border-top-width: 0;
+}
+
+.list-group-item + .list-group-item.active {
+ margin-top: -1px;
+ border-top-width: 1px;
+}
+
+.list-group-horizontal {
+ -ms-flex-direction: row;
+ flex-direction: row;
+}
+
+.list-group-horizontal > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+}
+
+.list-group-horizontal > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+}
+
+.list-group-horizontal > .list-group-item.active {
+ margin-top: 0;
+}
+
+.list-group-horizontal > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+}
+
+.list-group-horizontal > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+}
+
+@media (min-width: 576px) {
+ .list-group-horizontal-sm {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .list-group-horizontal-sm > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+ }
+ .list-group-horizontal-sm > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+ }
+ .list-group-horizontal-sm > .list-group-item.active {
+ margin-top: 0;
+ }
+ .list-group-horizontal-sm > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+ }
+ .list-group-horizontal-sm > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+ }
+}
+
+@media (min-width: 768px) {
+ .list-group-horizontal-md {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .list-group-horizontal-md > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+ }
+ .list-group-horizontal-md > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+ }
+ .list-group-horizontal-md > .list-group-item.active {
+ margin-top: 0;
+ }
+ .list-group-horizontal-md > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+ }
+ .list-group-horizontal-md > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+ }
+}
+
+@media (min-width: 992px) {
+ .list-group-horizontal-lg {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .list-group-horizontal-lg > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+ }
+ .list-group-horizontal-lg > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+ }
+ .list-group-horizontal-lg > .list-group-item.active {
+ margin-top: 0;
+ }
+ .list-group-horizontal-lg > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+ }
+ .list-group-horizontal-lg > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+ }
+}
+
+@media (min-width: 1200px) {
+ .list-group-horizontal-xl {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .list-group-horizontal-xl > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+ }
+ .list-group-horizontal-xl > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+ }
+ .list-group-horizontal-xl > .list-group-item.active {
+ margin-top: 0;
+ }
+ .list-group-horizontal-xl > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+ }
+ .list-group-horizontal-xl > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+ }
+}
+
+@media (min-width: 1400px) {
+ .list-group-horizontal-xxl {
+ -ms-flex-direction: row;
+ flex-direction: row;
+ }
+ .list-group-horizontal-xxl > .list-group-item:first-child {
+ border-bottom-left-radius: 0.25rem;
+ border-top-right-radius: 0;
+ }
+ .list-group-horizontal-xxl > .list-group-item:last-child {
+ border-top-right-radius: 0.25rem;
+ border-bottom-left-radius: 0;
+ }
+ .list-group-horizontal-xxl > .list-group-item.active {
+ margin-top: 0;
+ }
+ .list-group-horizontal-xxl > .list-group-item + .list-group-item {
+ border-top-width: 1px;
+ border-left-width: 0;
+ }
+ .list-group-horizontal-xxl > .list-group-item + .list-group-item.active {
+ margin-left: -1px;
+ border-left-width: 1px;
+ }
+}
+
+.list-group-flush {
+ border-radius: 0;
+}
+
+.list-group-flush > .list-group-item {
+ border-width: 0 0 1px;
+}
+
+.list-group-flush > .list-group-item:last-child {
+ border-bottom-width: 0;
+}
+
+.list-group-item-primary {
+ color: #21364c;
+ background-color: #d7dee5;
+}
+
+.list-group-item-primary.list-group-item-action:hover, .list-group-item-primary.list-group-item-action:focus {
+ color: #21364c;
+ background-color: #c2c8ce;
+}
+
+.list-group-item-primary.list-group-item-action.active {
+ color: #fff;
+ background-color: #21364c;
+ border-color: #21364c;
+}
+
+.list-group-item-secondary {
+ color: #292929;
+ background-color: #dadada;
+}
+
+.list-group-item-secondary.list-group-item-action:hover, .list-group-item-secondary.list-group-item-action:focus {
+ color: #292929;
+ background-color: #c4c4c4;
+}
+
+.list-group-item-secondary.list-group-item-action.active {
+ color: #fff;
+ background-color: #292929;
+ border-color: #292929;
+}
+
+.list-group-item-success {
+ color: #007154;
+ background-color: #ccf2e8;
+}
+
+.list-group-item-success.list-group-item-action:hover, .list-group-item-success.list-group-item-action:focus {
+ color: #007154;
+ background-color: #b8dad1;
+}
+
+.list-group-item-success.list-group-item-action.active {
+ color: #fff;
+ background-color: #007154;
+ border-color: #007154;
+}
+
+.list-group-item-info {
+ color: #1f5b83;
+ background-color: #d6eaf8;
+}
+
+.list-group-item-info.list-group-item-action:hover, .list-group-item-info.list-group-item-action:focus {
+ color: #1f5b83;
+ background-color: #c1d3df;
+}
+
+.list-group-item-info.list-group-item-action.active {
+ color: #fff;
+ background-color: #1f5b83;
+ border-color: #1f5b83;
+}
+
+.list-group-item-warning {
+ color: #925e0b;
+ background-color: #fdebd0;
+}
+
+.list-group-item-warning.list-group-item-action:hover, .list-group-item-warning.list-group-item-action:focus {
+ color: #925e0b;
+ background-color: #e4d4bb;
+}
+
+.list-group-item-warning.list-group-item-action.active {
+ color: #fff;
+ background-color: #925e0b;
+ border-color: #925e0b;
+}
+
+.list-group-item-danger {
+ color: #8b2e24;
+ background-color: #fadbd8;
+}
+
+.list-group-item-danger.list-group-item-action:hover, .list-group-item-danger.list-group-item-action:focus {
+ color: #8b2e24;
+ background-color: #e1c5c2;
+}
+
+.list-group-item-danger.list-group-item-action.active {
+ color: #fff;
+ background-color: #8b2e24;
+ border-color: #8b2e24;
+}
+
+.list-group-item-light {
+ color: #686d71;
+ background-color: #eff0f2;
+}
+
+.list-group-item-light.list-group-item-action:hover, .list-group-item-light.list-group-item-action:focus {
+ color: #686d71;
+ background-color: #d7d8da;
+}
+
+.list-group-item-light.list-group-item-action.active {
+ color: #fff;
+ background-color: #686d71;
+ border-color: #686d71;
+}
+
+.list-group-item-dark {
+ color: #1d1d1d;
+ background-color: #d6d6d6;
+}
+
+.list-group-item-dark.list-group-item-action:hover, .list-group-item-dark.list-group-item-action:focus {
+ color: #1d1d1d;
+ background-color: #c1c1c1;
+}
+
+.list-group-item-dark.list-group-item-action.active {
+ color: #fff;
+ background-color: #1d1d1d;
+ border-color: #1d1d1d;
+}
+
+.btn-close {
+ box-sizing: content-box;
+ width: 1em;
+ height: 1em;
+ padding: 0.25em 0.25em;
+ color: #fff;
+ background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
+ border: 0;
+ border-radius: 0.25rem;
+ opacity: 0.4;
+}
+
+.btn-close:hover {
+ color: #fff;
+ text-decoration: none;
+ opacity: 1;
+}
+
+.btn-close:focus {
+ outline: 0;
+ box-shadow: 0 0 0 0.25rem rgba(55, 90, 127, 0.25);
+ opacity: 1;
+}
+
+.btn-close:disabled, .btn-close.disabled {
+ pointer-events: none;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ opacity: 0.25;
+}
+
+.btn-close-white {
+ -webkit-filter: invert(1) grayscale(100%) brightness(200%);
+ filter: invert(1) grayscale(100%) brightness(200%);
+}
+
+.toast {
+ width: 350px;
+ max-width: 100%;
+ font-size: 0.875rem;
+ pointer-events: auto;
+ background-color: #444;
+ background-clip: padding-box;
+ border: 1px solid rgba(0, 0, 0, 0.1);
+ box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
+ border-radius: 0.25rem;
+}
+
+.toast:not(.showing):not(.show) {
+ opacity: 0;
+}
+
+.toast.hide {
+ display: none;
+}
+
+.toast-container {
+ width: -webkit-max-content;
+ width: -moz-max-content;
+ width: max-content;
+ max-width: 100%;
+ pointer-events: none;
+}
+
+.toast-container > :not(:last-child) {
+ margin-bottom: 0.75rem;
+}
+
+.toast-header {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ padding: 0.5rem 0.75rem;
+ color: #888;
+ background-color: #303030;
+ background-clip: padding-box;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.05);
+ border-top-left-radius: calc(0.25rem - 1px);
+ border-top-right-radius: calc(0.25rem - 1px);
+}
+
+.toast-header .btn-close {
+ margin-right: -0.375rem;
+ margin-left: 0.75rem;
+}
+
+.toast-body {
+ padding: 0.75rem;
+ word-wrap: break-word;
+}
+
+.modal {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 1060;
+ display: none;
+ width: 100%;
+ height: 100%;
+ overflow-x: hidden;
+ overflow-y: auto;
+ outline: 0;
+}
+
+.modal-dialog {
+ position: relative;
+ width: auto;
+ margin: 0.5rem;
+ pointer-events: none;
+}
+
+.modal.fade .modal-dialog {
+ transition: -webkit-transform 0.3s ease-out;
+ transition: transform 0.3s ease-out;
+ transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out;
+ -webkit-transform: translate(0, -50px);
+ transform: translate(0, -50px);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .modal.fade .modal-dialog {
+ transition: none;
+ }
+}
+
+.modal.show .modal-dialog {
+ -webkit-transform: none;
+ transform: none;
+}
+
+.modal.modal-static .modal-dialog {
+ -webkit-transform: scale(1.02);
+ transform: scale(1.02);
+}
+
+.modal-dialog-scrollable {
+ height: calc(100% - 1rem);
+}
+
+.modal-dialog-scrollable .modal-content {
+ max-height: 100%;
+ overflow: hidden;
+}
+
+.modal-dialog-scrollable .modal-body {
+ overflow-y: auto;
+}
+
+.modal-dialog-centered {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ min-height: calc(100% - 1rem);
+}
+
+.modal-content {
+ position: relative;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ width: 100%;
+ pointer-events: auto;
+ background-color: #303030;
+ background-clip: padding-box;
+ border: 1px solid #444;
+ border-radius: 0.3rem;
+ outline: 0;
+}
+
+.modal-backdrop {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 1040;
+ width: 100vw;
+ height: 100vh;
+ background-color: #000;
+}
+
+.modal-backdrop.fade {
+ opacity: 0;
+}
+
+.modal-backdrop.show {
+ opacity: 0.5;
+}
+
+.modal-header {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-negative: 0;
+ flex-shrink: 0;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: justify;
+ justify-content: space-between;
+ padding: 1rem 1rem;
+ border-bottom: 1px solid #444;
+ border-top-left-radius: calc(0.3rem - 1px);
+ border-top-right-radius: calc(0.3rem - 1px);
+}
+
+.modal-header .btn-close {
+ padding: 0.5rem 0.5rem;
+ margin: -0.5rem -0.5rem -0.5rem auto;
+}
+
+.modal-title {
+ margin-bottom: 0;
+ line-height: 1.5;
+}
+
+.modal-body {
+ position: relative;
+ -ms-flex: 1 1 auto;
+ flex: 1 1 auto;
+ padding: 1rem;
+}
+
+.modal-footer {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-wrap: wrap;
+ flex-wrap: wrap;
+ -ms-flex-negative: 0;
+ flex-shrink: 0;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: end;
+ justify-content: flex-end;
+ padding: 0.75rem;
+ border-top: 1px solid #444;
+ border-bottom-right-radius: calc(0.3rem - 1px);
+ border-bottom-left-radius: calc(0.3rem - 1px);
+}
+
+.modal-footer > * {
+ margin: 0.25rem;
+}
+
+@media (min-width: 576px) {
+ .modal-dialog {
+ max-width: 500px;
+ margin: 1.75rem auto;
+ }
+ .modal-dialog-scrollable {
+ height: calc(100% - 3.5rem);
+ }
+ .modal-dialog-centered {
+ min-height: calc(100% - 3.5rem);
+ }
+ .modal-sm {
+ max-width: 300px;
+ }
+}
+
+@media (min-width: 992px) {
+ .modal-lg,
+ .modal-xl {
+ max-width: 800px;
+ }
+}
+
+@media (min-width: 1200px) {
+ .modal-xl {
+ max-width: 1140px;
+ }
+}
+
+.modal-fullscreen {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+}
+
+.modal-fullscreen .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+}
+
+.modal-fullscreen .modal-header {
+ border-radius: 0;
+}
+
+.modal-fullscreen .modal-body {
+ overflow-y: auto;
+}
+
+.modal-fullscreen .modal-footer {
+ border-radius: 0;
+}
+
+@media (max-width: 575.98px) {
+ .modal-fullscreen-sm-down {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+ }
+ .modal-fullscreen-sm-down .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ .modal-fullscreen-sm-down .modal-header {
+ border-radius: 0;
+ }
+ .modal-fullscreen-sm-down .modal-body {
+ overflow-y: auto;
+ }
+ .modal-fullscreen-sm-down .modal-footer {
+ border-radius: 0;
+ }
+}
+
+@media (max-width: 767.98px) {
+ .modal-fullscreen-md-down {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+ }
+ .modal-fullscreen-md-down .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ .modal-fullscreen-md-down .modal-header {
+ border-radius: 0;
+ }
+ .modal-fullscreen-md-down .modal-body {
+ overflow-y: auto;
+ }
+ .modal-fullscreen-md-down .modal-footer {
+ border-radius: 0;
+ }
+}
+
+@media (max-width: 991.98px) {
+ .modal-fullscreen-lg-down {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+ }
+ .modal-fullscreen-lg-down .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ .modal-fullscreen-lg-down .modal-header {
+ border-radius: 0;
+ }
+ .modal-fullscreen-lg-down .modal-body {
+ overflow-y: auto;
+ }
+ .modal-fullscreen-lg-down .modal-footer {
+ border-radius: 0;
+ }
+}
+
+@media (max-width: 1199.98px) {
+ .modal-fullscreen-xl-down {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+ }
+ .modal-fullscreen-xl-down .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ .modal-fullscreen-xl-down .modal-header {
+ border-radius: 0;
+ }
+ .modal-fullscreen-xl-down .modal-body {
+ overflow-y: auto;
+ }
+ .modal-fullscreen-xl-down .modal-footer {
+ border-radius: 0;
+ }
+}
+
+@media (max-width: 1399.98px) {
+ .modal-fullscreen-xxl-down {
+ width: 100vw;
+ max-width: none;
+ height: 100%;
+ margin: 0;
+ }
+ .modal-fullscreen-xxl-down .modal-content {
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ .modal-fullscreen-xxl-down .modal-header {
+ border-radius: 0;
+ }
+ .modal-fullscreen-xxl-down .modal-body {
+ overflow-y: auto;
+ }
+ .modal-fullscreen-xxl-down .modal-footer {
+ border-radius: 0;
+ }
+}
+
+.tooltip {
+ position: absolute;
+ z-index: 1080;
+ display: block;
+ margin: 0;
+ font-family: var(--bs-font-sans-serif);
+ font-style: normal;
+ font-weight: 400;
+ line-height: 1.5;
+ text-align: left;
+ text-align: start;
+ text-decoration: none;
+ text-shadow: none;
+ text-transform: none;
+ letter-spacing: normal;
+ word-break: normal;
+ word-spacing: normal;
+ white-space: normal;
+ line-break: auto;
+ font-size: 0.875rem;
+ word-wrap: break-word;
+ opacity: 0;
+}
+
+.tooltip.show {
+ opacity: 0.9;
+}
+
+.tooltip .tooltip-arrow {
+ position: absolute;
+ display: block;
+ width: 0.8rem;
+ height: 0.4rem;
+}
+
+.tooltip .tooltip-arrow::before {
+ position: absolute;
+ content: "";
+ border-color: transparent;
+ border-style: solid;
+}
+
+.bs-tooltip-top, .bs-tooltip-auto[data-popper-placement^="top"] {
+ padding: 0.4rem 0;
+}
+
+.bs-tooltip-top .tooltip-arrow, .bs-tooltip-auto[data-popper-placement^="top"] .tooltip-arrow {
+ bottom: 0;
+}
+
+.bs-tooltip-top .tooltip-arrow::before, .bs-tooltip-auto[data-popper-placement^="top"] .tooltip-arrow::before {
+ top: -1px;
+ border-width: 0.4rem 0.4rem 0;
+ border-top-color: #000;
+}
+
+.bs-tooltip-end, .bs-tooltip-auto[data-popper-placement^="right"] {
+ padding: 0 0.4rem;
+}
+
+.bs-tooltip-end .tooltip-arrow, .bs-tooltip-auto[data-popper-placement^="right"] .tooltip-arrow {
+ left: 0;
+ width: 0.4rem;
+ height: 0.8rem;
+}
+
+.bs-tooltip-end .tooltip-arrow::before, .bs-tooltip-auto[data-popper-placement^="right"] .tooltip-arrow::before {
+ right: -1px;
+ border-width: 0.4rem 0.4rem 0.4rem 0;
+ border-right-color: #000;
+}
+
+.bs-tooltip-bottom, .bs-tooltip-auto[data-popper-placement^="bottom"] {
+ padding: 0.4rem 0;
+}
+
+.bs-tooltip-bottom .tooltip-arrow, .bs-tooltip-auto[data-popper-placement^="bottom"] .tooltip-arrow {
+ top: 0;
+}
+
+.bs-tooltip-bottom .tooltip-arrow::before, .bs-tooltip-auto[data-popper-placement^="bottom"] .tooltip-arrow::before {
+ bottom: -1px;
+ border-width: 0 0.4rem 0.4rem;
+ border-bottom-color: #000;
+}
+
+.bs-tooltip-start, .bs-tooltip-auto[data-popper-placement^="left"] {
+ padding: 0 0.4rem;
+}
+
+.bs-tooltip-start .tooltip-arrow, .bs-tooltip-auto[data-popper-placement^="left"] .tooltip-arrow {
+ right: 0;
+ width: 0.4rem;
+ height: 0.8rem;
+}
+
+.bs-tooltip-start .tooltip-arrow::before, .bs-tooltip-auto[data-popper-placement^="left"] .tooltip-arrow::before {
+ left: -1px;
+ border-width: 0.4rem 0 0.4rem 0.4rem;
+ border-left-color: #000;
+}
+
+.tooltip-inner {
+ max-width: 200px;
+ padding: 0.25rem 0.5rem;
+ color: #fff;
+ text-align: center;
+ background-color: #000;
+ border-radius: 0.25rem;
+}
+
+.popover {
+ position: absolute;
+ top: 0;
+ left: 0 /* rtl:ignore */;
+ z-index: 1070;
+ display: block;
+ max-width: 276px;
+ font-family: var(--bs-font-sans-serif);
+ font-style: normal;
+ font-weight: 400;
+ line-height: 1.5;
+ text-align: left;
+ text-align: start;
+ text-decoration: none;
+ text-shadow: none;
+ text-transform: none;
+ letter-spacing: normal;
+ word-break: normal;
+ word-spacing: normal;
+ white-space: normal;
+ line-break: auto;
+ font-size: 0.875rem;
+ word-wrap: break-word;
+ background-color: #303030;
+ background-clip: padding-box;
+ border: 1px solid rgba(0, 0, 0, 0.2);
+ border-radius: 0.3rem;
+}
+
+.popover .popover-arrow {
+ position: absolute;
+ display: block;
+ width: 1rem;
+ height: 0.5rem;
+}
+
+.popover .popover-arrow::before, .popover .popover-arrow::after {
+ position: absolute;
+ display: block;
+ content: "";
+ border-color: transparent;
+ border-style: solid;
+}
+
+.bs-popover-top > .popover-arrow, .bs-popover-auto[data-popper-placement^="top"] > .popover-arrow {
+ bottom: calc(-0.5rem - 1px);
+}
+
+.bs-popover-top > .popover-arrow::before, .bs-popover-auto[data-popper-placement^="top"] > .popover-arrow::before {
+ bottom: 0;
+ border-width: 0.5rem 0.5rem 0;
+ border-top-color: rgba(0, 0, 0, 0.25);
+}
+
+.bs-popover-top > .popover-arrow::after, .bs-popover-auto[data-popper-placement^="top"] > .popover-arrow::after {
+ bottom: 1px;
+ border-width: 0.5rem 0.5rem 0;
+ border-top-color: #303030;
+}
+
+.bs-popover-end > .popover-arrow, .bs-popover-auto[data-popper-placement^="right"] > .popover-arrow {
+ left: calc(-0.5rem - 1px);
+ width: 0.5rem;
+ height: 1rem;
+}
+
+.bs-popover-end > .popover-arrow::before, .bs-popover-auto[data-popper-placement^="right"] > .popover-arrow::before {
+ left: 0;
+ border-width: 0.5rem 0.5rem 0.5rem 0;
+ border-right-color: rgba(0, 0, 0, 0.25);
+}
+
+.bs-popover-end > .popover-arrow::after, .bs-popover-auto[data-popper-placement^="right"] > .popover-arrow::after {
+ left: 1px;
+ border-width: 0.5rem 0.5rem 0.5rem 0;
+ border-right-color: #303030;
+}
+
+.bs-popover-bottom > .popover-arrow, .bs-popover-auto[data-popper-placement^="bottom"] > .popover-arrow {
+ top: calc(-0.5rem - 1px);
+}
+
+.bs-popover-bottom > .popover-arrow::before, .bs-popover-auto[data-popper-placement^="bottom"] > .popover-arrow::before {
+ top: 0;
+ border-width: 0 0.5rem 0.5rem 0.5rem;
+ border-bottom-color: rgba(0, 0, 0, 0.25);
+}
+
+.bs-popover-bottom > .popover-arrow::after, .bs-popover-auto[data-popper-placement^="bottom"] > .popover-arrow::after {
+ top: 1px;
+ border-width: 0 0.5rem 0.5rem 0.5rem;
+ border-bottom-color: #303030;
+}
+
+.bs-popover-bottom .popover-header::before, .bs-popover-auto[data-popper-placement^="bottom"] .popover-header::before {
+ position: absolute;
+ top: 0;
+ left: 50%;
+ display: block;
+ width: 1rem;
+ margin-left: -0.5rem;
+ content: "";
+ border-bottom: 1px solid #444;
+}
+
+.bs-popover-start > .popover-arrow, .bs-popover-auto[data-popper-placement^="left"] > .popover-arrow {
+ right: calc(-0.5rem - 1px);
+ width: 0.5rem;
+ height: 1rem;
+}
+
+.bs-popover-start > .popover-arrow::before, .bs-popover-auto[data-popper-placement^="left"] > .popover-arrow::before {
+ right: 0;
+ border-width: 0.5rem 0 0.5rem 0.5rem;
+ border-left-color: rgba(0, 0, 0, 0.25);
+}
+
+.bs-popover-start > .popover-arrow::after, .bs-popover-auto[data-popper-placement^="left"] > .popover-arrow::after {
+ right: 1px;
+ border-width: 0.5rem 0 0.5rem 0.5rem;
+ border-left-color: #303030;
+}
+
+.popover-header {
+ padding: 0.5rem 1rem;
+ margin-bottom: 0;
+ font-size: 1rem;
+ background-color: #444;
+ border-bottom: 1px solid #3d3d3d;
+ border-top-left-radius: calc(0.3rem - 1px);
+ border-top-right-radius: calc(0.3rem - 1px);
+}
+
+.popover-header:empty {
+ display: none;
+}
+
+.popover-body {
+ padding: 1rem 1rem;
+ color: #fff;
+}
+
+.carousel {
+ position: relative;
+}
+
+.carousel.pointer-event {
+ -ms-touch-action: pan-y;
+ touch-action: pan-y;
+}
+
+.carousel-inner {
+ position: relative;
+ width: 100%;
+ overflow: hidden;
+}
+
+.carousel-inner::after {
+ display: block;
+ clear: both;
+ content: "";
+}
+
+.carousel-item {
+ position: relative;
+ display: none;
+ float: left;
+ width: 100%;
+ margin-right: -100%;
+ -webkit-backface-visibility: hidden;
+ backface-visibility: hidden;
+ transition: -webkit-transform 0.6s ease-in-out;
+ transition: transform 0.6s ease-in-out;
+ transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .carousel-item {
+ transition: none;
+ }
+}
+
+.carousel-item.active,
+.carousel-item-next,
+.carousel-item-prev {
+ display: block;
+}
+
+/* rtl:begin:ignore */
+.carousel-item-next:not(.carousel-item-start),
+.active.carousel-item-end {
+ -webkit-transform: translateX(100%);
+ transform: translateX(100%);
+}
+
+.carousel-item-prev:not(.carousel-item-end),
+.active.carousel-item-start {
+ -webkit-transform: translateX(-100%);
+ transform: translateX(-100%);
+}
+
+/* rtl:end:ignore */
+.carousel-fade .carousel-item {
+ opacity: 0;
+ transition-property: opacity;
+ -webkit-transform: none;
+ transform: none;
+}
+
+.carousel-fade .carousel-item.active,
+.carousel-fade .carousel-item-next.carousel-item-start,
+.carousel-fade .carousel-item-prev.carousel-item-end {
+ z-index: 1;
+ opacity: 1;
+}
+
+.carousel-fade .active.carousel-item-start,
+.carousel-fade .active.carousel-item-end {
+ z-index: 0;
+ opacity: 0;
+ transition: opacity 0s 0.6s;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .carousel-fade .active.carousel-item-start,
+ .carousel-fade .active.carousel-item-end {
+ transition: none;
+ }
+}
+
+.carousel-control-prev,
+.carousel-control-next {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ z-index: 1;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: center;
+ justify-content: center;
+ width: 15%;
+ padding: 0;
+ color: #fff;
+ text-align: center;
+ background: none;
+ border: 0;
+ opacity: 0.5;
+ transition: opacity 0.15s ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .carousel-control-prev,
+ .carousel-control-next {
+ transition: none;
+ }
+}
+
+.carousel-control-prev:hover, .carousel-control-prev:focus,
+.carousel-control-next:hover,
+.carousel-control-next:focus {
+ color: #fff;
+ text-decoration: none;
+ outline: 0;
+ opacity: 0.9;
+}
+
+.carousel-control-prev {
+ left: 0;
+}
+
+.carousel-control-next {
+ right: 0;
+}
+
+.carousel-control-prev-icon,
+.carousel-control-next-icon {
+ display: inline-block;
+ width: 2rem;
+ height: 2rem;
+ background-repeat: no-repeat;
+ background-position: 50%;
+ background-size: 100% 100%;
+}
+
+/* rtl:options: {
+ "autoRename": true,
+ "stringMap":[ {
+ "name" : "prev-next",
+ "search" : "prev",
+ "replace" : "next"
+ } ]
+} */
+.carousel-control-prev-icon {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/%3e%3c/svg%3e");
+}
+
+.carousel-control-next-icon {
+ background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
+}
+
+.carousel-indicators {
+ position: absolute;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 2;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-pack: center;
+ justify-content: center;
+ padding: 0;
+ margin-right: 15%;
+ margin-bottom: 1rem;
+ margin-left: 15%;
+ list-style: none;
+}
+
+.carousel-indicators [data-bs-target] {
+ box-sizing: content-box;
+ -ms-flex: 0 1 auto;
+ flex: 0 1 auto;
+ width: 30px;
+ height: 3px;
+ padding: 0;
+ margin-right: 3px;
+ margin-left: 3px;
+ text-indent: -999px;
+ cursor: pointer;
+ background-color: #fff;
+ background-clip: padding-box;
+ border: 0;
+ border-top: 10px solid transparent;
+ border-bottom: 10px solid transparent;
+ opacity: 0.5;
+ transition: opacity 0.6s ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .carousel-indicators [data-bs-target] {
+ transition: none;
+ }
+}
+
+.carousel-indicators .active {
+ opacity: 1;
+}
+
+.carousel-caption {
+ position: absolute;
+ right: 15%;
+ bottom: 1.25rem;
+ left: 15%;
+ padding-top: 1.25rem;
+ padding-bottom: 1.25rem;
+ color: #fff;
+ text-align: center;
+}
+
+.carousel-dark .carousel-control-prev-icon,
+.carousel-dark .carousel-control-next-icon {
+ -webkit-filter: invert(1) grayscale(100);
+ filter: invert(1) grayscale(100);
+}
+
+.carousel-dark .carousel-indicators [data-bs-target] {
+ background-color: #000;
+}
+
+.carousel-dark .carousel-caption {
+ color: #000;
+}
+
+@-webkit-keyframes spinner-border {
+ to {
+ -webkit-transform: rotate(360deg) /* rtl:ignore */;
+ transform: rotate(360deg) /* rtl:ignore */;
+ }
+}
+
+@keyframes spinner-border {
+ to {
+ -webkit-transform: rotate(360deg) /* rtl:ignore */;
+ transform: rotate(360deg) /* rtl:ignore */;
+ }
+}
+
+.spinner-border {
+ display: inline-block;
+ width: 2rem;
+ height: 2rem;
+ vertical-align: -0.125em;
+ border: 0.25em solid currentColor;
+ border-right-color: transparent;
+ border-radius: 50%;
+ -webkit-animation: 0.75s linear infinite spinner-border;
+ animation: 0.75s linear infinite spinner-border;
+}
+
+.spinner-border-sm {
+ width: 1rem;
+ height: 1rem;
+ border-width: 0.2em;
+}
+
+@-webkit-keyframes spinner-grow {
+ 0% {
+ -webkit-transform: scale(0);
+ transform: scale(0);
+ }
+ 50% {
+ opacity: 1;
+ -webkit-transform: none;
+ transform: none;
+ }
+}
+
+@keyframes spinner-grow {
+ 0% {
+ -webkit-transform: scale(0);
+ transform: scale(0);
+ }
+ 50% {
+ opacity: 1;
+ -webkit-transform: none;
+ transform: none;
+ }
+}
+
+.spinner-grow {
+ display: inline-block;
+ width: 2rem;
+ height: 2rem;
+ vertical-align: -0.125em;
+ background-color: currentColor;
+ border-radius: 50%;
+ opacity: 0;
+ -webkit-animation: 0.75s linear infinite spinner-grow;
+ animation: 0.75s linear infinite spinner-grow;
+}
+
+.spinner-grow-sm {
+ width: 1rem;
+ height: 1rem;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .spinner-border,
+ .spinner-grow {
+ -webkit-animation-duration: 1.5s;
+ animation-duration: 1.5s;
+ }
+}
+
+.offcanvas {
+ position: fixed;
+ bottom: 0;
+ z-index: 1050;
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-direction: column;
+ flex-direction: column;
+ max-width: 100%;
+ visibility: hidden;
+ background-color: #303030;
+ background-clip: padding-box;
+ outline: 0;
+ transition: -webkit-transform 0.3s ease-in-out;
+ transition: transform 0.3s ease-in-out;
+ transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .offcanvas {
+ transition: none;
+ }
+}
+
+.offcanvas-header {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-align: center;
+ align-items: center;
+ -ms-flex-pack: justify;
+ justify-content: space-between;
+ padding: 1rem 1rem;
+}
+
+.offcanvas-header .btn-close {
+ padding: 0.5rem 0.5rem;
+ margin: -0.5rem -0.5rem -0.5rem auto;
+}
+
+.offcanvas-title {
+ margin-bottom: 0;
+ line-height: 1.5;
+}
+
+.offcanvas-body {
+ -ms-flex-positive: 1;
+ flex-grow: 1;
+ padding: 1rem 1rem;
+ overflow-y: auto;
+}
+
+.offcanvas-start {
+ top: 0;
+ left: 0;
+ width: 400px;
+ border-right: 1px solid #444;
+ -webkit-transform: translateX(-100%);
+ transform: translateX(-100%);
+}
+
+.offcanvas-end {
+ top: 0;
+ right: 0;
+ width: 400px;
+ border-left: 1px solid #444;
+ -webkit-transform: translateX(100%);
+ transform: translateX(100%);
+}
+
+.offcanvas-top {
+ top: 0;
+ right: 0;
+ left: 0;
+ height: 30vh;
+ max-height: 100%;
+ border-bottom: 1px solid #444;
+ -webkit-transform: translateY(-100%);
+ transform: translateY(-100%);
+}
+
+.offcanvas-bottom {
+ right: 0;
+ left: 0;
+ height: 30vh;
+ max-height: 100%;
+ border-top: 1px solid #444;
+ -webkit-transform: translateY(100%);
+ transform: translateY(100%);
+}
+
+.offcanvas.show {
+ -webkit-transform: none;
+ transform: none;
+}
+
+.clearfix::after {
+ display: block;
+ clear: both;
+ content: "";
+}
+
+.link-primary {
+ color: #375a7f;
+}
+
+.link-primary:hover, .link-primary:focus {
+ color: #2c4866;
+}
+
+.link-secondary {
+ color: #444;
+}
+
+.link-secondary:hover, .link-secondary:focus {
+ color: #363636;
+}
+
+.link-success {
+ color: #00bc8c;
+}
+
+.link-success:hover, .link-success:focus {
+ color: #009670;
+}
+
+.link-info {
+ color: #3498db;
+}
+
+.link-info:hover, .link-info:focus {
+ color: #2a7aaf;
+}
+
+.link-warning {
+ color: #f39c12;
+}
+
+.link-warning:hover, .link-warning:focus {
+ color: #c27d0e;
+}
+
+.link-danger {
+ color: #e74c3c;
+}
+
+.link-danger:hover, .link-danger:focus {
+ color: #b93d30;
+}
+
+.link-light {
+ color: #adb5bd;
+}
+
+.link-light:hover, .link-light:focus {
+ color: #bdc4ca;
+}
+
+.link-dark {
+ color: #303030;
+}
+
+.link-dark:hover, .link-dark:focus {
+ color: #262626;
+}
+
+.ratio {
+ position: relative;
+ width: 100%;
+}
+
+.ratio::before {
+ display: block;
+ padding-top: var(--bs-aspect-ratio);
+ content: "";
+}
+
+.ratio > * {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+}
+
+.ratio-1x1 {
+ --bs-aspect-ratio: 100%;
+}
+
+.ratio-4x3 {
+ --bs-aspect-ratio: calc(3 / 4 * 100%);
+}
+
+.ratio-16x9 {
+ --bs-aspect-ratio: calc(9 / 16 * 100%);
+}
+
+.ratio-21x9 {
+ --bs-aspect-ratio: calc(9 / 21 * 100%);
+}
+
+.fixed-top {
+ position: fixed;
+ top: 0;
+ right: 0;
+ left: 0;
+ z-index: 1030;
+}
+
+.fixed-bottom {
+ position: fixed;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1030;
+}
+
+.sticky-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+}
+
+@media (min-width: 576px) {
+ .sticky-sm-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+ }
+}
+
+@media (min-width: 768px) {
+ .sticky-md-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+ }
+}
+
+@media (min-width: 992px) {
+ .sticky-lg-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+ }
+}
+
+@media (min-width: 1200px) {
+ .sticky-xl-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+ }
+}
+
+@media (min-width: 1400px) {
+ .sticky-xxl-top {
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 1020;
+ }
+}
+
+.visually-hidden,
+.visually-hidden-focusable:not(:focus):not(:focus-within) {
+ position: absolute !important;
+ width: 1px !important;
+ height: 1px !important;
+ padding: 0 !important;
+ margin: -1px !important;
+ overflow: hidden !important;
+ clip: rect(0, 0, 0, 0) !important;
+ white-space: nowrap !important;
+ border: 0 !important;
+}
+
+.stretched-link::after {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1;
+ content: "";
+}
+
+.text-truncate {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.align-baseline {
+ vertical-align: baseline !important;
+}
+
+.align-top {
+ vertical-align: top !important;
+}
+
+.align-middle {
+ vertical-align: middle !important;
+}
+
+.align-bottom {
+ vertical-align: bottom !important;
+}
+
+.align-text-bottom {
+ vertical-align: text-bottom !important;
+}
+
+.align-text-top {
+ vertical-align: text-top !important;
+}
+
+.float-start {
+ float: left !important;
+}
+
+.float-end {
+ float: right !important;
+}
+
+.float-none {
+ float: none !important;
+}
+
+.overflow-auto {
+ overflow: auto !important;
+}
+
+.overflow-hidden {
+ overflow: hidden !important;
+}
+
+.overflow-visible {
+ overflow: visible !important;
+}
+
+.overflow-scroll {
+ overflow: scroll !important;
+}
+
+.d-inline {
+ display: inline !important;
+}
+
+.d-inline-block {
+ display: inline-block !important;
+}
+
+.d-block {
+ display: block !important;
+}
+
+.d-grid {
+ display: grid !important;
+}
+
+.d-table {
+ display: table !important;
+}
+
+.d-table-row {
+ display: table-row !important;
+}
+
+.d-table-cell {
+ display: table-cell !important;
+}
+
+.d-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+}
+
+.d-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+}
+
+.d-none {
+ display: none !important;
+}
+
+.shadow {
+ box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
+}
+
+.shadow-sm {
+ box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075) !important;
+}
+
+.shadow-lg {
+ box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175) !important;
+}
+
+.shadow-none {
+ box-shadow: none !important;
+}
+
+.position-static {
+ position: static !important;
+}
+
+.position-relative {
+ position: relative !important;
+}
+
+.position-absolute {
+ position: absolute !important;
+}
+
+.position-fixed {
+ position: fixed !important;
+}
+
+.position-sticky {
+ position: -webkit-sticky !important;
+ position: sticky !important;
+}
+
+.top-0 {
+ top: 0 !important;
+}
+
+.top-50 {
+ top: 50% !important;
+}
+
+.top-100 {
+ top: 100% !important;
+}
+
+.bottom-0 {
+ bottom: 0 !important;
+}
+
+.bottom-50 {
+ bottom: 50% !important;
+}
+
+.bottom-100 {
+ bottom: 100% !important;
+}
+
+.start-0 {
+ left: 0 !important;
+}
+
+.start-50 {
+ left: 50% !important;
+}
+
+.start-100 {
+ left: 100% !important;
+}
+
+.end-0 {
+ right: 0 !important;
+}
+
+.end-50 {
+ right: 50% !important;
+}
+
+.end-100 {
+ right: 100% !important;
+}
+
+.translate-middle {
+ -webkit-transform: translate(-50%, -50%) !important;
+ transform: translate(-50%, -50%) !important;
+}
+
+.translate-middle-x {
+ -webkit-transform: translateX(-50%) !important;
+ transform: translateX(-50%) !important;
+}
+
+.translate-middle-y {
+ -webkit-transform: translateY(-50%) !important;
+ transform: translateY(-50%) !important;
+}
+
+.border {
+ border: 1px solid #dee2e6 !important;
+}
+
+.border-0 {
+ border: 0 !important;
+}
+
+.border-top {
+ border-top: 1px solid #dee2e6 !important;
+}
+
+.border-top-0 {
+ border-top: 0 !important;
+}
+
+.border-end {
+ border-right: 1px solid #dee2e6 !important;
+}
+
+.border-end-0 {
+ border-right: 0 !important;
+}
+
+.border-bottom {
+ border-bottom: 1px solid #dee2e6 !important;
+}
+
+.border-bottom-0 {
+ border-bottom: 0 !important;
+}
+
+.border-start {
+ border-left: 1px solid #dee2e6 !important;
+}
+
+.border-start-0 {
+ border-left: 0 !important;
+}
+
+.border-primary {
+ border-color: #375a7f !important;
+}
+
+.border-secondary {
+ border-color: #444 !important;
+}
+
+.border-success {
+ border-color: #00bc8c !important;
+}
+
+.border-info {
+ border-color: #3498db !important;
+}
+
+.border-warning {
+ border-color: #f39c12 !important;
+}
+
+.border-danger {
+ border-color: #e74c3c !important;
+}
+
+.border-light {
+ border-color: #adb5bd !important;
+}
+
+.border-dark {
+ border-color: #303030 !important;
+}
+
+.border-white {
+ border-color: #fff !important;
+}
+
+.border-1 {
+ border-width: 1px !important;
+}
+
+.border-2 {
+ border-width: 2px !important;
+}
+
+.border-3 {
+ border-width: 3px !important;
+}
+
+.border-4 {
+ border-width: 4px !important;
+}
+
+.border-5 {
+ border-width: 5px !important;
+}
+
+.w-25 {
+ width: 25% !important;
+}
+
+.w-50 {
+ width: 50% !important;
+}
+
+.w-75 {
+ width: 75% !important;
+}
+
+.w-100 {
+ width: 100% !important;
+}
+
+.w-auto {
+ width: auto !important;
+}
+
+.mw-100 {
+ max-width: 100% !important;
+}
+
+.vw-100 {
+ width: 100vw !important;
+}
+
+.min-vw-100 {
+ min-width: 100vw !important;
+}
+
+.h-25 {
+ height: 25% !important;
+}
+
+.h-50 {
+ height: 50% !important;
+}
+
+.h-75 {
+ height: 75% !important;
+}
+
+.h-100 {
+ height: 100% !important;
+}
+
+.h-auto {
+ height: auto !important;
+}
+
+.mh-100 {
+ max-height: 100% !important;
+}
+
+.vh-100 {
+ height: 100vh !important;
+}
+
+.min-vh-100 {
+ min-height: 100vh !important;
+}
+
+.flex-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+}
+
+.flex-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+}
+
+.flex-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+}
+
+.flex-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+}
+
+.flex-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+}
+
+.flex-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+}
+
+.flex-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+}
+
+.flex-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+}
+
+.flex-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+}
+
+.flex-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+}
+
+.flex-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+}
+
+.flex-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+}
+
+.gap-0 {
+ gap: 0 !important;
+}
+
+.gap-1 {
+ gap: 0.25rem !important;
+}
+
+.gap-2 {
+ gap: 0.5rem !important;
+}
+
+.gap-3 {
+ gap: 1rem !important;
+}
+
+.gap-4 {
+ gap: 1.5rem !important;
+}
+
+.gap-5 {
+ gap: 3rem !important;
+}
+
+.justify-content-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+}
+
+.justify-content-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+}
+
+.justify-content-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+}
+
+.justify-content-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+}
+
+.justify-content-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+}
+
+.justify-content-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+}
+
+.align-items-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+}
+
+.align-items-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+}
+
+.align-items-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+}
+
+.align-items-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+}
+
+.align-items-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+}
+
+.align-content-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+}
+
+.align-content-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+}
+
+.align-content-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+}
+
+.align-content-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+}
+
+.align-content-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+}
+
+.align-content-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+}
+
+.align-self-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+}
+
+.align-self-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+}
+
+.align-self-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+}
+
+.align-self-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+}
+
+.align-self-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+}
+
+.align-self-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+}
+
+.order-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+}
+
+.order-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+}
+
+.order-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+}
+
+.order-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+}
+
+.order-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+}
+
+.order-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+}
+
+.order-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+}
+
+.order-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+}
+
+.m-0 {
+ margin: 0 !important;
+}
+
+.m-1 {
+ margin: 0.25rem !important;
+}
+
+.m-2 {
+ margin: 0.5rem !important;
+}
+
+.m-3 {
+ margin: 1rem !important;
+}
+
+.m-4 {
+ margin: 1.5rem !important;
+}
+
+.m-5 {
+ margin: 3rem !important;
+}
+
+.m-auto {
+ margin: auto !important;
+}
+
+.mx-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+}
+
+.mx-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+}
+
+.mx-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+}
+
+.mx-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+}
+
+.mx-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+}
+
+.mx-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+}
+
+.mx-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+}
+
+.my-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+}
+
+.my-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+}
+
+.my-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+}
+
+.my-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+}
+
+.my-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+}
+
+.my-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+}
+
+.my-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+}
+
+.mt-0 {
+ margin-top: 0 !important;
+}
+
+.mt-1 {
+ margin-top: 0.25rem !important;
+}
+
+.mt-2 {
+ margin-top: 0.5rem !important;
+}
+
+.mt-3 {
+ margin-top: 1rem !important;
+}
+
+.mt-4 {
+ margin-top: 1.5rem !important;
+}
+
+.mt-5 {
+ margin-top: 3rem !important;
+}
+
+.mt-auto {
+ margin-top: auto !important;
+}
+
+.me-0 {
+ margin-right: 0 !important;
+}
+
+.me-1 {
+ margin-right: 0.25rem !important;
+}
+
+.me-2 {
+ margin-right: 0.5rem !important;
+}
+
+.me-3 {
+ margin-right: 1rem !important;
+}
+
+.me-4 {
+ margin-right: 1.5rem !important;
+}
+
+.me-5 {
+ margin-right: 3rem !important;
+}
+
+.me-auto {
+ margin-right: auto !important;
+}
+
+.mb-0 {
+ margin-bottom: 0 !important;
+}
+
+.mb-1 {
+ margin-bottom: 0.25rem !important;
+}
+
+.mb-2 {
+ margin-bottom: 0.5rem !important;
+}
+
+.mb-3 {
+ margin-bottom: 1rem !important;
+}
+
+.mb-4 {
+ margin-bottom: 1.5rem !important;
+}
+
+.mb-5 {
+ margin-bottom: 3rem !important;
+}
+
+.mb-auto {
+ margin-bottom: auto !important;
+}
+
+.ms-0 {
+ margin-left: 0 !important;
+}
+
+.ms-1 {
+ margin-left: 0.25rem !important;
+}
+
+.ms-2 {
+ margin-left: 0.5rem !important;
+}
+
+.ms-3 {
+ margin-left: 1rem !important;
+}
+
+.ms-4 {
+ margin-left: 1.5rem !important;
+}
+
+.ms-5 {
+ margin-left: 3rem !important;
+}
+
+.ms-auto {
+ margin-left: auto !important;
+}
+
+.p-0 {
+ padding: 0 !important;
+}
+
+.p-1 {
+ padding: 0.25rem !important;
+}
+
+.p-2 {
+ padding: 0.5rem !important;
+}
+
+.p-3 {
+ padding: 1rem !important;
+}
+
+.p-4 {
+ padding: 1.5rem !important;
+}
+
+.p-5 {
+ padding: 3rem !important;
+}
+
+.px-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+}
+
+.px-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+}
+
+.px-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+}
+
+.px-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+}
+
+.px-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+}
+
+.px-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+}
+
+.py-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+}
+
+.py-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+}
+
+.py-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+}
+
+.py-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+}
+
+.py-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+}
+
+.py-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+}
+
+.pt-0 {
+ padding-top: 0 !important;
+}
+
+.pt-1 {
+ padding-top: 0.25rem !important;
+}
+
+.pt-2 {
+ padding-top: 0.5rem !important;
+}
+
+.pt-3 {
+ padding-top: 1rem !important;
+}
+
+.pt-4 {
+ padding-top: 1.5rem !important;
+}
+
+.pt-5 {
+ padding-top: 3rem !important;
+}
+
+.pe-0 {
+ padding-right: 0 !important;
+}
+
+.pe-1 {
+ padding-right: 0.25rem !important;
+}
+
+.pe-2 {
+ padding-right: 0.5rem !important;
+}
+
+.pe-3 {
+ padding-right: 1rem !important;
+}
+
+.pe-4 {
+ padding-right: 1.5rem !important;
+}
+
+.pe-5 {
+ padding-right: 3rem !important;
+}
+
+.pb-0 {
+ padding-bottom: 0 !important;
+}
+
+.pb-1 {
+ padding-bottom: 0.25rem !important;
+}
+
+.pb-2 {
+ padding-bottom: 0.5rem !important;
+}
+
+.pb-3 {
+ padding-bottom: 1rem !important;
+}
+
+.pb-4 {
+ padding-bottom: 1.5rem !important;
+}
+
+.pb-5 {
+ padding-bottom: 3rem !important;
+}
+
+.ps-0 {
+ padding-left: 0 !important;
+}
+
+.ps-1 {
+ padding-left: 0.25rem !important;
+}
+
+.ps-2 {
+ padding-left: 0.5rem !important;
+}
+
+.ps-3 {
+ padding-left: 1rem !important;
+}
+
+.ps-4 {
+ padding-left: 1.5rem !important;
+}
+
+.ps-5 {
+ padding-left: 3rem !important;
+}
+
+.font-monospace {
+ font-family: var(--bs-font-monospace) !important;
+}
+
+.fs-1 {
+ font-size: calc(1.425rem + 2.1vw) !important;
+}
+
+.fs-2 {
+ font-size: calc(1.375rem + 1.5vw) !important;
+}
+
+.fs-3 {
+ font-size: calc(1.325rem + 0.9vw) !important;
+}
+
+.fs-4 {
+ font-size: calc(1.275rem + 0.3vw) !important;
+}
+
+.fs-5 {
+ font-size: 1.25rem !important;
+}
+
+.fs-6 {
+ font-size: 1rem !important;
+}
+
+.fst-italic {
+ font-style: italic !important;
+}
+
+.fst-normal {
+ font-style: normal !important;
+}
+
+.fw-light {
+ font-weight: 300 !important;
+}
+
+.fw-lighter {
+ font-weight: lighter !important;
+}
+
+.fw-normal {
+ font-weight: 400 !important;
+}
+
+.fw-bold {
+ font-weight: 700 !important;
+}
+
+.fw-bolder {
+ font-weight: bolder !important;
+}
+
+.lh-1 {
+ line-height: 1 !important;
+}
+
+.lh-sm {
+ line-height: 1.25 !important;
+}
+
+.lh-base {
+ line-height: 1.5 !important;
+}
+
+.lh-lg {
+ line-height: 2 !important;
+}
+
+.text-start {
+ text-align: left !important;
+}
+
+.text-end {
+ text-align: right !important;
+}
+
+.text-center {
+ text-align: center !important;
+}
+
+.text-decoration-none {
+ text-decoration: none !important;
+}
+
+.text-decoration-underline {
+ text-decoration: underline !important;
+}
+
+.text-decoration-line-through {
+ text-decoration: line-through !important;
+}
+
+.text-lowercase {
+ text-transform: lowercase !important;
+}
+
+.text-uppercase {
+ text-transform: uppercase !important;
+}
+
+.text-capitalize {
+ text-transform: capitalize !important;
+}
+
+.text-wrap {
+ white-space: normal !important;
+}
+
+.text-nowrap {
+ white-space: nowrap !important;
+}
+
+/* rtl:begin:remove */
+.text-break {
+ word-wrap: break-word !important;
+ word-break: break-word !important;
+}
+
+/* rtl:end:remove */
+.text-primary {
+ color: #375a7f !important;
+}
+
+.text-secondary {
+ color: #444 !important;
+}
+
+.text-success {
+ color: #00bc8c !important;
+}
+
+.text-info {
+ color: #3498db !important;
+}
+
+.text-warning {
+ color: #f39c12 !important;
+}
+
+.text-danger {
+ color: #e74c3c !important;
+}
+
+.text-light {
+ color: #adb5bd !important;
+}
+
+.text-dark {
+ color: #303030 !important;
+}
+
+.text-white {
+ color: #fff !important;
+}
+
+.text-body {
+ color: #fff !important;
+}
+
+.text-muted {
+ color: #888 !important;
+}
+
+.text-black-50 {
+ color: rgba(0, 0, 0, 0.5) !important;
+}
+
+.text-white-50 {
+ color: rgba(255, 255, 255, 0.5) !important;
+}
+
+.text-reset {
+ color: inherit !important;
+}
+
+.bg-primary {
+ background-color: #375a7f !important;
+}
+
+.bg-secondary {
+ background-color: #444 !important;
+}
+
+.bg-success {
+ background-color: #00bc8c !important;
+}
+
+.bg-info {
+ background-color: #3498db !important;
+}
+
+.bg-warning {
+ background-color: #f39c12 !important;
+}
+
+.bg-danger {
+ background-color: #e74c3c !important;
+}
+
+.bg-light {
+ background-color: #adb5bd !important;
+}
+
+.bg-dark {
+ background-color: #303030 !important;
+}
+
+.bg-body {
+ background-color: #222 !important;
+}
+
+.bg-white {
+ background-color: #fff !important;
+}
+
+.bg-transparent {
+ background-color: transparent !important;
+}
+
+.bg-gradient {
+ background-image: var(--bs-gradient) !important;
+}
+
+.user-select-all {
+ -webkit-user-select: all !important;
+ -moz-user-select: all !important;
+ user-select: all !important;
+}
+
+.user-select-auto {
+ -webkit-user-select: auto !important;
+ -moz-user-select: auto !important;
+ -ms-user-select: auto !important;
+ user-select: auto !important;
+}
+
+.user-select-none {
+ -webkit-user-select: none !important;
+ -moz-user-select: none !important;
+ -ms-user-select: none !important;
+ user-select: none !important;
+}
+
+.pe-none {
+ pointer-events: none !important;
+}
+
+.pe-auto {
+ pointer-events: auto !important;
+}
+
+.rounded {
+ border-radius: 0.25rem !important;
+}
+
+.rounded-0 {
+ border-radius: 0 !important;
+}
+
+.rounded-1 {
+ border-radius: 0.2rem !important;
+}
+
+.rounded-2 {
+ border-radius: 0.25rem !important;
+}
+
+.rounded-3 {
+ border-radius: 0.3rem !important;
+}
+
+.rounded-circle {
+ border-radius: 50% !important;
+}
+
+.rounded-pill {
+ border-radius: 50rem !important;
+}
+
+.rounded-top {
+ border-top-left-radius: 0.25rem !important;
+ border-top-right-radius: 0.25rem !important;
+}
+
+.rounded-end {
+ border-top-right-radius: 0.25rem !important;
+ border-bottom-right-radius: 0.25rem !important;
+}
+
+.rounded-bottom {
+ border-bottom-right-radius: 0.25rem !important;
+ border-bottom-left-radius: 0.25rem !important;
+}
+
+.rounded-start {
+ border-bottom-left-radius: 0.25rem !important;
+ border-top-left-radius: 0.25rem !important;
+}
+
+.visible {
+ visibility: visible !important;
+}
+
+.invisible {
+ visibility: hidden !important;
+}
+
+@media (min-width: 576px) {
+ .float-sm-start {
+ float: left !important;
+ }
+ .float-sm-end {
+ float: right !important;
+ }
+ .float-sm-none {
+ float: none !important;
+ }
+ .d-sm-inline {
+ display: inline !important;
+ }
+ .d-sm-inline-block {
+ display: inline-block !important;
+ }
+ .d-sm-block {
+ display: block !important;
+ }
+ .d-sm-grid {
+ display: grid !important;
+ }
+ .d-sm-table {
+ display: table !important;
+ }
+ .d-sm-table-row {
+ display: table-row !important;
+ }
+ .d-sm-table-cell {
+ display: table-cell !important;
+ }
+ .d-sm-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-sm-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-sm-none {
+ display: none !important;
+ }
+ .flex-sm-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+ }
+ .flex-sm-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+ }
+ .flex-sm-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+ }
+ .flex-sm-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+ }
+ .flex-sm-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+ }
+ .flex-sm-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+ }
+ .flex-sm-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+ }
+ .flex-sm-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+ }
+ .flex-sm-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+ }
+ .flex-sm-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+ }
+ .flex-sm-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+ }
+ .flex-sm-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+ }
+ .gap-sm-0 {
+ gap: 0 !important;
+ }
+ .gap-sm-1 {
+ gap: 0.25rem !important;
+ }
+ .gap-sm-2 {
+ gap: 0.5rem !important;
+ }
+ .gap-sm-3 {
+ gap: 1rem !important;
+ }
+ .gap-sm-4 {
+ gap: 1.5rem !important;
+ }
+ .gap-sm-5 {
+ gap: 3rem !important;
+ }
+ .justify-content-sm-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+ }
+ .justify-content-sm-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+ }
+ .justify-content-sm-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+ }
+ .justify-content-sm-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+ }
+ .justify-content-sm-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+ }
+ .justify-content-sm-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+ }
+ .align-items-sm-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+ }
+ .align-items-sm-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+ }
+ .align-items-sm-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+ }
+ .align-items-sm-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+ }
+ .align-items-sm-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+ }
+ .align-content-sm-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+ }
+ .align-content-sm-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+ }
+ .align-content-sm-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+ }
+ .align-content-sm-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+ }
+ .align-content-sm-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+ }
+ .align-content-sm-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+ }
+ .align-self-sm-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+ }
+ .align-self-sm-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+ }
+ .align-self-sm-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+ }
+ .align-self-sm-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+ }
+ .align-self-sm-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+ }
+ .align-self-sm-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+ }
+ .order-sm-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+ }
+ .order-sm-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+ }
+ .order-sm-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+ }
+ .order-sm-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+ }
+ .order-sm-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+ }
+ .order-sm-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+ }
+ .order-sm-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+ }
+ .order-sm-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+ }
+ .m-sm-0 {
+ margin: 0 !important;
+ }
+ .m-sm-1 {
+ margin: 0.25rem !important;
+ }
+ .m-sm-2 {
+ margin: 0.5rem !important;
+ }
+ .m-sm-3 {
+ margin: 1rem !important;
+ }
+ .m-sm-4 {
+ margin: 1.5rem !important;
+ }
+ .m-sm-5 {
+ margin: 3rem !important;
+ }
+ .m-sm-auto {
+ margin: auto !important;
+ }
+ .mx-sm-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+ }
+ .mx-sm-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+ }
+ .mx-sm-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+ }
+ .mx-sm-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+ }
+ .mx-sm-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+ }
+ .mx-sm-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+ }
+ .mx-sm-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+ }
+ .my-sm-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ }
+ .my-sm-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+ }
+ .my-sm-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+ }
+ .my-sm-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+ }
+ .my-sm-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+ }
+ .my-sm-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+ }
+ .my-sm-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+ }
+ .mt-sm-0 {
+ margin-top: 0 !important;
+ }
+ .mt-sm-1 {
+ margin-top: 0.25rem !important;
+ }
+ .mt-sm-2 {
+ margin-top: 0.5rem !important;
+ }
+ .mt-sm-3 {
+ margin-top: 1rem !important;
+ }
+ .mt-sm-4 {
+ margin-top: 1.5rem !important;
+ }
+ .mt-sm-5 {
+ margin-top: 3rem !important;
+ }
+ .mt-sm-auto {
+ margin-top: auto !important;
+ }
+ .me-sm-0 {
+ margin-right: 0 !important;
+ }
+ .me-sm-1 {
+ margin-right: 0.25rem !important;
+ }
+ .me-sm-2 {
+ margin-right: 0.5rem !important;
+ }
+ .me-sm-3 {
+ margin-right: 1rem !important;
+ }
+ .me-sm-4 {
+ margin-right: 1.5rem !important;
+ }
+ .me-sm-5 {
+ margin-right: 3rem !important;
+ }
+ .me-sm-auto {
+ margin-right: auto !important;
+ }
+ .mb-sm-0 {
+ margin-bottom: 0 !important;
+ }
+ .mb-sm-1 {
+ margin-bottom: 0.25rem !important;
+ }
+ .mb-sm-2 {
+ margin-bottom: 0.5rem !important;
+ }
+ .mb-sm-3 {
+ margin-bottom: 1rem !important;
+ }
+ .mb-sm-4 {
+ margin-bottom: 1.5rem !important;
+ }
+ .mb-sm-5 {
+ margin-bottom: 3rem !important;
+ }
+ .mb-sm-auto {
+ margin-bottom: auto !important;
+ }
+ .ms-sm-0 {
+ margin-left: 0 !important;
+ }
+ .ms-sm-1 {
+ margin-left: 0.25rem !important;
+ }
+ .ms-sm-2 {
+ margin-left: 0.5rem !important;
+ }
+ .ms-sm-3 {
+ margin-left: 1rem !important;
+ }
+ .ms-sm-4 {
+ margin-left: 1.5rem !important;
+ }
+ .ms-sm-5 {
+ margin-left: 3rem !important;
+ }
+ .ms-sm-auto {
+ margin-left: auto !important;
+ }
+ .p-sm-0 {
+ padding: 0 !important;
+ }
+ .p-sm-1 {
+ padding: 0.25rem !important;
+ }
+ .p-sm-2 {
+ padding: 0.5rem !important;
+ }
+ .p-sm-3 {
+ padding: 1rem !important;
+ }
+ .p-sm-4 {
+ padding: 1.5rem !important;
+ }
+ .p-sm-5 {
+ padding: 3rem !important;
+ }
+ .px-sm-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+ }
+ .px-sm-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+ }
+ .px-sm-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+ }
+ .px-sm-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+ }
+ .px-sm-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+ }
+ .px-sm-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+ }
+ .py-sm-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ }
+ .py-sm-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+ }
+ .py-sm-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+ }
+ .py-sm-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+ }
+ .py-sm-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+ }
+ .py-sm-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+ }
+ .pt-sm-0 {
+ padding-top: 0 !important;
+ }
+ .pt-sm-1 {
+ padding-top: 0.25rem !important;
+ }
+ .pt-sm-2 {
+ padding-top: 0.5rem !important;
+ }
+ .pt-sm-3 {
+ padding-top: 1rem !important;
+ }
+ .pt-sm-4 {
+ padding-top: 1.5rem !important;
+ }
+ .pt-sm-5 {
+ padding-top: 3rem !important;
+ }
+ .pe-sm-0 {
+ padding-right: 0 !important;
+ }
+ .pe-sm-1 {
+ padding-right: 0.25rem !important;
+ }
+ .pe-sm-2 {
+ padding-right: 0.5rem !important;
+ }
+ .pe-sm-3 {
+ padding-right: 1rem !important;
+ }
+ .pe-sm-4 {
+ padding-right: 1.5rem !important;
+ }
+ .pe-sm-5 {
+ padding-right: 3rem !important;
+ }
+ .pb-sm-0 {
+ padding-bottom: 0 !important;
+ }
+ .pb-sm-1 {
+ padding-bottom: 0.25rem !important;
+ }
+ .pb-sm-2 {
+ padding-bottom: 0.5rem !important;
+ }
+ .pb-sm-3 {
+ padding-bottom: 1rem !important;
+ }
+ .pb-sm-4 {
+ padding-bottom: 1.5rem !important;
+ }
+ .pb-sm-5 {
+ padding-bottom: 3rem !important;
+ }
+ .ps-sm-0 {
+ padding-left: 0 !important;
+ }
+ .ps-sm-1 {
+ padding-left: 0.25rem !important;
+ }
+ .ps-sm-2 {
+ padding-left: 0.5rem !important;
+ }
+ .ps-sm-3 {
+ padding-left: 1rem !important;
+ }
+ .ps-sm-4 {
+ padding-left: 1.5rem !important;
+ }
+ .ps-sm-5 {
+ padding-left: 3rem !important;
+ }
+ .text-sm-start {
+ text-align: left !important;
+ }
+ .text-sm-end {
+ text-align: right !important;
+ }
+ .text-sm-center {
+ text-align: center !important;
+ }
+}
+
+@media (min-width: 768px) {
+ .float-md-start {
+ float: left !important;
+ }
+ .float-md-end {
+ float: right !important;
+ }
+ .float-md-none {
+ float: none !important;
+ }
+ .d-md-inline {
+ display: inline !important;
+ }
+ .d-md-inline-block {
+ display: inline-block !important;
+ }
+ .d-md-block {
+ display: block !important;
+ }
+ .d-md-grid {
+ display: grid !important;
+ }
+ .d-md-table {
+ display: table !important;
+ }
+ .d-md-table-row {
+ display: table-row !important;
+ }
+ .d-md-table-cell {
+ display: table-cell !important;
+ }
+ .d-md-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-md-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-md-none {
+ display: none !important;
+ }
+ .flex-md-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+ }
+ .flex-md-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+ }
+ .flex-md-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+ }
+ .flex-md-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+ }
+ .flex-md-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+ }
+ .flex-md-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+ }
+ .flex-md-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+ }
+ .flex-md-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+ }
+ .flex-md-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+ }
+ .flex-md-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+ }
+ .flex-md-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+ }
+ .flex-md-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+ }
+ .gap-md-0 {
+ gap: 0 !important;
+ }
+ .gap-md-1 {
+ gap: 0.25rem !important;
+ }
+ .gap-md-2 {
+ gap: 0.5rem !important;
+ }
+ .gap-md-3 {
+ gap: 1rem !important;
+ }
+ .gap-md-4 {
+ gap: 1.5rem !important;
+ }
+ .gap-md-5 {
+ gap: 3rem !important;
+ }
+ .justify-content-md-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+ }
+ .justify-content-md-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+ }
+ .justify-content-md-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+ }
+ .justify-content-md-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+ }
+ .justify-content-md-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+ }
+ .justify-content-md-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+ }
+ .align-items-md-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+ }
+ .align-items-md-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+ }
+ .align-items-md-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+ }
+ .align-items-md-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+ }
+ .align-items-md-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+ }
+ .align-content-md-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+ }
+ .align-content-md-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+ }
+ .align-content-md-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+ }
+ .align-content-md-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+ }
+ .align-content-md-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+ }
+ .align-content-md-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+ }
+ .align-self-md-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+ }
+ .align-self-md-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+ }
+ .align-self-md-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+ }
+ .align-self-md-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+ }
+ .align-self-md-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+ }
+ .align-self-md-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+ }
+ .order-md-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+ }
+ .order-md-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+ }
+ .order-md-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+ }
+ .order-md-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+ }
+ .order-md-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+ }
+ .order-md-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+ }
+ .order-md-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+ }
+ .order-md-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+ }
+ .m-md-0 {
+ margin: 0 !important;
+ }
+ .m-md-1 {
+ margin: 0.25rem !important;
+ }
+ .m-md-2 {
+ margin: 0.5rem !important;
+ }
+ .m-md-3 {
+ margin: 1rem !important;
+ }
+ .m-md-4 {
+ margin: 1.5rem !important;
+ }
+ .m-md-5 {
+ margin: 3rem !important;
+ }
+ .m-md-auto {
+ margin: auto !important;
+ }
+ .mx-md-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+ }
+ .mx-md-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+ }
+ .mx-md-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+ }
+ .mx-md-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+ }
+ .mx-md-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+ }
+ .mx-md-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+ }
+ .mx-md-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+ }
+ .my-md-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ }
+ .my-md-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+ }
+ .my-md-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+ }
+ .my-md-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+ }
+ .my-md-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+ }
+ .my-md-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+ }
+ .my-md-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+ }
+ .mt-md-0 {
+ margin-top: 0 !important;
+ }
+ .mt-md-1 {
+ margin-top: 0.25rem !important;
+ }
+ .mt-md-2 {
+ margin-top: 0.5rem !important;
+ }
+ .mt-md-3 {
+ margin-top: 1rem !important;
+ }
+ .mt-md-4 {
+ margin-top: 1.5rem !important;
+ }
+ .mt-md-5 {
+ margin-top: 3rem !important;
+ }
+ .mt-md-auto {
+ margin-top: auto !important;
+ }
+ .me-md-0 {
+ margin-right: 0 !important;
+ }
+ .me-md-1 {
+ margin-right: 0.25rem !important;
+ }
+ .me-md-2 {
+ margin-right: 0.5rem !important;
+ }
+ .me-md-3 {
+ margin-right: 1rem !important;
+ }
+ .me-md-4 {
+ margin-right: 1.5rem !important;
+ }
+ .me-md-5 {
+ margin-right: 3rem !important;
+ }
+ .me-md-auto {
+ margin-right: auto !important;
+ }
+ .mb-md-0 {
+ margin-bottom: 0 !important;
+ }
+ .mb-md-1 {
+ margin-bottom: 0.25rem !important;
+ }
+ .mb-md-2 {
+ margin-bottom: 0.5rem !important;
+ }
+ .mb-md-3 {
+ margin-bottom: 1rem !important;
+ }
+ .mb-md-4 {
+ margin-bottom: 1.5rem !important;
+ }
+ .mb-md-5 {
+ margin-bottom: 3rem !important;
+ }
+ .mb-md-auto {
+ margin-bottom: auto !important;
+ }
+ .ms-md-0 {
+ margin-left: 0 !important;
+ }
+ .ms-md-1 {
+ margin-left: 0.25rem !important;
+ }
+ .ms-md-2 {
+ margin-left: 0.5rem !important;
+ }
+ .ms-md-3 {
+ margin-left: 1rem !important;
+ }
+ .ms-md-4 {
+ margin-left: 1.5rem !important;
+ }
+ .ms-md-5 {
+ margin-left: 3rem !important;
+ }
+ .ms-md-auto {
+ margin-left: auto !important;
+ }
+ .p-md-0 {
+ padding: 0 !important;
+ }
+ .p-md-1 {
+ padding: 0.25rem !important;
+ }
+ .p-md-2 {
+ padding: 0.5rem !important;
+ }
+ .p-md-3 {
+ padding: 1rem !important;
+ }
+ .p-md-4 {
+ padding: 1.5rem !important;
+ }
+ .p-md-5 {
+ padding: 3rem !important;
+ }
+ .px-md-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+ }
+ .px-md-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+ }
+ .px-md-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+ }
+ .px-md-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+ }
+ .px-md-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+ }
+ .px-md-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+ }
+ .py-md-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ }
+ .py-md-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+ }
+ .py-md-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+ }
+ .py-md-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+ }
+ .py-md-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+ }
+ .py-md-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+ }
+ .pt-md-0 {
+ padding-top: 0 !important;
+ }
+ .pt-md-1 {
+ padding-top: 0.25rem !important;
+ }
+ .pt-md-2 {
+ padding-top: 0.5rem !important;
+ }
+ .pt-md-3 {
+ padding-top: 1rem !important;
+ }
+ .pt-md-4 {
+ padding-top: 1.5rem !important;
+ }
+ .pt-md-5 {
+ padding-top: 3rem !important;
+ }
+ .pe-md-0 {
+ padding-right: 0 !important;
+ }
+ .pe-md-1 {
+ padding-right: 0.25rem !important;
+ }
+ .pe-md-2 {
+ padding-right: 0.5rem !important;
+ }
+ .pe-md-3 {
+ padding-right: 1rem !important;
+ }
+ .pe-md-4 {
+ padding-right: 1.5rem !important;
+ }
+ .pe-md-5 {
+ padding-right: 3rem !important;
+ }
+ .pb-md-0 {
+ padding-bottom: 0 !important;
+ }
+ .pb-md-1 {
+ padding-bottom: 0.25rem !important;
+ }
+ .pb-md-2 {
+ padding-bottom: 0.5rem !important;
+ }
+ .pb-md-3 {
+ padding-bottom: 1rem !important;
+ }
+ .pb-md-4 {
+ padding-bottom: 1.5rem !important;
+ }
+ .pb-md-5 {
+ padding-bottom: 3rem !important;
+ }
+ .ps-md-0 {
+ padding-left: 0 !important;
+ }
+ .ps-md-1 {
+ padding-left: 0.25rem !important;
+ }
+ .ps-md-2 {
+ padding-left: 0.5rem !important;
+ }
+ .ps-md-3 {
+ padding-left: 1rem !important;
+ }
+ .ps-md-4 {
+ padding-left: 1.5rem !important;
+ }
+ .ps-md-5 {
+ padding-left: 3rem !important;
+ }
+ .text-md-start {
+ text-align: left !important;
+ }
+ .text-md-end {
+ text-align: right !important;
+ }
+ .text-md-center {
+ text-align: center !important;
+ }
+}
+
+@media (min-width: 992px) {
+ .float-lg-start {
+ float: left !important;
+ }
+ .float-lg-end {
+ float: right !important;
+ }
+ .float-lg-none {
+ float: none !important;
+ }
+ .d-lg-inline {
+ display: inline !important;
+ }
+ .d-lg-inline-block {
+ display: inline-block !important;
+ }
+ .d-lg-block {
+ display: block !important;
+ }
+ .d-lg-grid {
+ display: grid !important;
+ }
+ .d-lg-table {
+ display: table !important;
+ }
+ .d-lg-table-row {
+ display: table-row !important;
+ }
+ .d-lg-table-cell {
+ display: table-cell !important;
+ }
+ .d-lg-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-lg-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-lg-none {
+ display: none !important;
+ }
+ .flex-lg-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+ }
+ .flex-lg-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+ }
+ .flex-lg-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+ }
+ .flex-lg-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+ }
+ .flex-lg-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+ }
+ .flex-lg-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+ }
+ .flex-lg-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+ }
+ .flex-lg-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+ }
+ .flex-lg-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+ }
+ .flex-lg-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+ }
+ .flex-lg-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+ }
+ .flex-lg-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+ }
+ .gap-lg-0 {
+ gap: 0 !important;
+ }
+ .gap-lg-1 {
+ gap: 0.25rem !important;
+ }
+ .gap-lg-2 {
+ gap: 0.5rem !important;
+ }
+ .gap-lg-3 {
+ gap: 1rem !important;
+ }
+ .gap-lg-4 {
+ gap: 1.5rem !important;
+ }
+ .gap-lg-5 {
+ gap: 3rem !important;
+ }
+ .justify-content-lg-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+ }
+ .justify-content-lg-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+ }
+ .justify-content-lg-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+ }
+ .justify-content-lg-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+ }
+ .justify-content-lg-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+ }
+ .justify-content-lg-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+ }
+ .align-items-lg-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+ }
+ .align-items-lg-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+ }
+ .align-items-lg-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+ }
+ .align-items-lg-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+ }
+ .align-items-lg-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+ }
+ .align-content-lg-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+ }
+ .align-content-lg-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+ }
+ .align-content-lg-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+ }
+ .align-content-lg-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+ }
+ .align-content-lg-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+ }
+ .align-content-lg-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+ }
+ .align-self-lg-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+ }
+ .align-self-lg-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+ }
+ .align-self-lg-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+ }
+ .align-self-lg-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+ }
+ .align-self-lg-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+ }
+ .align-self-lg-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+ }
+ .order-lg-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+ }
+ .order-lg-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+ }
+ .order-lg-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+ }
+ .order-lg-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+ }
+ .order-lg-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+ }
+ .order-lg-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+ }
+ .order-lg-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+ }
+ .order-lg-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+ }
+ .m-lg-0 {
+ margin: 0 !important;
+ }
+ .m-lg-1 {
+ margin: 0.25rem !important;
+ }
+ .m-lg-2 {
+ margin: 0.5rem !important;
+ }
+ .m-lg-3 {
+ margin: 1rem !important;
+ }
+ .m-lg-4 {
+ margin: 1.5rem !important;
+ }
+ .m-lg-5 {
+ margin: 3rem !important;
+ }
+ .m-lg-auto {
+ margin: auto !important;
+ }
+ .mx-lg-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+ }
+ .mx-lg-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+ }
+ .mx-lg-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+ }
+ .mx-lg-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+ }
+ .mx-lg-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+ }
+ .mx-lg-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+ }
+ .mx-lg-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+ }
+ .my-lg-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ }
+ .my-lg-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+ }
+ .my-lg-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+ }
+ .my-lg-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+ }
+ .my-lg-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+ }
+ .my-lg-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+ }
+ .my-lg-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+ }
+ .mt-lg-0 {
+ margin-top: 0 !important;
+ }
+ .mt-lg-1 {
+ margin-top: 0.25rem !important;
+ }
+ .mt-lg-2 {
+ margin-top: 0.5rem !important;
+ }
+ .mt-lg-3 {
+ margin-top: 1rem !important;
+ }
+ .mt-lg-4 {
+ margin-top: 1.5rem !important;
+ }
+ .mt-lg-5 {
+ margin-top: 3rem !important;
+ }
+ .mt-lg-auto {
+ margin-top: auto !important;
+ }
+ .me-lg-0 {
+ margin-right: 0 !important;
+ }
+ .me-lg-1 {
+ margin-right: 0.25rem !important;
+ }
+ .me-lg-2 {
+ margin-right: 0.5rem !important;
+ }
+ .me-lg-3 {
+ margin-right: 1rem !important;
+ }
+ .me-lg-4 {
+ margin-right: 1.5rem !important;
+ }
+ .me-lg-5 {
+ margin-right: 3rem !important;
+ }
+ .me-lg-auto {
+ margin-right: auto !important;
+ }
+ .mb-lg-0 {
+ margin-bottom: 0 !important;
+ }
+ .mb-lg-1 {
+ margin-bottom: 0.25rem !important;
+ }
+ .mb-lg-2 {
+ margin-bottom: 0.5rem !important;
+ }
+ .mb-lg-3 {
+ margin-bottom: 1rem !important;
+ }
+ .mb-lg-4 {
+ margin-bottom: 1.5rem !important;
+ }
+ .mb-lg-5 {
+ margin-bottom: 3rem !important;
+ }
+ .mb-lg-auto {
+ margin-bottom: auto !important;
+ }
+ .ms-lg-0 {
+ margin-left: 0 !important;
+ }
+ .ms-lg-1 {
+ margin-left: 0.25rem !important;
+ }
+ .ms-lg-2 {
+ margin-left: 0.5rem !important;
+ }
+ .ms-lg-3 {
+ margin-left: 1rem !important;
+ }
+ .ms-lg-4 {
+ margin-left: 1.5rem !important;
+ }
+ .ms-lg-5 {
+ margin-left: 3rem !important;
+ }
+ .ms-lg-auto {
+ margin-left: auto !important;
+ }
+ .p-lg-0 {
+ padding: 0 !important;
+ }
+ .p-lg-1 {
+ padding: 0.25rem !important;
+ }
+ .p-lg-2 {
+ padding: 0.5rem !important;
+ }
+ .p-lg-3 {
+ padding: 1rem !important;
+ }
+ .p-lg-4 {
+ padding: 1.5rem !important;
+ }
+ .p-lg-5 {
+ padding: 3rem !important;
+ }
+ .px-lg-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+ }
+ .px-lg-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+ }
+ .px-lg-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+ }
+ .px-lg-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+ }
+ .px-lg-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+ }
+ .px-lg-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+ }
+ .py-lg-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ }
+ .py-lg-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+ }
+ .py-lg-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+ }
+ .py-lg-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+ }
+ .py-lg-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+ }
+ .py-lg-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+ }
+ .pt-lg-0 {
+ padding-top: 0 !important;
+ }
+ .pt-lg-1 {
+ padding-top: 0.25rem !important;
+ }
+ .pt-lg-2 {
+ padding-top: 0.5rem !important;
+ }
+ .pt-lg-3 {
+ padding-top: 1rem !important;
+ }
+ .pt-lg-4 {
+ padding-top: 1.5rem !important;
+ }
+ .pt-lg-5 {
+ padding-top: 3rem !important;
+ }
+ .pe-lg-0 {
+ padding-right: 0 !important;
+ }
+ .pe-lg-1 {
+ padding-right: 0.25rem !important;
+ }
+ .pe-lg-2 {
+ padding-right: 0.5rem !important;
+ }
+ .pe-lg-3 {
+ padding-right: 1rem !important;
+ }
+ .pe-lg-4 {
+ padding-right: 1.5rem !important;
+ }
+ .pe-lg-5 {
+ padding-right: 3rem !important;
+ }
+ .pb-lg-0 {
+ padding-bottom: 0 !important;
+ }
+ .pb-lg-1 {
+ padding-bottom: 0.25rem !important;
+ }
+ .pb-lg-2 {
+ padding-bottom: 0.5rem !important;
+ }
+ .pb-lg-3 {
+ padding-bottom: 1rem !important;
+ }
+ .pb-lg-4 {
+ padding-bottom: 1.5rem !important;
+ }
+ .pb-lg-5 {
+ padding-bottom: 3rem !important;
+ }
+ .ps-lg-0 {
+ padding-left: 0 !important;
+ }
+ .ps-lg-1 {
+ padding-left: 0.25rem !important;
+ }
+ .ps-lg-2 {
+ padding-left: 0.5rem !important;
+ }
+ .ps-lg-3 {
+ padding-left: 1rem !important;
+ }
+ .ps-lg-4 {
+ padding-left: 1.5rem !important;
+ }
+ .ps-lg-5 {
+ padding-left: 3rem !important;
+ }
+ .text-lg-start {
+ text-align: left !important;
+ }
+ .text-lg-end {
+ text-align: right !important;
+ }
+ .text-lg-center {
+ text-align: center !important;
+ }
+}
+
+@media (min-width: 1200px) {
+ .float-xl-start {
+ float: left !important;
+ }
+ .float-xl-end {
+ float: right !important;
+ }
+ .float-xl-none {
+ float: none !important;
+ }
+ .d-xl-inline {
+ display: inline !important;
+ }
+ .d-xl-inline-block {
+ display: inline-block !important;
+ }
+ .d-xl-block {
+ display: block !important;
+ }
+ .d-xl-grid {
+ display: grid !important;
+ }
+ .d-xl-table {
+ display: table !important;
+ }
+ .d-xl-table-row {
+ display: table-row !important;
+ }
+ .d-xl-table-cell {
+ display: table-cell !important;
+ }
+ .d-xl-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-xl-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-xl-none {
+ display: none !important;
+ }
+ .flex-xl-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+ }
+ .flex-xl-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+ }
+ .flex-xl-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+ }
+ .flex-xl-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+ }
+ .flex-xl-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+ }
+ .flex-xl-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+ }
+ .flex-xl-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+ }
+ .flex-xl-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+ }
+ .flex-xl-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+ }
+ .flex-xl-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+ }
+ .flex-xl-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+ }
+ .flex-xl-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+ }
+ .gap-xl-0 {
+ gap: 0 !important;
+ }
+ .gap-xl-1 {
+ gap: 0.25rem !important;
+ }
+ .gap-xl-2 {
+ gap: 0.5rem !important;
+ }
+ .gap-xl-3 {
+ gap: 1rem !important;
+ }
+ .gap-xl-4 {
+ gap: 1.5rem !important;
+ }
+ .gap-xl-5 {
+ gap: 3rem !important;
+ }
+ .justify-content-xl-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+ }
+ .justify-content-xl-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+ }
+ .justify-content-xl-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+ }
+ .justify-content-xl-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+ }
+ .justify-content-xl-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+ }
+ .justify-content-xl-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+ }
+ .align-items-xl-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+ }
+ .align-items-xl-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+ }
+ .align-items-xl-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+ }
+ .align-items-xl-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+ }
+ .align-items-xl-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+ }
+ .align-content-xl-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+ }
+ .align-content-xl-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+ }
+ .align-content-xl-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+ }
+ .align-content-xl-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+ }
+ .align-content-xl-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+ }
+ .align-content-xl-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+ }
+ .align-self-xl-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+ }
+ .align-self-xl-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+ }
+ .align-self-xl-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+ }
+ .align-self-xl-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+ }
+ .align-self-xl-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+ }
+ .align-self-xl-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+ }
+ .order-xl-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+ }
+ .order-xl-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+ }
+ .order-xl-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+ }
+ .order-xl-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+ }
+ .order-xl-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+ }
+ .order-xl-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+ }
+ .order-xl-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+ }
+ .order-xl-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+ }
+ .m-xl-0 {
+ margin: 0 !important;
+ }
+ .m-xl-1 {
+ margin: 0.25rem !important;
+ }
+ .m-xl-2 {
+ margin: 0.5rem !important;
+ }
+ .m-xl-3 {
+ margin: 1rem !important;
+ }
+ .m-xl-4 {
+ margin: 1.5rem !important;
+ }
+ .m-xl-5 {
+ margin: 3rem !important;
+ }
+ .m-xl-auto {
+ margin: auto !important;
+ }
+ .mx-xl-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+ }
+ .mx-xl-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+ }
+ .mx-xl-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+ }
+ .mx-xl-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+ }
+ .mx-xl-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+ }
+ .mx-xl-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+ }
+ .mx-xl-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+ }
+ .my-xl-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ }
+ .my-xl-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+ }
+ .my-xl-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+ }
+ .my-xl-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+ }
+ .my-xl-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+ }
+ .my-xl-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+ }
+ .my-xl-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+ }
+ .mt-xl-0 {
+ margin-top: 0 !important;
+ }
+ .mt-xl-1 {
+ margin-top: 0.25rem !important;
+ }
+ .mt-xl-2 {
+ margin-top: 0.5rem !important;
+ }
+ .mt-xl-3 {
+ margin-top: 1rem !important;
+ }
+ .mt-xl-4 {
+ margin-top: 1.5rem !important;
+ }
+ .mt-xl-5 {
+ margin-top: 3rem !important;
+ }
+ .mt-xl-auto {
+ margin-top: auto !important;
+ }
+ .me-xl-0 {
+ margin-right: 0 !important;
+ }
+ .me-xl-1 {
+ margin-right: 0.25rem !important;
+ }
+ .me-xl-2 {
+ margin-right: 0.5rem !important;
+ }
+ .me-xl-3 {
+ margin-right: 1rem !important;
+ }
+ .me-xl-4 {
+ margin-right: 1.5rem !important;
+ }
+ .me-xl-5 {
+ margin-right: 3rem !important;
+ }
+ .me-xl-auto {
+ margin-right: auto !important;
+ }
+ .mb-xl-0 {
+ margin-bottom: 0 !important;
+ }
+ .mb-xl-1 {
+ margin-bottom: 0.25rem !important;
+ }
+ .mb-xl-2 {
+ margin-bottom: 0.5rem !important;
+ }
+ .mb-xl-3 {
+ margin-bottom: 1rem !important;
+ }
+ .mb-xl-4 {
+ margin-bottom: 1.5rem !important;
+ }
+ .mb-xl-5 {
+ margin-bottom: 3rem !important;
+ }
+ .mb-xl-auto {
+ margin-bottom: auto !important;
+ }
+ .ms-xl-0 {
+ margin-left: 0 !important;
+ }
+ .ms-xl-1 {
+ margin-left: 0.25rem !important;
+ }
+ .ms-xl-2 {
+ margin-left: 0.5rem !important;
+ }
+ .ms-xl-3 {
+ margin-left: 1rem !important;
+ }
+ .ms-xl-4 {
+ margin-left: 1.5rem !important;
+ }
+ .ms-xl-5 {
+ margin-left: 3rem !important;
+ }
+ .ms-xl-auto {
+ margin-left: auto !important;
+ }
+ .p-xl-0 {
+ padding: 0 !important;
+ }
+ .p-xl-1 {
+ padding: 0.25rem !important;
+ }
+ .p-xl-2 {
+ padding: 0.5rem !important;
+ }
+ .p-xl-3 {
+ padding: 1rem !important;
+ }
+ .p-xl-4 {
+ padding: 1.5rem !important;
+ }
+ .p-xl-5 {
+ padding: 3rem !important;
+ }
+ .px-xl-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+ }
+ .px-xl-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+ }
+ .px-xl-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+ }
+ .px-xl-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+ }
+ .px-xl-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+ }
+ .px-xl-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+ }
+ .py-xl-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ }
+ .py-xl-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+ }
+ .py-xl-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+ }
+ .py-xl-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+ }
+ .py-xl-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+ }
+ .py-xl-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+ }
+ .pt-xl-0 {
+ padding-top: 0 !important;
+ }
+ .pt-xl-1 {
+ padding-top: 0.25rem !important;
+ }
+ .pt-xl-2 {
+ padding-top: 0.5rem !important;
+ }
+ .pt-xl-3 {
+ padding-top: 1rem !important;
+ }
+ .pt-xl-4 {
+ padding-top: 1.5rem !important;
+ }
+ .pt-xl-5 {
+ padding-top: 3rem !important;
+ }
+ .pe-xl-0 {
+ padding-right: 0 !important;
+ }
+ .pe-xl-1 {
+ padding-right: 0.25rem !important;
+ }
+ .pe-xl-2 {
+ padding-right: 0.5rem !important;
+ }
+ .pe-xl-3 {
+ padding-right: 1rem !important;
+ }
+ .pe-xl-4 {
+ padding-right: 1.5rem !important;
+ }
+ .pe-xl-5 {
+ padding-right: 3rem !important;
+ }
+ .pb-xl-0 {
+ padding-bottom: 0 !important;
+ }
+ .pb-xl-1 {
+ padding-bottom: 0.25rem !important;
+ }
+ .pb-xl-2 {
+ padding-bottom: 0.5rem !important;
+ }
+ .pb-xl-3 {
+ padding-bottom: 1rem !important;
+ }
+ .pb-xl-4 {
+ padding-bottom: 1.5rem !important;
+ }
+ .pb-xl-5 {
+ padding-bottom: 3rem !important;
+ }
+ .ps-xl-0 {
+ padding-left: 0 !important;
+ }
+ .ps-xl-1 {
+ padding-left: 0.25rem !important;
+ }
+ .ps-xl-2 {
+ padding-left: 0.5rem !important;
+ }
+ .ps-xl-3 {
+ padding-left: 1rem !important;
+ }
+ .ps-xl-4 {
+ padding-left: 1.5rem !important;
+ }
+ .ps-xl-5 {
+ padding-left: 3rem !important;
+ }
+ .text-xl-start {
+ text-align: left !important;
+ }
+ .text-xl-end {
+ text-align: right !important;
+ }
+ .text-xl-center {
+ text-align: center !important;
+ }
+}
+
+@media (min-width: 1400px) {
+ .float-xxl-start {
+ float: left !important;
+ }
+ .float-xxl-end {
+ float: right !important;
+ }
+ .float-xxl-none {
+ float: none !important;
+ }
+ .d-xxl-inline {
+ display: inline !important;
+ }
+ .d-xxl-inline-block {
+ display: inline-block !important;
+ }
+ .d-xxl-block {
+ display: block !important;
+ }
+ .d-xxl-grid {
+ display: grid !important;
+ }
+ .d-xxl-table {
+ display: table !important;
+ }
+ .d-xxl-table-row {
+ display: table-row !important;
+ }
+ .d-xxl-table-cell {
+ display: table-cell !important;
+ }
+ .d-xxl-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-xxl-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-xxl-none {
+ display: none !important;
+ }
+ .flex-xxl-fill {
+ -ms-flex: 1 1 auto !important;
+ flex: 1 1 auto !important;
+ }
+ .flex-xxl-row {
+ -ms-flex-direction: row !important;
+ flex-direction: row !important;
+ }
+ .flex-xxl-column {
+ -ms-flex-direction: column !important;
+ flex-direction: column !important;
+ }
+ .flex-xxl-row-reverse {
+ -ms-flex-direction: row-reverse !important;
+ flex-direction: row-reverse !important;
+ }
+ .flex-xxl-column-reverse {
+ -ms-flex-direction: column-reverse !important;
+ flex-direction: column-reverse !important;
+ }
+ .flex-xxl-grow-0 {
+ -ms-flex-positive: 0 !important;
+ flex-grow: 0 !important;
+ }
+ .flex-xxl-grow-1 {
+ -ms-flex-positive: 1 !important;
+ flex-grow: 1 !important;
+ }
+ .flex-xxl-shrink-0 {
+ -ms-flex-negative: 0 !important;
+ flex-shrink: 0 !important;
+ }
+ .flex-xxl-shrink-1 {
+ -ms-flex-negative: 1 !important;
+ flex-shrink: 1 !important;
+ }
+ .flex-xxl-wrap {
+ -ms-flex-wrap: wrap !important;
+ flex-wrap: wrap !important;
+ }
+ .flex-xxl-nowrap {
+ -ms-flex-wrap: nowrap !important;
+ flex-wrap: nowrap !important;
+ }
+ .flex-xxl-wrap-reverse {
+ -ms-flex-wrap: wrap-reverse !important;
+ flex-wrap: wrap-reverse !important;
+ }
+ .gap-xxl-0 {
+ gap: 0 !important;
+ }
+ .gap-xxl-1 {
+ gap: 0.25rem !important;
+ }
+ .gap-xxl-2 {
+ gap: 0.5rem !important;
+ }
+ .gap-xxl-3 {
+ gap: 1rem !important;
+ }
+ .gap-xxl-4 {
+ gap: 1.5rem !important;
+ }
+ .gap-xxl-5 {
+ gap: 3rem !important;
+ }
+ .justify-content-xxl-start {
+ -ms-flex-pack: start !important;
+ justify-content: flex-start !important;
+ }
+ .justify-content-xxl-end {
+ -ms-flex-pack: end !important;
+ justify-content: flex-end !important;
+ }
+ .justify-content-xxl-center {
+ -ms-flex-pack: center !important;
+ justify-content: center !important;
+ }
+ .justify-content-xxl-between {
+ -ms-flex-pack: justify !important;
+ justify-content: space-between !important;
+ }
+ .justify-content-xxl-around {
+ -ms-flex-pack: distribute !important;
+ justify-content: space-around !important;
+ }
+ .justify-content-xxl-evenly {
+ -ms-flex-pack: space-evenly !important;
+ justify-content: space-evenly !important;
+ }
+ .align-items-xxl-start {
+ -ms-flex-align: start !important;
+ align-items: flex-start !important;
+ }
+ .align-items-xxl-end {
+ -ms-flex-align: end !important;
+ align-items: flex-end !important;
+ }
+ .align-items-xxl-center {
+ -ms-flex-align: center !important;
+ align-items: center !important;
+ }
+ .align-items-xxl-baseline {
+ -ms-flex-align: baseline !important;
+ align-items: baseline !important;
+ }
+ .align-items-xxl-stretch {
+ -ms-flex-align: stretch !important;
+ align-items: stretch !important;
+ }
+ .align-content-xxl-start {
+ -ms-flex-line-pack: start !important;
+ align-content: flex-start !important;
+ }
+ .align-content-xxl-end {
+ -ms-flex-line-pack: end !important;
+ align-content: flex-end !important;
+ }
+ .align-content-xxl-center {
+ -ms-flex-line-pack: center !important;
+ align-content: center !important;
+ }
+ .align-content-xxl-between {
+ -ms-flex-line-pack: justify !important;
+ align-content: space-between !important;
+ }
+ .align-content-xxl-around {
+ -ms-flex-line-pack: distribute !important;
+ align-content: space-around !important;
+ }
+ .align-content-xxl-stretch {
+ -ms-flex-line-pack: stretch !important;
+ align-content: stretch !important;
+ }
+ .align-self-xxl-auto {
+ -ms-flex-item-align: auto !important;
+ align-self: auto !important;
+ }
+ .align-self-xxl-start {
+ -ms-flex-item-align: start !important;
+ align-self: flex-start !important;
+ }
+ .align-self-xxl-end {
+ -ms-flex-item-align: end !important;
+ align-self: flex-end !important;
+ }
+ .align-self-xxl-center {
+ -ms-flex-item-align: center !important;
+ align-self: center !important;
+ }
+ .align-self-xxl-baseline {
+ -ms-flex-item-align: baseline !important;
+ align-self: baseline !important;
+ }
+ .align-self-xxl-stretch {
+ -ms-flex-item-align: stretch !important;
+ align-self: stretch !important;
+ }
+ .order-xxl-first {
+ -ms-flex-order: -1 !important;
+ order: -1 !important;
+ }
+ .order-xxl-0 {
+ -ms-flex-order: 0 !important;
+ order: 0 !important;
+ }
+ .order-xxl-1 {
+ -ms-flex-order: 1 !important;
+ order: 1 !important;
+ }
+ .order-xxl-2 {
+ -ms-flex-order: 2 !important;
+ order: 2 !important;
+ }
+ .order-xxl-3 {
+ -ms-flex-order: 3 !important;
+ order: 3 !important;
+ }
+ .order-xxl-4 {
+ -ms-flex-order: 4 !important;
+ order: 4 !important;
+ }
+ .order-xxl-5 {
+ -ms-flex-order: 5 !important;
+ order: 5 !important;
+ }
+ .order-xxl-last {
+ -ms-flex-order: 6 !important;
+ order: 6 !important;
+ }
+ .m-xxl-0 {
+ margin: 0 !important;
+ }
+ .m-xxl-1 {
+ margin: 0.25rem !important;
+ }
+ .m-xxl-2 {
+ margin: 0.5rem !important;
+ }
+ .m-xxl-3 {
+ margin: 1rem !important;
+ }
+ .m-xxl-4 {
+ margin: 1.5rem !important;
+ }
+ .m-xxl-5 {
+ margin: 3rem !important;
+ }
+ .m-xxl-auto {
+ margin: auto !important;
+ }
+ .mx-xxl-0 {
+ margin-right: 0 !important;
+ margin-left: 0 !important;
+ }
+ .mx-xxl-1 {
+ margin-right: 0.25rem !important;
+ margin-left: 0.25rem !important;
+ }
+ .mx-xxl-2 {
+ margin-right: 0.5rem !important;
+ margin-left: 0.5rem !important;
+ }
+ .mx-xxl-3 {
+ margin-right: 1rem !important;
+ margin-left: 1rem !important;
+ }
+ .mx-xxl-4 {
+ margin-right: 1.5rem !important;
+ margin-left: 1.5rem !important;
+ }
+ .mx-xxl-5 {
+ margin-right: 3rem !important;
+ margin-left: 3rem !important;
+ }
+ .mx-xxl-auto {
+ margin-right: auto !important;
+ margin-left: auto !important;
+ }
+ .my-xxl-0 {
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ }
+ .my-xxl-1 {
+ margin-top: 0.25rem !important;
+ margin-bottom: 0.25rem !important;
+ }
+ .my-xxl-2 {
+ margin-top: 0.5rem !important;
+ margin-bottom: 0.5rem !important;
+ }
+ .my-xxl-3 {
+ margin-top: 1rem !important;
+ margin-bottom: 1rem !important;
+ }
+ .my-xxl-4 {
+ margin-top: 1.5rem !important;
+ margin-bottom: 1.5rem !important;
+ }
+ .my-xxl-5 {
+ margin-top: 3rem !important;
+ margin-bottom: 3rem !important;
+ }
+ .my-xxl-auto {
+ margin-top: auto !important;
+ margin-bottom: auto !important;
+ }
+ .mt-xxl-0 {
+ margin-top: 0 !important;
+ }
+ .mt-xxl-1 {
+ margin-top: 0.25rem !important;
+ }
+ .mt-xxl-2 {
+ margin-top: 0.5rem !important;
+ }
+ .mt-xxl-3 {
+ margin-top: 1rem !important;
+ }
+ .mt-xxl-4 {
+ margin-top: 1.5rem !important;
+ }
+ .mt-xxl-5 {
+ margin-top: 3rem !important;
+ }
+ .mt-xxl-auto {
+ margin-top: auto !important;
+ }
+ .me-xxl-0 {
+ margin-right: 0 !important;
+ }
+ .me-xxl-1 {
+ margin-right: 0.25rem !important;
+ }
+ .me-xxl-2 {
+ margin-right: 0.5rem !important;
+ }
+ .me-xxl-3 {
+ margin-right: 1rem !important;
+ }
+ .me-xxl-4 {
+ margin-right: 1.5rem !important;
+ }
+ .me-xxl-5 {
+ margin-right: 3rem !important;
+ }
+ .me-xxl-auto {
+ margin-right: auto !important;
+ }
+ .mb-xxl-0 {
+ margin-bottom: 0 !important;
+ }
+ .mb-xxl-1 {
+ margin-bottom: 0.25rem !important;
+ }
+ .mb-xxl-2 {
+ margin-bottom: 0.5rem !important;
+ }
+ .mb-xxl-3 {
+ margin-bottom: 1rem !important;
+ }
+ .mb-xxl-4 {
+ margin-bottom: 1.5rem !important;
+ }
+ .mb-xxl-5 {
+ margin-bottom: 3rem !important;
+ }
+ .mb-xxl-auto {
+ margin-bottom: auto !important;
+ }
+ .ms-xxl-0 {
+ margin-left: 0 !important;
+ }
+ .ms-xxl-1 {
+ margin-left: 0.25rem !important;
+ }
+ .ms-xxl-2 {
+ margin-left: 0.5rem !important;
+ }
+ .ms-xxl-3 {
+ margin-left: 1rem !important;
+ }
+ .ms-xxl-4 {
+ margin-left: 1.5rem !important;
+ }
+ .ms-xxl-5 {
+ margin-left: 3rem !important;
+ }
+ .ms-xxl-auto {
+ margin-left: auto !important;
+ }
+ .p-xxl-0 {
+ padding: 0 !important;
+ }
+ .p-xxl-1 {
+ padding: 0.25rem !important;
+ }
+ .p-xxl-2 {
+ padding: 0.5rem !important;
+ }
+ .p-xxl-3 {
+ padding: 1rem !important;
+ }
+ .p-xxl-4 {
+ padding: 1.5rem !important;
+ }
+ .p-xxl-5 {
+ padding: 3rem !important;
+ }
+ .px-xxl-0 {
+ padding-right: 0 !important;
+ padding-left: 0 !important;
+ }
+ .px-xxl-1 {
+ padding-right: 0.25rem !important;
+ padding-left: 0.25rem !important;
+ }
+ .px-xxl-2 {
+ padding-right: 0.5rem !important;
+ padding-left: 0.5rem !important;
+ }
+ .px-xxl-3 {
+ padding-right: 1rem !important;
+ padding-left: 1rem !important;
+ }
+ .px-xxl-4 {
+ padding-right: 1.5rem !important;
+ padding-left: 1.5rem !important;
+ }
+ .px-xxl-5 {
+ padding-right: 3rem !important;
+ padding-left: 3rem !important;
+ }
+ .py-xxl-0 {
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ }
+ .py-xxl-1 {
+ padding-top: 0.25rem !important;
+ padding-bottom: 0.25rem !important;
+ }
+ .py-xxl-2 {
+ padding-top: 0.5rem !important;
+ padding-bottom: 0.5rem !important;
+ }
+ .py-xxl-3 {
+ padding-top: 1rem !important;
+ padding-bottom: 1rem !important;
+ }
+ .py-xxl-4 {
+ padding-top: 1.5rem !important;
+ padding-bottom: 1.5rem !important;
+ }
+ .py-xxl-5 {
+ padding-top: 3rem !important;
+ padding-bottom: 3rem !important;
+ }
+ .pt-xxl-0 {
+ padding-top: 0 !important;
+ }
+ .pt-xxl-1 {
+ padding-top: 0.25rem !important;
+ }
+ .pt-xxl-2 {
+ padding-top: 0.5rem !important;
+ }
+ .pt-xxl-3 {
+ padding-top: 1rem !important;
+ }
+ .pt-xxl-4 {
+ padding-top: 1.5rem !important;
+ }
+ .pt-xxl-5 {
+ padding-top: 3rem !important;
+ }
+ .pe-xxl-0 {
+ padding-right: 0 !important;
+ }
+ .pe-xxl-1 {
+ padding-right: 0.25rem !important;
+ }
+ .pe-xxl-2 {
+ padding-right: 0.5rem !important;
+ }
+ .pe-xxl-3 {
+ padding-right: 1rem !important;
+ }
+ .pe-xxl-4 {
+ padding-right: 1.5rem !important;
+ }
+ .pe-xxl-5 {
+ padding-right: 3rem !important;
+ }
+ .pb-xxl-0 {
+ padding-bottom: 0 !important;
+ }
+ .pb-xxl-1 {
+ padding-bottom: 0.25rem !important;
+ }
+ .pb-xxl-2 {
+ padding-bottom: 0.5rem !important;
+ }
+ .pb-xxl-3 {
+ padding-bottom: 1rem !important;
+ }
+ .pb-xxl-4 {
+ padding-bottom: 1.5rem !important;
+ }
+ .pb-xxl-5 {
+ padding-bottom: 3rem !important;
+ }
+ .ps-xxl-0 {
+ padding-left: 0 !important;
+ }
+ .ps-xxl-1 {
+ padding-left: 0.25rem !important;
+ }
+ .ps-xxl-2 {
+ padding-left: 0.5rem !important;
+ }
+ .ps-xxl-3 {
+ padding-left: 1rem !important;
+ }
+ .ps-xxl-4 {
+ padding-left: 1.5rem !important;
+ }
+ .ps-xxl-5 {
+ padding-left: 3rem !important;
+ }
+ .text-xxl-start {
+ text-align: left !important;
+ }
+ .text-xxl-end {
+ text-align: right !important;
+ }
+ .text-xxl-center {
+ text-align: center !important;
+ }
+}
+
+@media (min-width: 1200px) {
+ .fs-1 {
+ font-size: 3rem !important;
+ }
+ .fs-2 {
+ font-size: 2.5rem !important;
+ }
+ .fs-3 {
+ font-size: 2rem !important;
+ }
+ .fs-4 {
+ font-size: 1.5rem !important;
+ }
+}
+
+@media print {
+ .d-print-inline {
+ display: inline !important;
+ }
+ .d-print-inline-block {
+ display: inline-block !important;
+ }
+ .d-print-block {
+ display: block !important;
+ }
+ .d-print-grid {
+ display: grid !important;
+ }
+ .d-print-table {
+ display: table !important;
+ }
+ .d-print-table-row {
+ display: table-row !important;
+ }
+ .d-print-table-cell {
+ display: table-cell !important;
+ }
+ .d-print-flex {
+ display: -ms-flexbox !important;
+ display: flex !important;
+ }
+ .d-print-inline-flex {
+ display: -ms-inline-flexbox !important;
+ display: inline-flex !important;
+ }
+ .d-print-none {
+ display: none !important;
+ }
+}
+
+.blockquote-footer {
+ color: #888;
+}
+
+.input-group-addon {
+ color: #fff;
+}
+
+.form-floating > label {
+ color: #444;
+}
+
+.nav-tabs .nav-link,
+.nav-tabs .nav-link.active,
+.nav-tabs .nav-link.active:focus,
+.nav-tabs .nav-link.active:hover,
+.nav-tabs .nav-item.open .nav-link,
+.nav-tabs .nav-item.open .nav-link:focus,
+.nav-tabs .nav-item.open .nav-link:hover,
+.nav-pills .nav-link,
+.nav-pills .nav-link.active,
+.nav-pills .nav-link.active:focus,
+.nav-pills .nav-link.active:hover,
+.nav-pills .nav-item.open .nav-link,
+.nav-pills .nav-item.open .nav-link:focus,
+.nav-pills .nav-item.open .nav-link:hover {
+ color: #fff;
+}
+
+.breadcrumb a {
+ color: #fff;
+}
+
+.pagination a:hover {
+ text-decoration: none;
+}
+
+.alert {
+ border: none;
+ color: #fff;
+}
+
+.alert a,
+.alert .alert-link {
+ color: #fff;
+ text-decoration: underline;
+}
+
+.alert-primary {
+ background-color: #375a7f;
+}
+
+.alert-secondary {
+ background-color: #444;
+}
+
+.alert-success {
+ background-color: #00bc8c;
+}
+
+.alert-info {
+ background-color: #3498db;
+}
+
+.alert-warning {
+ background-color: #f39c12;
+}
+
+.alert-danger {
+ background-color: #e74c3c;
+}
+
+.alert-light {
+ background-color: #adb5bd;
+}
+
+.alert-dark {
+ background-color: #303030;
+}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap.css b/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap.css
new file mode 100644
index 0000000..1cfdff2
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/bootstrap/bootstrap.css
@@ -0,0 +1,6763 @@
+/*!
+ * Bootstrap v3.3.6 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
+html {
+ font-family: sans-serif;
+ -webkit-text-size-adjust: 100%;
+ -ms-text-size-adjust: 100%;
+}
+
+body {
+/* margin: 0; */
+}
+
+article,
+aside,
+details,
+figcaption,
+figure,
+footer,
+header,
+hgroup,
+main,
+menu,
+nav,
+section,
+summary {
+ display: block;
+}
+audio,
+canvas,
+progress,
+video {
+ display: inline-block;
+ vertical-align: baseline;
+}
+audio:not([controls]) {
+ display: none;
+ height: 0;
+}
+[hidden],
+template {
+ display: none;
+}
+a {
+ background-color: transparent;
+}
+a:active,
+a:hover {
+ outline: 0;
+}
+abbr[title] {
+ border-bottom: 1px dotted;
+}
+b,
+strong {
+ font-weight: bold;
+}
+dfn {
+ font-style: italic;
+}
+h1 {
+ margin: .67em 0;
+ font-size: 2em;
+}
+mark {
+ color: #000;
+ background: #ff0;
+}
+small {
+ font-size: 80%;
+}
+sub,
+sup {
+ position: relative;
+ font-size: 75%;
+ line-height: 0;
+ vertical-align: baseline;
+}
+sup {
+ top: -.5em;
+}
+sub {
+ bottom: -.25em;
+}
+img {
+ border: 0;
+}
+svg:not(:root) {
+ overflow: hidden;
+}
+figure {
+ margin: 1em 40px;
+}
+hr {
+ height: 0;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+pre {
+ overflow: auto;
+}
+code,
+kbd,
+pre,
+samp {
+ font-family: monospace, monospace;
+ font-size: 1em;
+}
+button,
+input,
+optgroup,
+select,
+textarea {
+ margin: 0;
+ font: inherit;
+ color: inherit;
+}
+button {
+ overflow: visible;
+}
+button,
+select {
+ text-transform: none;
+}
+button,
+html input[type="button"],
+input[type="reset"],
+input[type="submit"] {
+ -webkit-appearance: button;
+ cursor: pointer;
+}
+button[disabled],
+html input[disabled] {
+ cursor: default;
+}
+button::-moz-focus-inner,
+input::-moz-focus-inner {
+ padding: 0;
+ border: 0;
+}
+input {
+ line-height: normal;
+}
+input[type="checkbox"],
+input[type="radio"] {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ padding: 0;
+}
+input[type="number"]::-webkit-inner-spin-button,
+input[type="number"]::-webkit-outer-spin-button {
+ height: auto;
+}
+input[type="search"] {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ -webkit-appearance: textfield;
+}
+input[type="search"]::-webkit-search-cancel-button,
+input[type="search"]::-webkit-search-decoration {
+ -webkit-appearance: none;
+}
+fieldset {
+ padding: .35em .625em .75em;
+ margin: 0 2px;
+ border: 1px solid #c0c0c0;
+}
+legend {
+ padding: 0;
+ border: 0;
+}
+textarea {
+ overflow: auto;
+}
+optgroup {
+ font-weight: bold;
+}
+table {
+ border-spacing: 0;
+ border-collapse: collapse;
+}
+td,
+th {
+ padding: 0;
+}
+/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
+@media print {
+ *,
+ *:before,
+ *:after {
+ color: #000 !important;
+ text-shadow: none !important;
+ background: transparent !important;
+ -webkit-box-shadow: none !important;
+ box-shadow: none !important;
+ }
+ a,
+ a:visited {
+ text-decoration: underline;
+ }
+ a[href]:after {
+ content: " (" attr(href) ")";
+ }
+ abbr[title]:after {
+ content: " (" attr(title) ")";
+ }
+ a[href^="#"]:after,
+ a[href^="javascript:"]:after {
+ content: "";
+ }
+ pre,
+ blockquote {
+ border: 1px solid #999;
+
+ page-break-inside: avoid;
+ }
+ thead {
+ display: table-header-group;
+ }
+ tr,
+ img {
+ page-break-inside: avoid;
+ }
+ img {
+ max-width: 100% !important;
+ }
+ p,
+ h2,
+ h3 {
+ orphans: 3;
+ widows: 3;
+ }
+ h2,
+ h3 {
+ page-break-after: avoid;
+ }
+ .navbar {
+ display: none;
+ }
+ .btn > .caret,
+ .dropup > .btn > .caret {
+ border-top-color: #000 !important;
+ }
+ .label {
+ border: 1px solid #000;
+ }
+ .table {
+ border-collapse: collapse !important;
+ }
+ .table td,
+ .table th {
+ background-color: #fff !important;
+ }
+ .table-bordered th,
+ .table-bordered td {
+ border: 1px solid #ddd !important;
+ }
+}
+@font-face {
+ font-family: 'Glyphicons Halflings';
+
+ src: url('../fonts/glyphicons-halflings-regular.eot');
+ src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
+}
+.glyphicon {
+ position: relative;
+ top: 1px;
+ display: inline-block;
+ font-family: 'Glyphicons Halflings';
+ font-style: normal;
+ font-weight: normal;
+ line-height: 1;
+
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+.glyphicon-asterisk:before {
+ content: "\002a";
+}
+.glyphicon-plus:before {
+ content: "\002b";
+}
+.glyphicon-euro:before,
+.glyphicon-eur:before {
+ content: "\20ac";
+}
+.glyphicon-minus:before {
+ content: "\2212";
+}
+.glyphicon-cloud:before {
+ content: "\2601";
+}
+.glyphicon-envelope:before {
+ content: "\2709";
+}
+.glyphicon-pencil:before {
+ content: "\270f";
+}
+.glyphicon-glass:before {
+ content: "\e001";
+}
+.glyphicon-music:before {
+ content: "\e002";
+}
+.glyphicon-search:before {
+ content: "\e003";
+}
+.glyphicon-heart:before {
+ content: "\e005";
+}
+.glyphicon-star:before {
+ content: "\e006";
+}
+.glyphicon-star-empty:before {
+ content: "\e007";
+}
+.glyphicon-user:before {
+ content: "\e008";
+}
+.glyphicon-film:before {
+ content: "\e009";
+}
+.glyphicon-th-large:before {
+ content: "\e010";
+}
+.glyphicon-th:before {
+ content: "\e011";
+}
+.glyphicon-th-list:before {
+ content: "\e012";
+}
+.glyphicon-ok:before {
+ content: "\e013";
+}
+.glyphicon-remove:before {
+ content: "\e014";
+}
+.glyphicon-zoom-in:before {
+ content: "\e015";
+}
+.glyphicon-zoom-out:before {
+ content: "\e016";
+}
+.glyphicon-off:before {
+ content: "\e017";
+}
+.glyphicon-signal:before {
+ content: "\e018";
+}
+.glyphicon-cog:before {
+ content: "\e019";
+}
+.glyphicon-trash:before {
+ content: "\e020";
+}
+.glyphicon-home:before {
+ content: "\e021";
+}
+.glyphicon-file:before {
+ content: "\e022";
+}
+.glyphicon-time:before {
+ content: "\e023";
+}
+.glyphicon-road:before {
+ content: "\e024";
+}
+.glyphicon-download-alt:before {
+ content: "\e025";
+}
+.glyphicon-download:before {
+ content: "\e026";
+}
+.glyphicon-upload:before {
+ content: "\e027";
+}
+.glyphicon-inbox:before {
+ content: "\e028";
+}
+.glyphicon-play-circle:before {
+ content: "\e029";
+}
+.glyphicon-repeat:before {
+ content: "\e030";
+}
+.glyphicon-refresh:before {
+ content: "\e031";
+}
+.glyphicon-list-alt:before {
+ content: "\e032";
+}
+.glyphicon-lock:before {
+ content: "\e033";
+}
+.glyphicon-flag:before {
+ content: "\e034";
+}
+.glyphicon-headphones:before {
+ content: "\e035";
+}
+.glyphicon-volume-off:before {
+ content: "\e036";
+}
+.glyphicon-volume-down:before {
+ content: "\e037";
+}
+.glyphicon-volume-up:before {
+ content: "\e038";
+}
+.glyphicon-qrcode:before {
+ content: "\e039";
+}
+.glyphicon-barcode:before {
+ content: "\e040";
+}
+.glyphicon-tag:before {
+ content: "\e041";
+}
+.glyphicon-tags:before {
+ content: "\e042";
+}
+.glyphicon-book:before {
+ content: "\e043";
+}
+.glyphicon-bookmark:before {
+ content: "\e044";
+}
+.glyphicon-print:before {
+ content: "\e045";
+}
+.glyphicon-camera:before {
+ content: "\e046";
+}
+.glyphicon-font:before {
+ content: "\e047";
+}
+.glyphicon-bold:before {
+ content: "\e048";
+}
+.glyphicon-italic:before {
+ content: "\e049";
+}
+.glyphicon-text-height:before {
+ content: "\e050";
+}
+.glyphicon-text-width:before {
+ content: "\e051";
+}
+.glyphicon-align-left:before {
+ content: "\e052";
+}
+.glyphicon-align-center:before {
+ content: "\e053";
+}
+.glyphicon-align-right:before {
+ content: "\e054";
+}
+.glyphicon-align-justify:before {
+ content: "\e055";
+}
+.glyphicon-list:before {
+ content: "\e056";
+}
+.glyphicon-indent-left:before {
+ content: "\e057";
+}
+.glyphicon-indent-right:before {
+ content: "\e058";
+}
+.glyphicon-facetime-video:before {
+ content: "\e059";
+}
+.glyphicon-picture:before {
+ content: "\e060";
+}
+.glyphicon-map-marker:before {
+ content: "\e062";
+}
+.glyphicon-adjust:before {
+ content: "\e063";
+}
+.glyphicon-tint:before {
+ content: "\e064";
+}
+.glyphicon-edit:before {
+ content: "\e065";
+}
+.glyphicon-share:before {
+ content: "\e066";
+}
+.glyphicon-check:before {
+ content: "\e067";
+}
+.glyphicon-move:before {
+ content: "\e068";
+}
+.glyphicon-step-backward:before {
+ content: "\e069";
+}
+.glyphicon-fast-backward:before {
+ content: "\e070";
+}
+.glyphicon-backward:before {
+ content: "\e071";
+}
+.glyphicon-play:before {
+ content: "\e072";
+}
+.glyphicon-pause:before {
+ content: "\e073";
+}
+.glyphicon-stop:before {
+ content: "\e074";
+}
+.glyphicon-forward:before {
+ content: "\e075";
+}
+.glyphicon-fast-forward:before {
+ content: "\e076";
+}
+.glyphicon-step-forward:before {
+ content: "\e077";
+}
+.glyphicon-eject:before {
+ content: "\e078";
+}
+.glyphicon-chevron-left:before {
+ content: "\e079";
+}
+.glyphicon-chevron-right:before {
+ content: "\e080";
+}
+.glyphicon-plus-sign:before {
+ content: "\e081";
+}
+.glyphicon-minus-sign:before {
+ content: "\e082";
+}
+.glyphicon-remove-sign:before {
+ content: "\e083";
+}
+.glyphicon-ok-sign:before {
+ content: "\e084";
+}
+.glyphicon-question-sign:before {
+ content: "\e085";
+}
+.glyphicon-info-sign:before {
+ content: "\e086";
+}
+.glyphicon-screenshot:before {
+ content: "\e087";
+}
+.glyphicon-remove-circle:before {
+ content: "\e088";
+}
+.glyphicon-ok-circle:before {
+ content: "\e089";
+}
+.glyphicon-ban-circle:before {
+ content: "\e090";
+}
+.glyphicon-arrow-left:before {
+ content: "\e091";
+}
+.glyphicon-arrow-right:before {
+ content: "\e092";
+}
+.glyphicon-arrow-up:before {
+ content: "\e093";
+}
+.glyphicon-arrow-down:before {
+ content: "\e094";
+}
+.glyphicon-share-alt:before {
+ content: "\e095";
+}
+.glyphicon-resize-full:before {
+ content: "\e096";
+}
+.glyphicon-resize-small:before {
+ content: "\e097";
+}
+.glyphicon-exclamation-sign:before {
+ content: "\e101";
+}
+.glyphicon-gift:before {
+ content: "\e102";
+}
+.glyphicon-leaf:before {
+ content: "\e103";
+}
+.glyphicon-fire:before {
+ content: "\e104";
+}
+.glyphicon-eye-open:before {
+ content: "\e105";
+}
+.glyphicon-eye-close:before {
+ content: "\e106";
+}
+.glyphicon-warning-sign:before {
+ content: "\e107";
+}
+.glyphicon-plane:before {
+ content: "\e108";
+}
+.glyphicon-calendar:before {
+ content: "\e109";
+}
+.glyphicon-random:before {
+ content: "\e110";
+}
+.glyphicon-comment:before {
+ content: "\e111";
+}
+.glyphicon-magnet:before {
+ content: "\e112";
+}
+.glyphicon-chevron-up:before {
+ content: "\e113";
+}
+.glyphicon-chevron-down:before {
+ content: "\e114";
+}
+.glyphicon-retweet:before {
+ content: "\e115";
+}
+.glyphicon-shopping-cart:before {
+ content: "\e116";
+}
+.glyphicon-folder-close:before {
+ content: "\e117";
+}
+.glyphicon-folder-open:before {
+ content: "\e118";
+}
+.glyphicon-resize-vertical:before {
+ content: "\e119";
+}
+.glyphicon-resize-horizontal:before {
+ content: "\e120";
+}
+.glyphicon-hdd:before {
+ content: "\e121";
+}
+.glyphicon-bullhorn:before {
+ content: "\e122";
+}
+.glyphicon-bell:before {
+ content: "\e123";
+}
+.glyphicon-certificate:before {
+ content: "\e124";
+}
+.glyphicon-thumbs-up:before {
+ content: "\e125";
+}
+.glyphicon-thumbs-down:before {
+ content: "\e126";
+}
+.glyphicon-hand-right:before {
+ content: "\e127";
+}
+.glyphicon-hand-left:before {
+ content: "\e128";
+}
+.glyphicon-hand-up:before {
+ content: "\e129";
+}
+.glyphicon-hand-down:before {
+ content: "\e130";
+}
+.glyphicon-circle-arrow-right:before {
+ content: "\e131";
+}
+.glyphicon-circle-arrow-left:before {
+ content: "\e132";
+}
+.glyphicon-circle-arrow-up:before {
+ content: "\e133";
+}
+.glyphicon-circle-arrow-down:before {
+ content: "\e134";
+}
+.glyphicon-globe:before {
+ content: "\e135";
+}
+.glyphicon-wrench:before {
+ content: "\e136";
+}
+.glyphicon-tasks:before {
+ content: "\e137";
+}
+.glyphicon-filter:before {
+ content: "\e138";
+}
+.glyphicon-briefcase:before {
+ content: "\e139";
+}
+.glyphicon-fullscreen:before {
+ content: "\e140";
+}
+.glyphicon-dashboard:before {
+ content: "\e141";
+}
+.glyphicon-paperclip:before {
+ content: "\e142";
+}
+.glyphicon-heart-empty:before {
+ content: "\e143";
+}
+.glyphicon-link:before {
+ content: "\e144";
+}
+.glyphicon-phone:before {
+ content: "\e145";
+}
+.glyphicon-pushpin:before {
+ content: "\e146";
+}
+.glyphicon-usd:before {
+ content: "\e148";
+}
+.glyphicon-gbp:before {
+ content: "\e149";
+}
+.glyphicon-sort:before {
+ content: "\e150";
+}
+.glyphicon-sort-by-alphabet:before {
+ content: "\e151";
+}
+.glyphicon-sort-by-alphabet-alt:before {
+ content: "\e152";
+}
+.glyphicon-sort-by-order:before {
+ content: "\e153";
+}
+.glyphicon-sort-by-order-alt:before {
+ content: "\e154";
+}
+.glyphicon-sort-by-attributes:before {
+ content: "\e155";
+}
+.glyphicon-sort-by-attributes-alt:before {
+ content: "\e156";
+}
+.glyphicon-unchecked:before {
+ content: "\e157";
+}
+.glyphicon-expand:before {
+ content: "\e158";
+}
+.glyphicon-collapse-down:before {
+ content: "\e159";
+}
+.glyphicon-collapse-up:before {
+ content: "\e160";
+}
+.glyphicon-log-in:before {
+ content: "\e161";
+}
+.glyphicon-flash:before {
+ content: "\e162";
+}
+.glyphicon-log-out:before {
+ content: "\e163";
+}
+.glyphicon-new-window:before {
+ content: "\e164";
+}
+.glyphicon-record:before {
+ content: "\e165";
+}
+.glyphicon-save:before {
+ content: "\e166";
+}
+.glyphicon-open:before {
+ content: "\e167";
+}
+.glyphicon-saved:before {
+ content: "\e168";
+}
+.glyphicon-import:before {
+ content: "\e169";
+}
+.glyphicon-export:before {
+ content: "\e170";
+}
+.glyphicon-send:before {
+ content: "\e171";
+}
+.glyphicon-floppy-disk:before {
+ content: "\e172";
+}
+.glyphicon-floppy-saved:before {
+ content: "\e173";
+}
+.glyphicon-floppy-remove:before {
+ content: "\e174";
+}
+.glyphicon-floppy-save:before {
+ content: "\e175";
+}
+.glyphicon-floppy-open:before {
+ content: "\e176";
+}
+.glyphicon-credit-card:before {
+ content: "\e177";
+}
+.glyphicon-transfer:before {
+ content: "\e178";
+}
+.glyphicon-cutlery:before {
+ content: "\e179";
+}
+.glyphicon-header:before {
+ content: "\e180";
+}
+.glyphicon-compressed:before {
+ content: "\e181";
+}
+.glyphicon-earphone:before {
+ content: "\e182";
+}
+.glyphicon-phone-alt:before {
+ content: "\e183";
+}
+.glyphicon-tower:before {
+ content: "\e184";
+}
+.glyphicon-stats:before {
+ content: "\e185";
+}
+.glyphicon-sd-video:before {
+ content: "\e186";
+}
+.glyphicon-hd-video:before {
+ content: "\e187";
+}
+.glyphicon-subtitles:before {
+ content: "\e188";
+}
+.glyphicon-sound-stereo:before {
+ content: "\e189";
+}
+.glyphicon-sound-dolby:before {
+ content: "\e190";
+}
+.glyphicon-sound-5-1:before {
+ content: "\e191";
+}
+.glyphicon-sound-6-1:before {
+ content: "\e192";
+}
+.glyphicon-sound-7-1:before {
+ content: "\e193";
+}
+.glyphicon-copyright-mark:before {
+ content: "\e194";
+}
+.glyphicon-registration-mark:before {
+ content: "\e195";
+}
+.glyphicon-cloud-download:before {
+ content: "\e197";
+}
+.glyphicon-cloud-upload:before {
+ content: "\e198";
+}
+.glyphicon-tree-conifer:before {
+ content: "\e199";
+}
+.glyphicon-tree-deciduous:before {
+ content: "\e200";
+}
+.glyphicon-cd:before {
+ content: "\e201";
+}
+.glyphicon-save-file:before {
+ content: "\e202";
+}
+.glyphicon-open-file:before {
+ content: "\e203";
+}
+.glyphicon-level-up:before {
+ content: "\e204";
+}
+.glyphicon-copy:before {
+ content: "\e205";
+}
+.glyphicon-paste:before {
+ content: "\e206";
+}
+.glyphicon-alert:before {
+ content: "\e209";
+}
+.glyphicon-equalizer:before {
+ content: "\e210";
+}
+.glyphicon-king:before {
+ content: "\e211";
+}
+.glyphicon-queen:before {
+ content: "\e212";
+}
+.glyphicon-pawn:before {
+ content: "\e213";
+}
+.glyphicon-bishop:before {
+ content: "\e214";
+}
+.glyphicon-knight:before {
+ content: "\e215";
+}
+.glyphicon-baby-formula:before {
+ content: "\e216";
+}
+.glyphicon-tent:before {
+ content: "\26fa";
+}
+.glyphicon-blackboard:before {
+ content: "\e218";
+}
+.glyphicon-bed:before {
+ content: "\e219";
+}
+.glyphicon-apple:before {
+ content: "\f8ff";
+}
+.glyphicon-erase:before {
+ content: "\e221";
+}
+.glyphicon-hourglass:before {
+ content: "\231b";
+}
+.glyphicon-lamp:before {
+ content: "\e223";
+}
+.glyphicon-duplicate:before {
+ content: "\e224";
+}
+.glyphicon-piggy-bank:before {
+ content: "\e225";
+}
+.glyphicon-scissors:before {
+ content: "\e226";
+}
+.glyphicon-bitcoin:before {
+ content: "\e227";
+}
+.glyphicon-btc:before {
+ content: "\e227";
+}
+.glyphicon-xbt:before {
+ content: "\e227";
+}
+.glyphicon-yen:before {
+ content: "\00a5";
+}
+.glyphicon-jpy:before {
+ content: "\00a5";
+}
+.glyphicon-ruble:before {
+ content: "\20bd";
+}
+.glyphicon-rub:before {
+ content: "\20bd";
+}
+.glyphicon-scale:before {
+ content: "\e230";
+}
+.glyphicon-ice-lolly:before {
+ content: "\e231";
+}
+.glyphicon-ice-lolly-tasted:before {
+ content: "\e232";
+}
+.glyphicon-education:before {
+ content: "\e233";
+}
+.glyphicon-option-horizontal:before {
+ content: "\e234";
+}
+.glyphicon-option-vertical:before {
+ content: "\e235";
+}
+.glyphicon-menu-hamburger:before {
+ content: "\e236";
+}
+.glyphicon-modal-window:before {
+ content: "\e237";
+}
+.glyphicon-oil:before {
+ content: "\e238";
+}
+.glyphicon-grain:before {
+ content: "\e239";
+}
+.glyphicon-sunglasses:before {
+ content: "\e240";
+}
+.glyphicon-text-size:before {
+ content: "\e241";
+}
+.glyphicon-text-color:before {
+ content: "\e242";
+}
+.glyphicon-text-background:before {
+ content: "\e243";
+}
+.glyphicon-object-align-top:before {
+ content: "\e244";
+}
+.glyphicon-object-align-bottom:before {
+ content: "\e245";
+}
+.glyphicon-object-align-horizontal:before {
+ content: "\e246";
+}
+.glyphicon-object-align-left:before {
+ content: "\e247";
+}
+.glyphicon-object-align-vertical:before {
+ content: "\e248";
+}
+.glyphicon-object-align-right:before {
+ content: "\e249";
+}
+.glyphicon-triangle-right:before {
+ content: "\e250";
+}
+.glyphicon-triangle-left:before {
+ content: "\e251";
+}
+.glyphicon-triangle-bottom:before {
+ content: "\e252";
+}
+.glyphicon-triangle-top:before {
+ content: "\e253";
+}
+.glyphicon-console:before {
+ content: "\e254";
+}
+.glyphicon-superscript:before {
+ content: "\e255";
+}
+.glyphicon-subscript:before {
+ content: "\e256";
+}
+.glyphicon-menu-left:before {
+ content: "\e257";
+}
+.glyphicon-menu-right:before {
+ content: "\e258";
+}
+.glyphicon-menu-down:before {
+ content: "\e259";
+}
+.glyphicon-menu-up:before {
+ content: "\e260";
+}
+* {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+*:before,
+*:after {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+html {
+ font-size: 10px;
+
+ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
+}
+body {
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #333;
+ background-color: #fff;
+}
+input,
+button,
+select,
+textarea {
+ font-family: inherit;
+ font-size: inherit;
+ line-height: inherit;
+}
+a {
+ color: #337ab7;
+ text-decoration: none;
+}
+a:hover,
+a:focus {
+ color: #23527c;
+ text-decoration: underline;
+}
+a:focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+figure {
+ margin: 0;
+}
+img {
+ vertical-align: middle;
+}
+.img-responsive,
+.thumbnail > img,
+.thumbnail a > img,
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+}
+.img-rounded {
+ border-radius: 6px;
+}
+.img-thumbnail {
+ display: inline-block;
+ max-width: 100%;
+ height: auto;
+ padding: 4px;
+ line-height: 1.42857143;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ -webkit-transition: all .2s ease-in-out;
+ -o-transition: all .2s ease-in-out;
+ transition: all .2s ease-in-out;
+}
+.img-circle {
+ border-radius: 50%;
+}
+hr {
+ margin-top: 20px;
+ margin-bottom: 20px;
+ border: 0;
+ border-top: 1px solid #eee;
+}
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ border: 0;
+}
+.sr-only-focusable:active,
+.sr-only-focusable:focus {
+ position: static;
+ width: auto;
+ height: auto;
+ margin: 0;
+ overflow: visible;
+ clip: auto;
+}
+[role="button"] {
+ cursor: pointer;
+}
+h1,
+h2,
+h3,
+h4,
+h5,
+h6,
+.h1,
+.h2,
+.h3,
+.h4,
+.h5,
+.h6 {
+ font-family: inherit;
+ font-weight: 500;
+ line-height: 1.1;
+ color: inherit;
+}
+h1 small,
+h2 small,
+h3 small,
+h4 small,
+h5 small,
+h6 small,
+.h1 small,
+.h2 small,
+.h3 small,
+.h4 small,
+.h5 small,
+.h6 small,
+h1 .small,
+h2 .small,
+h3 .small,
+h4 .small,
+h5 .small,
+h6 .small,
+.h1 .small,
+.h2 .small,
+.h3 .small,
+.h4 .small,
+.h5 .small,
+.h6 .small {
+ font-weight: normal;
+ line-height: 1;
+ color: #777;
+}
+h1,
+.h1,
+h2,
+.h2,
+h3,
+.h3 {
+ margin-top: 20px;
+ margin-bottom: 10px;
+}
+h1 small,
+.h1 small,
+h2 small,
+.h2 small,
+h3 small,
+.h3 small,
+h1 .small,
+.h1 .small,
+h2 .small,
+.h2 .small,
+h3 .small,
+.h3 .small {
+ font-size: 65%;
+}
+h4,
+.h4,
+h5,
+.h5,
+h6,
+.h6 {
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+h4 small,
+.h4 small,
+h5 small,
+.h5 small,
+h6 small,
+.h6 small,
+h4 .small,
+.h4 .small,
+h5 .small,
+.h5 .small,
+h6 .small,
+.h6 .small {
+ font-size: 75%;
+}
+h1,
+.h1 {
+ font-size: 36px;
+}
+h2,
+.h2 {
+ font-size: 30px;
+}
+h3,
+.h3 {
+ font-size: 24px;
+}
+h4,
+.h4 {
+ font-size: 18px;
+}
+h5,
+.h5 {
+ font-size: 14px;
+}
+h6,
+.h6 {
+ font-size: 12px;
+}
+p {
+ margin: 0 0 10px;
+}
+.lead {
+ margin-bottom: 20px;
+ font-size: 16px;
+ font-weight: 300;
+ line-height: 1.4;
+}
+@media (min-width: 768px) {
+ .lead {
+ font-size: 21px;
+ }
+}
+small,
+.small {
+ font-size: 85%;
+}
+mark,
+.mark {
+ padding: .2em;
+ background-color: #fcf8e3;
+}
+.text-left {
+ text-align: left;
+}
+.text-right {
+ text-align: right;
+}
+.text-center {
+ text-align: center;
+}
+.text-justify {
+ text-align: justify;
+}
+.text-nowrap {
+ white-space: nowrap;
+}
+.text-lowercase {
+ text-transform: lowercase;
+}
+.text-uppercase {
+ text-transform: uppercase;
+}
+.text-capitalize {
+ text-transform: capitalize;
+}
+.text-muted {
+ color: #777;
+}
+.text-primary {
+ color: #337ab7;
+}
+a.text-primary:hover,
+a.text-primary:focus {
+ color: #286090;
+}
+.text-success {
+ color: #3c763d;
+}
+a.text-success:hover,
+a.text-success:focus {
+ color: #2b542c;
+}
+.text-info {
+ color: #31708f;
+}
+a.text-info:hover,
+a.text-info:focus {
+ color: #245269;
+}
+.text-warning {
+ color: #8a6d3b;
+}
+a.text-warning:hover,
+a.text-warning:focus {
+ color: #66512c;
+}
+.text-danger {
+ color: #a94442;
+}
+a.text-danger:hover,
+a.text-danger:focus {
+ color: #843534;
+}
+.bg-primary {
+ color: #fff;
+ background-color: #337ab7;
+}
+a.bg-primary:hover,
+a.bg-primary:focus {
+ background-color: #286090;
+}
+.bg-success {
+ background-color: #dff0d8;
+}
+a.bg-success:hover,
+a.bg-success:focus {
+ background-color: #c1e2b3;
+}
+.bg-info {
+ background-color: #d9edf7;
+}
+a.bg-info:hover,
+a.bg-info:focus {
+ background-color: #afd9ee;
+}
+.bg-warning {
+ background-color: #fcf8e3;
+}
+a.bg-warning:hover,
+a.bg-warning:focus {
+ background-color: #f7ecb5;
+}
+.bg-danger {
+ background-color: #f2dede;
+}
+a.bg-danger:hover,
+a.bg-danger:focus {
+ background-color: #e4b9b9;
+}
+.page-header {
+ padding-bottom: 9px;
+ margin: 40px 0 20px;
+ border-bottom: 1px solid #eee;
+}
+ul,
+ol {
+ margin-top: 0;
+ margin-bottom: 10px;
+}
+ul ul,
+ol ul,
+ul ol,
+ol ol {
+ margin-bottom: 0;
+}
+.list-unstyled {
+ padding-left: 0;
+ list-style: none;
+}
+.list-inline {
+ padding-left: 0;
+ margin-left: -5px;
+ list-style: none;
+}
+.list-inline > li {
+ display: inline-block;
+ padding-right: 5px;
+ padding-left: 5px;
+}
+dl {
+ margin-top: 0;
+ margin-bottom: 20px;
+}
+dt,
+dd {
+ line-height: 1.42857143;
+}
+dt {
+ font-weight: bold;
+}
+dd {
+ margin-left: 0;
+}
+@media (min-width: 768px) {
+ .dl-horizontal dt {
+ float: left;
+ width: 160px;
+ overflow: hidden;
+ clear: left;
+ text-align: right;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .dl-horizontal dd {
+ margin-left: 180px;
+ }
+}
+abbr[title],
+abbr[data-original-title] {
+ cursor: help;
+ border-bottom: 1px dotted #777;
+}
+.initialism {
+ font-size: 90%;
+ text-transform: uppercase;
+}
+blockquote {
+ padding: 10px 20px;
+ margin: 0 0 20px;
+ font-size: 17.5px;
+ border-left: 5px solid #eee;
+}
+blockquote p:last-child,
+blockquote ul:last-child,
+blockquote ol:last-child {
+ margin-bottom: 0;
+}
+blockquote footer,
+blockquote small,
+blockquote .small {
+ display: block;
+ font-size: 80%;
+ line-height: 1.42857143;
+ color: #777;
+}
+blockquote footer:before,
+blockquote small:before,
+blockquote .small:before {
+ content: '\2014 \00A0';
+}
+.blockquote-reverse,
+blockquote.pull-right {
+ padding-right: 15px;
+ padding-left: 0;
+ text-align: right;
+ border-right: 5px solid #eee;
+ border-left: 0;
+}
+.blockquote-reverse footer:before,
+blockquote.pull-right footer:before,
+.blockquote-reverse small:before,
+blockquote.pull-right small:before,
+.blockquote-reverse .small:before,
+blockquote.pull-right .small:before {
+ content: '';
+}
+.blockquote-reverse footer:after,
+blockquote.pull-right footer:after,
+.blockquote-reverse small:after,
+blockquote.pull-right small:after,
+.blockquote-reverse .small:after,
+blockquote.pull-right .small:after {
+ content: '\00A0 \2014';
+}
+address {
+ margin-bottom: 20px;
+ font-style: normal;
+ line-height: 1.42857143;
+}
+code,
+kbd,
+pre,
+samp {
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+}
+code {
+ padding: 2px 4px;
+ font-size: 90%;
+ color: #c7254e;
+ background-color: #f9f2f4;
+ border-radius: 4px;
+}
+kbd {
+ padding: 2px 4px;
+ font-size: 90%;
+ color: #fff;
+ background-color: #333;
+ border-radius: 3px;
+ -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+ box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+}
+kbd kbd {
+ padding: 0;
+ font-size: 100%;
+ font-weight: bold;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+pre {
+ display: block;
+ padding: 9.5px;
+ margin: 0 0 10px;
+ font-size: 13px;
+ line-height: 1.42857143;
+ color: #333;
+ word-break: break-all;
+ word-wrap: break-word;
+ background-color: #f5f5f5;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+}
+pre code {
+ padding: 0;
+ font-size: inherit;
+ color: inherit;
+ white-space: pre-wrap;
+ background-color: transparent;
+ border-radius: 0;
+}
+.pre-scrollable {
+ max-height: 340px;
+ overflow-y: scroll;
+}
+.container {
+ padding-right: 15px;
+ padding-left: 15px;
+ margin-right: auto;
+ margin-left: auto;
+}
+@media (min-width: 768px) {
+ .container {
+ width: 750px;
+ }
+}
+@media (min-width: 992px) {
+ .container {
+ width: 970px;
+ }
+}
+@media (min-width: 1200px) {
+ .container {
+ width: 1170px;
+ }
+}
+.container-fluid {
+ padding-right: 15px;
+ padding-left: 15px;
+ margin-right: auto;
+ margin-left: auto;
+}
+.row {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
+ position: relative;
+ min-height: 1px;
+ padding-right: 15px;
+ padding-left: 15px;
+}
+.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
+ float: left;
+}
+.col-xs-12 {
+ width: 100%;
+}
+.col-xs-11 {
+ width: 91.66666667%;
+}
+.col-xs-10 {
+ width: 83.33333333%;
+}
+.col-xs-9 {
+ width: 75%;
+}
+.col-xs-8 {
+ width: 66.66666667%;
+}
+.col-xs-7 {
+ width: 58.33333333%;
+}
+.col-xs-6 {
+ width: 50%;
+}
+.col-xs-5 {
+ width: 41.66666667%;
+}
+.col-xs-4 {
+ width: 33.33333333%;
+}
+.col-xs-3 {
+ width: 25%;
+}
+.col-xs-2 {
+ width: 16.66666667%;
+}
+.col-xs-1 {
+ width: 8.33333333%;
+}
+.col-xs-pull-12 {
+ right: 100%;
+}
+.col-xs-pull-11 {
+ right: 91.66666667%;
+}
+.col-xs-pull-10 {
+ right: 83.33333333%;
+}
+.col-xs-pull-9 {
+ right: 75%;
+}
+.col-xs-pull-8 {
+ right: 66.66666667%;
+}
+.col-xs-pull-7 {
+ right: 58.33333333%;
+}
+.col-xs-pull-6 {
+ right: 50%;
+}
+.col-xs-pull-5 {
+ right: 41.66666667%;
+}
+.col-xs-pull-4 {
+ right: 33.33333333%;
+}
+.col-xs-pull-3 {
+ right: 25%;
+}
+.col-xs-pull-2 {
+ right: 16.66666667%;
+}
+.col-xs-pull-1 {
+ right: 8.33333333%;
+}
+.col-xs-pull-0 {
+ right: auto;
+}
+.col-xs-push-12 {
+ left: 100%;
+}
+.col-xs-push-11 {
+ left: 91.66666667%;
+}
+.col-xs-push-10 {
+ left: 83.33333333%;
+}
+.col-xs-push-9 {
+ left: 75%;
+}
+.col-xs-push-8 {
+ left: 66.66666667%;
+}
+.col-xs-push-7 {
+ left: 58.33333333%;
+}
+.col-xs-push-6 {
+ left: 50%;
+}
+.col-xs-push-5 {
+ left: 41.66666667%;
+}
+.col-xs-push-4 {
+ left: 33.33333333%;
+}
+.col-xs-push-3 {
+ left: 25%;
+}
+.col-xs-push-2 {
+ left: 16.66666667%;
+}
+.col-xs-push-1 {
+ left: 8.33333333%;
+}
+.col-xs-push-0 {
+ left: auto;
+}
+.col-xs-offset-12 {
+ margin-left: 100%;
+}
+.col-xs-offset-11 {
+ margin-left: 91.66666667%;
+}
+.col-xs-offset-10 {
+ margin-left: 83.33333333%;
+}
+.col-xs-offset-9 {
+ margin-left: 75%;
+}
+.col-xs-offset-8 {
+ margin-left: 66.66666667%;
+}
+.col-xs-offset-7 {
+ margin-left: 58.33333333%;
+}
+.col-xs-offset-6 {
+ margin-left: 50%;
+}
+.col-xs-offset-5 {
+ margin-left: 41.66666667%;
+}
+.col-xs-offset-4 {
+ margin-left: 33.33333333%;
+}
+.col-xs-offset-3 {
+ margin-left: 25%;
+}
+.col-xs-offset-2 {
+ margin-left: 16.66666667%;
+}
+.col-xs-offset-1 {
+ margin-left: 8.33333333%;
+}
+.col-xs-offset-0 {
+ margin-left: 0;
+}
+@media (min-width: 768px) {
+ .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
+ float: left;
+ }
+ .col-sm-12 {
+ width: 100%;
+ }
+ .col-sm-11 {
+ width: 91.66666667%;
+ }
+ .col-sm-10 {
+ width: 83.33333333%;
+ }
+ .col-sm-9 {
+ width: 75%;
+ }
+ .col-sm-8 {
+ width: 66.66666667%;
+ }
+ .col-sm-7 {
+ width: 58.33333333%;
+ }
+ .col-sm-6 {
+ width: 50%;
+ }
+ .col-sm-5 {
+ width: 41.66666667%;
+ }
+ .col-sm-4 {
+ width: 33.33333333%;
+ }
+ .col-sm-3 {
+ width: 25%;
+ }
+ .col-sm-2 {
+ width: 16.66666667%;
+ }
+ .col-sm-1 {
+ width: 8.33333333%;
+ }
+ .col-sm-pull-12 {
+ right: 100%;
+ }
+ .col-sm-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-sm-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-sm-pull-9 {
+ right: 75%;
+ }
+ .col-sm-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-sm-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-sm-pull-6 {
+ right: 50%;
+ }
+ .col-sm-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-sm-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-sm-pull-3 {
+ right: 25%;
+ }
+ .col-sm-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-sm-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-sm-pull-0 {
+ right: auto;
+ }
+ .col-sm-push-12 {
+ left: 100%;
+ }
+ .col-sm-push-11 {
+ left: 91.66666667%;
+ }
+ .col-sm-push-10 {
+ left: 83.33333333%;
+ }
+ .col-sm-push-9 {
+ left: 75%;
+ }
+ .col-sm-push-8 {
+ left: 66.66666667%;
+ }
+ .col-sm-push-7 {
+ left: 58.33333333%;
+ }
+ .col-sm-push-6 {
+ left: 50%;
+ }
+ .col-sm-push-5 {
+ left: 41.66666667%;
+ }
+ .col-sm-push-4 {
+ left: 33.33333333%;
+ }
+ .col-sm-push-3 {
+ left: 25%;
+ }
+ .col-sm-push-2 {
+ left: 16.66666667%;
+ }
+ .col-sm-push-1 {
+ left: 8.33333333%;
+ }
+ .col-sm-push-0 {
+ left: auto;
+ }
+ .col-sm-offset-12 {
+ margin-left: 100%;
+ }
+ .col-sm-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-sm-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-sm-offset-9 {
+ margin-left: 75%;
+ }
+ .col-sm-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-sm-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-sm-offset-6 {
+ margin-left: 50%;
+ }
+ .col-sm-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-sm-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-sm-offset-3 {
+ margin-left: 25%;
+ }
+ .col-sm-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-sm-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-sm-offset-0 {
+ margin-left: 0;
+ }
+}
+@media (min-width: 992px) {
+ .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
+ float: left;
+ }
+ .col-md-12 {
+ width: 100%;
+ }
+ .col-md-11 {
+ width: 91.66666667%;
+ }
+ .col-md-10 {
+ width: 83.33333333%;
+ }
+ .col-md-9 {
+ width: 75%;
+ }
+ .col-md-8 {
+ width: 66.66666667%;
+ }
+ .col-md-7 {
+ width: 58.33333333%;
+ }
+ .col-md-6 {
+ width: 50%;
+ }
+ .col-md-5 {
+ width: 41.66666667%;
+ }
+ .col-md-4 {
+ width: 33.33333333%;
+ }
+ .col-md-3 {
+ width: 25%;
+ }
+ .col-md-2 {
+ width: 16.66666667%;
+ }
+ .col-md-1 {
+ width: 8.33333333%;
+ }
+ .col-md-pull-12 {
+ right: 100%;
+ }
+ .col-md-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-md-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-md-pull-9 {
+ right: 75%;
+ }
+ .col-md-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-md-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-md-pull-6 {
+ right: 50%;
+ }
+ .col-md-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-md-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-md-pull-3 {
+ right: 25%;
+ }
+ .col-md-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-md-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-md-pull-0 {
+ right: auto;
+ }
+ .col-md-push-12 {
+ left: 100%;
+ }
+ .col-md-push-11 {
+ left: 91.66666667%;
+ }
+ .col-md-push-10 {
+ left: 83.33333333%;
+ }
+ .col-md-push-9 {
+ left: 75%;
+ }
+ .col-md-push-8 {
+ left: 66.66666667%;
+ }
+ .col-md-push-7 {
+ left: 58.33333333%;
+ }
+ .col-md-push-6 {
+ left: 50%;
+ }
+ .col-md-push-5 {
+ left: 41.66666667%;
+ }
+ .col-md-push-4 {
+ left: 33.33333333%;
+ }
+ .col-md-push-3 {
+ left: 25%;
+ }
+ .col-md-push-2 {
+ left: 16.66666667%;
+ }
+ .col-md-push-1 {
+ left: 8.33333333%;
+ }
+ .col-md-push-0 {
+ left: auto;
+ }
+ .col-md-offset-12 {
+ margin-left: 100%;
+ }
+ .col-md-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-md-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-md-offset-9 {
+ margin-left: 75%;
+ }
+ .col-md-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-md-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-md-offset-6 {
+ margin-left: 50%;
+ }
+ .col-md-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-md-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-md-offset-3 {
+ margin-left: 25%;
+ }
+ .col-md-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-md-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-md-offset-0 {
+ margin-left: 0;
+ }
+}
+@media (min-width: 1200px) {
+ .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
+ float: left;
+ }
+ .col-lg-12 {
+ width: 100%;
+ }
+ .col-lg-11 {
+ width: 91.66666667%;
+ }
+ .col-lg-10 {
+ width: 83.33333333%;
+ }
+ .col-lg-9 {
+ width: 75%;
+ }
+ .col-lg-8 {
+ width: 66.66666667%;
+ }
+ .col-lg-7 {
+ width: 58.33333333%;
+ }
+ .col-lg-6 {
+ width: 50%;
+ }
+ .col-lg-5 {
+ width: 41.66666667%;
+ }
+ .col-lg-4 {
+ width: 33.33333333%;
+ }
+ .col-lg-3 {
+ width: 25%;
+ }
+ .col-lg-2 {
+ width: 16.66666667%;
+ }
+ .col-lg-1 {
+ width: 8.33333333%;
+ }
+ .col-lg-pull-12 {
+ right: 100%;
+ }
+ .col-lg-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-lg-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-lg-pull-9 {
+ right: 75%;
+ }
+ .col-lg-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-lg-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-lg-pull-6 {
+ right: 50%;
+ }
+ .col-lg-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-lg-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-lg-pull-3 {
+ right: 25%;
+ }
+ .col-lg-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-lg-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-lg-pull-0 {
+ right: auto;
+ }
+ .col-lg-push-12 {
+ left: 100%;
+ }
+ .col-lg-push-11 {
+ left: 91.66666667%;
+ }
+ .col-lg-push-10 {
+ left: 83.33333333%;
+ }
+ .col-lg-push-9 {
+ left: 75%;
+ }
+ .col-lg-push-8 {
+ left: 66.66666667%;
+ }
+ .col-lg-push-7 {
+ left: 58.33333333%;
+ }
+ .col-lg-push-6 {
+ left: 50%;
+ }
+ .col-lg-push-5 {
+ left: 41.66666667%;
+ }
+ .col-lg-push-4 {
+ left: 33.33333333%;
+ }
+ .col-lg-push-3 {
+ left: 25%;
+ }
+ .col-lg-push-2 {
+ left: 16.66666667%;
+ }
+ .col-lg-push-1 {
+ left: 8.33333333%;
+ }
+ .col-lg-push-0 {
+ left: auto;
+ }
+ .col-lg-offset-12 {
+ margin-left: 100%;
+ }
+ .col-lg-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-lg-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-lg-offset-9 {
+ margin-left: 75%;
+ }
+ .col-lg-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-lg-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-lg-offset-6 {
+ margin-left: 50%;
+ }
+ .col-lg-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-lg-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-lg-offset-3 {
+ margin-left: 25%;
+ }
+ .col-lg-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-lg-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-lg-offset-0 {
+ margin-left: 0;
+ }
+}
+table {
+ background-color: transparent;
+}
+caption {
+ padding-top: 8px;
+ padding-bottom: 8px;
+ color: #777;
+ text-align: left;
+}
+th {
+ text-align: left;
+}
+.table {
+ width: 100%;
+ max-width: 100%;
+ margin-bottom: 20px;
+}
+.table > thead > tr > th,
+.table > tbody > tr > th,
+.table > tfoot > tr > th,
+.table > thead > tr > td,
+.table > tbody > tr > td,
+.table > tfoot > tr > td {
+ padding: 8px;
+ line-height: 1.42857143;
+ vertical-align: top;
+ border-top: 1px solid #ddd;
+}
+.table > thead > tr > th {
+ vertical-align: bottom;
+ border-bottom: 2px solid #ddd;
+}
+.table > caption + thead > tr:first-child > th,
+.table > colgroup + thead > tr:first-child > th,
+.table > thead:first-child > tr:first-child > th,
+.table > caption + thead > tr:first-child > td,
+.table > colgroup + thead > tr:first-child > td,
+.table > thead:first-child > tr:first-child > td {
+ border-top: 0;
+}
+.table > tbody + tbody {
+ border-top: 2px solid #ddd;
+}
+.table .table {
+ background-color: #fff;
+}
+.table-condensed > thead > tr > th,
+.table-condensed > tbody > tr > th,
+.table-condensed > tfoot > tr > th,
+.table-condensed > thead > tr > td,
+.table-condensed > tbody > tr > td,
+.table-condensed > tfoot > tr > td {
+ padding: 5px;
+}
+.table-bordered {
+ border: 1px solid #ddd;
+}
+.table-bordered > thead > tr > th,
+.table-bordered > tbody > tr > th,
+.table-bordered > tfoot > tr > th,
+.table-bordered > thead > tr > td,
+.table-bordered > tbody > tr > td,
+.table-bordered > tfoot > tr > td {
+ border: 1px solid #ddd;
+}
+.table-bordered > thead > tr > th,
+.table-bordered > thead > tr > td {
+ border-bottom-width: 2px;
+}
+.table-striped > tbody > tr:nth-of-type(odd) {
+ background-color: #f9f9f9;
+}
+.table-hover > tbody > tr:hover {
+ background-color: #f5f5f5;
+}
+table col[class*="col-"] {
+ position: static;
+ display: table-column;
+ float: none;
+}
+table td[class*="col-"],
+table th[class*="col-"] {
+ position: static;
+ display: table-cell;
+ float: none;
+}
+.table > thead > tr > td.active,
+.table > tbody > tr > td.active,
+.table > tfoot > tr > td.active,
+.table > thead > tr > th.active,
+.table > tbody > tr > th.active,
+.table > tfoot > tr > th.active,
+.table > thead > tr.active > td,
+.table > tbody > tr.active > td,
+.table > tfoot > tr.active > td,
+.table > thead > tr.active > th,
+.table > tbody > tr.active > th,
+.table > tfoot > tr.active > th {
+ background-color: #f5f5f5;
+}
+.table-hover > tbody > tr > td.active:hover,
+.table-hover > tbody > tr > th.active:hover,
+.table-hover > tbody > tr.active:hover > td,
+.table-hover > tbody > tr:hover > .active,
+.table-hover > tbody > tr.active:hover > th {
+ background-color: #e8e8e8;
+}
+.table > thead > tr > td.success,
+.table > tbody > tr > td.success,
+.table > tfoot > tr > td.success,
+.table > thead > tr > th.success,
+.table > tbody > tr > th.success,
+.table > tfoot > tr > th.success,
+.table > thead > tr.success > td,
+.table > tbody > tr.success > td,
+.table > tfoot > tr.success > td,
+.table > thead > tr.success > th,
+.table > tbody > tr.success > th,
+.table > tfoot > tr.success > th {
+ background-color: #dff0d8;
+}
+.table-hover > tbody > tr > td.success:hover,
+.table-hover > tbody > tr > th.success:hover,
+.table-hover > tbody > tr.success:hover > td,
+.table-hover > tbody > tr:hover > .success,
+.table-hover > tbody > tr.success:hover > th {
+ background-color: #d0e9c6;
+}
+.table > thead > tr > td.info,
+.table > tbody > tr > td.info,
+.table > tfoot > tr > td.info,
+.table > thead > tr > th.info,
+.table > tbody > tr > th.info,
+.table > tfoot > tr > th.info,
+.table > thead > tr.info > td,
+.table > tbody > tr.info > td,
+.table > tfoot > tr.info > td,
+.table > thead > tr.info > th,
+.table > tbody > tr.info > th,
+.table > tfoot > tr.info > th {
+ background-color: #d9edf7;
+}
+.table-hover > tbody > tr > td.info:hover,
+.table-hover > tbody > tr > th.info:hover,
+.table-hover > tbody > tr.info:hover > td,
+.table-hover > tbody > tr:hover > .info,
+.table-hover > tbody > tr.info:hover > th {
+ background-color: #c4e3f3;
+}
+.table > thead > tr > td.warning,
+.table > tbody > tr > td.warning,
+.table > tfoot > tr > td.warning,
+.table > thead > tr > th.warning,
+.table > tbody > tr > th.warning,
+.table > tfoot > tr > th.warning,
+.table > thead > tr.warning > td,
+.table > tbody > tr.warning > td,
+.table > tfoot > tr.warning > td,
+.table > thead > tr.warning > th,
+.table > tbody > tr.warning > th,
+.table > tfoot > tr.warning > th {
+ background-color: #fcf8e3;
+}
+.table-hover > tbody > tr > td.warning:hover,
+.table-hover > tbody > tr > th.warning:hover,
+.table-hover > tbody > tr.warning:hover > td,
+.table-hover > tbody > tr:hover > .warning,
+.table-hover > tbody > tr.warning:hover > th {
+ background-color: #faf2cc;
+}
+.table > thead > tr > td.danger,
+.table > tbody > tr > td.danger,
+.table > tfoot > tr > td.danger,
+.table > thead > tr > th.danger,
+.table > tbody > tr > th.danger,
+.table > tfoot > tr > th.danger,
+.table > thead > tr.danger > td,
+.table > tbody > tr.danger > td,
+.table > tfoot > tr.danger > td,
+.table > thead > tr.danger > th,
+.table > tbody > tr.danger > th,
+.table > tfoot > tr.danger > th {
+ background-color: #f2dede;
+}
+.table-hover > tbody > tr > td.danger:hover,
+.table-hover > tbody > tr > th.danger:hover,
+.table-hover > tbody > tr.danger:hover > td,
+.table-hover > tbody > tr:hover > .danger,
+.table-hover > tbody > tr.danger:hover > th {
+ background-color: #ebcccc;
+}
+.table-responsive {
+ min-height: .01%;
+ overflow-x: auto;
+}
+@media screen and (max-width: 767px) {
+ .table-responsive {
+ width: 100%;
+ margin-bottom: 15px;
+ overflow-y: hidden;
+ -ms-overflow-style: -ms-autohiding-scrollbar;
+ border: 1px solid #ddd;
+ }
+ .table-responsive > .table {
+ margin-bottom: 0;
+ }
+ .table-responsive > .table > thead > tr > th,
+ .table-responsive > .table > tbody > tr > th,
+ .table-responsive > .table > tfoot > tr > th,
+ .table-responsive > .table > thead > tr > td,
+ .table-responsive > .table > tbody > tr > td,
+ .table-responsive > .table > tfoot > tr > td {
+ white-space: nowrap;
+ }
+ .table-responsive > .table-bordered {
+ border: 0;
+ }
+ .table-responsive > .table-bordered > thead > tr > th:first-child,
+ .table-responsive > .table-bordered > tbody > tr > th:first-child,
+ .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+ .table-responsive > .table-bordered > thead > tr > td:first-child,
+ .table-responsive > .table-bordered > tbody > tr > td:first-child,
+ .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+ border-left: 0;
+ }
+ .table-responsive > .table-bordered > thead > tr > th:last-child,
+ .table-responsive > .table-bordered > tbody > tr > th:last-child,
+ .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+ .table-responsive > .table-bordered > thead > tr > td:last-child,
+ .table-responsive > .table-bordered > tbody > tr > td:last-child,
+ .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+ border-right: 0;
+ }
+ .table-responsive > .table-bordered > tbody > tr:last-child > th,
+ .table-responsive > .table-bordered > tfoot > tr:last-child > th,
+ .table-responsive > .table-bordered > tbody > tr:last-child > td,
+ .table-responsive > .table-bordered > tfoot > tr:last-child > td {
+ border-bottom: 0;
+ }
+}
+fieldset {
+ min-width: 0;
+ padding: 0;
+ margin: 0;
+ border: 0;
+}
+legend {
+ display: block;
+ width: 100%;
+ padding: 0;
+ margin-bottom: 20px;
+ font-size: 21px;
+ line-height: inherit;
+ color: #333;
+ border: 0;
+ border-bottom: 1px solid #e5e5e5;
+}
+label {
+ display: inline-block;
+ max-width: 100%;
+ margin-bottom: 5px;
+ font-weight: bold;
+}
+input[type="search"] {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+input[type="radio"],
+input[type="checkbox"] {
+ margin: 4px 0 0;
+ margin-top: 1px \9;
+ line-height: normal;
+}
+input[type="file"] {
+ display: block;
+}
+input[type="range"] {
+ display: block;
+ width: 100%;
+}
+select[multiple],
+select[size] {
+ height: auto;
+}
+input[type="file"]:focus,
+input[type="radio"]:focus,
+input[type="checkbox"]:focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+output {
+ display: block;
+ padding-top: 7px;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #555;
+}
+.form-control {
+ display: block;
+ width: 100%;
+ height: 34px;
+ padding: 6px 12px;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #555;
+ background-color: #fff;
+ background-image: none;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
+ -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+ transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+}
+.form-control:focus {
+ border-color: #66afe9;
+ outline: 0;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+ box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+}
+.form-control::-moz-placeholder {
+ color: #999;
+ opacity: 1;
+}
+.form-control:-ms-input-placeholder {
+ color: #999;
+}
+.form-control::-webkit-input-placeholder {
+ color: #999;
+}
+.form-control::-ms-expand {
+ background-color: transparent;
+ border: 0;
+}
+.form-control[disabled],
+.form-control[readonly],
+fieldset[disabled] .form-control {
+ background-color: #eee;
+ opacity: 1;
+}
+.form-control[disabled],
+fieldset[disabled] .form-control {
+ cursor: not-allowed;
+}
+textarea.form-control {
+ height: auto;
+}
+input[type="search"] {
+ -webkit-appearance: none;
+}
+@media screen and (-webkit-min-device-pixel-ratio: 0) {
+ input[type="date"].form-control,
+ input[type="time"].form-control,
+ input[type="datetime-local"].form-control,
+ input[type="month"].form-control {
+ line-height: 34px;
+ }
+ input[type="date"].input-sm,
+ input[type="time"].input-sm,
+ input[type="datetime-local"].input-sm,
+ input[type="month"].input-sm,
+ .input-group-sm input[type="date"],
+ .input-group-sm input[type="time"],
+ .input-group-sm input[type="datetime-local"],
+ .input-group-sm input[type="month"] {
+ line-height: 30px;
+ }
+ input[type="date"].input-lg,
+ input[type="time"].input-lg,
+ input[type="datetime-local"].input-lg,
+ input[type="month"].input-lg,
+ .input-group-lg input[type="date"],
+ .input-group-lg input[type="time"],
+ .input-group-lg input[type="datetime-local"],
+ .input-group-lg input[type="month"] {
+ line-height: 46px;
+ }
+}
+.form-group {
+ margin-bottom: 15px;
+}
+.radio,
+.checkbox {
+ position: relative;
+ display: block;
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+.radio label,
+.checkbox label {
+ min-height: 20px;
+ padding-left: 20px;
+ margin-bottom: 0;
+ font-weight: normal;
+ cursor: pointer;
+}
+.radio input[type="radio"],
+.radio-inline input[type="radio"],
+.checkbox input[type="checkbox"],
+.checkbox-inline input[type="checkbox"] {
+ position: absolute;
+ margin-top: 4px \9;
+ margin-left: -20px;
+}
+.radio + .radio,
+.checkbox + .checkbox {
+ margin-top: -5px;
+}
+.radio-inline,
+.checkbox-inline {
+ position: relative;
+ display: inline-block;
+ padding-left: 20px;
+ margin-bottom: 0;
+ font-weight: normal;
+ vertical-align: middle;
+ cursor: pointer;
+}
+.radio-inline + .radio-inline,
+.checkbox-inline + .checkbox-inline {
+ margin-top: 0;
+ margin-left: 10px;
+}
+input[type="radio"][disabled],
+input[type="checkbox"][disabled],
+input[type="radio"].disabled,
+input[type="checkbox"].disabled,
+fieldset[disabled] input[type="radio"],
+fieldset[disabled] input[type="checkbox"] {
+ cursor: not-allowed;
+}
+.radio-inline.disabled,
+.checkbox-inline.disabled,
+fieldset[disabled] .radio-inline,
+fieldset[disabled] .checkbox-inline {
+ cursor: not-allowed;
+}
+.radio.disabled label,
+.checkbox.disabled label,
+fieldset[disabled] .radio label,
+fieldset[disabled] .checkbox label {
+ cursor: not-allowed;
+}
+.form-control-static {
+ min-height: 34px;
+ padding-top: 7px;
+ padding-bottom: 7px;
+ margin-bottom: 0;
+}
+.form-control-static.input-lg,
+.form-control-static.input-sm {
+ padding-right: 0;
+ padding-left: 0;
+}
+.input-sm {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+select.input-sm {
+ height: 30px;
+ line-height: 30px;
+}
+textarea.input-sm,
+select[multiple].input-sm {
+ height: auto;
+}
+.form-group-sm .form-control {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+.form-group-sm select.form-control {
+ height: 30px;
+ line-height: 30px;
+}
+.form-group-sm textarea.form-control,
+.form-group-sm select[multiple].form-control {
+ height: auto;
+}
+.form-group-sm .form-control-static {
+ height: 30px;
+ min-height: 32px;
+ padding: 6px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+}
+.input-lg {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+select.input-lg {
+ height: 46px;
+ line-height: 46px;
+}
+textarea.input-lg,
+select[multiple].input-lg {
+ height: auto;
+}
+.form-group-lg .form-control {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+.form-group-lg select.form-control {
+ height: 46px;
+ line-height: 46px;
+}
+.form-group-lg textarea.form-control,
+.form-group-lg select[multiple].form-control {
+ height: auto;
+}
+.form-group-lg .form-control-static {
+ height: 46px;
+ min-height: 38px;
+ padding: 11px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+}
+.has-feedback {
+ position: relative;
+}
+.has-feedback .form-control {
+ padding-right: 42.5px;
+}
+.form-control-feedback {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 2;
+ display: block;
+ width: 34px;
+ height: 34px;
+ line-height: 34px;
+ text-align: center;
+ pointer-events: none;
+}
+.input-lg + .form-control-feedback,
+.input-group-lg + .form-control-feedback,
+.form-group-lg .form-control + .form-control-feedback {
+ width: 46px;
+ height: 46px;
+ line-height: 46px;
+}
+.input-sm + .form-control-feedback,
+.input-group-sm + .form-control-feedback,
+.form-group-sm .form-control + .form-control-feedback {
+ width: 30px;
+ height: 30px;
+ line-height: 30px;
+}
+.has-success .help-block,
+.has-success .control-label,
+.has-success .radio,
+.has-success .checkbox,
+.has-success .radio-inline,
+.has-success .checkbox-inline,
+.has-success.radio label,
+.has-success.checkbox label,
+.has-success.radio-inline label,
+.has-success.checkbox-inline label {
+ color: #3c763d;
+}
+.has-success .form-control {
+ border-color: #3c763d;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-success .form-control:focus {
+ border-color: #2b542c;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+}
+.has-success .input-group-addon {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #3c763d;
+}
+.has-success .form-control-feedback {
+ color: #3c763d;
+}
+.has-warning .help-block,
+.has-warning .control-label,
+.has-warning .radio,
+.has-warning .checkbox,
+.has-warning .radio-inline,
+.has-warning .checkbox-inline,
+.has-warning.radio label,
+.has-warning.checkbox label,
+.has-warning.radio-inline label,
+.has-warning.checkbox-inline label {
+ color: #8a6d3b;
+}
+.has-warning .form-control {
+ border-color: #8a6d3b;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-warning .form-control:focus {
+ border-color: #66512c;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+}
+.has-warning .input-group-addon {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #8a6d3b;
+}
+.has-warning .form-control-feedback {
+ color: #8a6d3b;
+}
+.has-error .help-block,
+.has-error .control-label,
+.has-error .radio,
+.has-error .checkbox,
+.has-error .radio-inline,
+.has-error .checkbox-inline,
+.has-error.radio label,
+.has-error.checkbox label,
+.has-error.radio-inline label,
+.has-error.checkbox-inline label {
+ color: #a94442;
+}
+.has-error .form-control {
+ border-color: #a94442;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-error .form-control:focus {
+ border-color: #843534;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+}
+.has-error .input-group-addon {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #a94442;
+}
+.has-error .form-control-feedback {
+ color: #a94442;
+}
+.has-feedback label ~ .form-control-feedback {
+ top: 25px;
+}
+.has-feedback label.sr-only ~ .form-control-feedback {
+ top: 0;
+}
+.help-block {
+ display: block;
+ margin-top: 5px;
+ margin-bottom: 10px;
+ color: #737373;
+}
+@media (min-width: 768px) {
+ .form-inline .form-group {
+ display: inline-block;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .form-control {
+ display: inline-block;
+ width: auto;
+ vertical-align: middle;
+ }
+ .form-inline .form-control-static {
+ display: inline-block;
+ }
+ .form-inline .input-group {
+ display: inline-table;
+ vertical-align: middle;
+ }
+ .form-inline .input-group .input-group-addon,
+ .form-inline .input-group .input-group-btn,
+ .form-inline .input-group .form-control {
+ width: auto;
+ }
+ .form-inline .input-group > .form-control {
+ width: 100%;
+ }
+ .form-inline .control-label {
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .radio,
+ .form-inline .checkbox {
+ display: inline-block;
+ margin-top: 0;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .radio label,
+ .form-inline .checkbox label {
+ padding-left: 0;
+ }
+ .form-inline .radio input[type="radio"],
+ .form-inline .checkbox input[type="checkbox"] {
+ position: relative;
+ margin-left: 0;
+ }
+ .form-inline .has-feedback .form-control-feedback {
+ top: 0;
+ }
+}
+.form-horizontal .radio,
+.form-horizontal .checkbox,
+.form-horizontal .radio-inline,
+.form-horizontal .checkbox-inline {
+ padding-top: 7px;
+ margin-top: 0;
+ margin-bottom: 0;
+}
+.form-horizontal .radio,
+.form-horizontal .checkbox {
+ min-height: 27px;
+}
+.form-horizontal .form-group {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+@media (min-width: 768px) {
+ .form-horizontal .control-label {
+ padding-top: 7px;
+ margin-bottom: 0;
+ text-align: right;
+ }
+}
+.form-horizontal .has-feedback .form-control-feedback {
+ right: 15px;
+}
+@media (min-width: 768px) {
+ .form-horizontal .form-group-lg .control-label {
+ padding-top: 11px;
+ font-size: 18px;
+ }
+}
+@media (min-width: 768px) {
+ .form-horizontal .form-group-sm .control-label {
+ padding-top: 6px;
+ font-size: 12px;
+ }
+}
+.btn {
+ display: inline-block;
+ padding: 6px 12px;
+ margin-bottom: 0;
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 1.42857143;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ -ms-touch-action: manipulation;
+ touch-action: manipulation;
+ cursor: pointer;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ background-image: none;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.btn:focus,
+.btn:active:focus,
+.btn.active:focus,
+.btn.focus,
+.btn:active.focus,
+.btn.active.focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+.btn:hover,
+.btn:focus,
+.btn.focus {
+ color: #333;
+ text-decoration: none;
+}
+.btn:active,
+.btn.active {
+ background-image: none;
+ outline: 0;
+ -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+ box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn.disabled,
+.btn[disabled],
+fieldset[disabled] .btn {
+ cursor: not-allowed;
+ filter: alpha(opacity=65);
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ opacity: .65;
+}
+a.btn.disabled,
+fieldset[disabled] a.btn {
+ pointer-events: none;
+}
+.btn-default {
+ color: #333;
+ background-color: #fff;
+ border-color: #ccc;
+}
+.btn-default:focus,
+.btn-default.focus {
+ color: #333;
+ background-color: #e6e6e6;
+ border-color: #8c8c8c;
+}
+.btn-default:hover {
+ color: #333;
+ background-color: #e6e6e6;
+ border-color: #adadad;
+}
+.btn-default:active,
+.btn-default.active,
+.open > .dropdown-toggle.btn-default {
+ color: #333;
+ background-color: #e6e6e6;
+ border-color: #adadad;
+}
+.btn-default:active:hover,
+.btn-default.active:hover,
+.open > .dropdown-toggle.btn-default:hover,
+.btn-default:active:focus,
+.btn-default.active:focus,
+.open > .dropdown-toggle.btn-default:focus,
+.btn-default:active.focus,
+.btn-default.active.focus,
+.open > .dropdown-toggle.btn-default.focus {
+ color: #333;
+ background-color: #d4d4d4;
+ border-color: #8c8c8c;
+}
+.btn-default:active,
+.btn-default.active,
+.open > .dropdown-toggle.btn-default {
+ background-image: none;
+}
+.btn-default.disabled:hover,
+.btn-default[disabled]:hover,
+fieldset[disabled] .btn-default:hover,
+.btn-default.disabled:focus,
+.btn-default[disabled]:focus,
+fieldset[disabled] .btn-default:focus,
+.btn-default.disabled.focus,
+.btn-default[disabled].focus,
+fieldset[disabled] .btn-default.focus {
+ background-color: #fff;
+ border-color: #ccc;
+}
+.btn-default .badge {
+ color: #fff;
+ background-color: #333;
+}
+.btn-primary {
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #2e6da4;
+}
+.btn-primary:focus,
+.btn-primary.focus {
+ color: #fff;
+ background-color: #286090;
+ border-color: #122b40;
+}
+.btn-primary:hover {
+ color: #fff;
+ background-color: #286090;
+ border-color: #204d74;
+}
+.btn-primary:active,
+.btn-primary.active,
+.open > .dropdown-toggle.btn-primary {
+ color: #fff;
+ background-color: #286090;
+ border-color: #204d74;
+}
+.btn-primary:active:hover,
+.btn-primary.active:hover,
+.open > .dropdown-toggle.btn-primary:hover,
+.btn-primary:active:focus,
+.btn-primary.active:focus,
+.open > .dropdown-toggle.btn-primary:focus,
+.btn-primary:active.focus,
+.btn-primary.active.focus,
+.open > .dropdown-toggle.btn-primary.focus {
+ color: #fff;
+ background-color: #204d74;
+ border-color: #122b40;
+}
+.btn-primary:active,
+.btn-primary.active,
+.open > .dropdown-toggle.btn-primary {
+ background-image: none;
+}
+.btn-primary.disabled:hover,
+.btn-primary[disabled]:hover,
+fieldset[disabled] .btn-primary:hover,
+.btn-primary.disabled:focus,
+.btn-primary[disabled]:focus,
+fieldset[disabled] .btn-primary:focus,
+.btn-primary.disabled.focus,
+.btn-primary[disabled].focus,
+fieldset[disabled] .btn-primary.focus {
+ background-color: #337ab7;
+ border-color: #2e6da4;
+}
+.btn-primary .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.btn-success {
+ color: #fff;
+ background-color: #5cb85c;
+ border-color: #4cae4c;
+}
+.btn-success:focus,
+.btn-success.focus {
+ color: #fff;
+ background-color: #449d44;
+ border-color: #255625;
+}
+.btn-success:hover {
+ color: #fff;
+ background-color: #449d44;
+ border-color: #398439;
+}
+.btn-success:active,
+.btn-success.active,
+.open > .dropdown-toggle.btn-success {
+ color: #fff;
+ background-color: #449d44;
+ border-color: #398439;
+}
+.btn-success:active:hover,
+.btn-success.active:hover,
+.open > .dropdown-toggle.btn-success:hover,
+.btn-success:active:focus,
+.btn-success.active:focus,
+.open > .dropdown-toggle.btn-success:focus,
+.btn-success:active.focus,
+.btn-success.active.focus,
+.open > .dropdown-toggle.btn-success.focus {
+ color: #fff;
+ background-color: #398439;
+ border-color: #255625;
+}
+.btn-success:active,
+.btn-success.active,
+.open > .dropdown-toggle.btn-success {
+ background-image: none;
+}
+.btn-success.disabled:hover,
+.btn-success[disabled]:hover,
+fieldset[disabled] .btn-success:hover,
+.btn-success.disabled:focus,
+.btn-success[disabled]:focus,
+fieldset[disabled] .btn-success:focus,
+.btn-success.disabled.focus,
+.btn-success[disabled].focus,
+fieldset[disabled] .btn-success.focus {
+ background-color: #5cb85c;
+ border-color: #4cae4c;
+}
+.btn-success .badge {
+ color: #5cb85c;
+ background-color: #fff;
+}
+.btn-info {
+ color: #fff;
+ background-color: #5bc0de;
+ border-color: #46b8da;
+}
+.btn-info:focus,
+.btn-info.focus {
+ color: #fff;
+ background-color: #31b0d5;
+ border-color: #1b6d85;
+}
+.btn-info:hover {
+ color: #fff;
+ background-color: #31b0d5;
+ border-color: #269abc;
+}
+.btn-info:active,
+.btn-info.active,
+.open > .dropdown-toggle.btn-info {
+ color: #fff;
+ background-color: #31b0d5;
+ border-color: #269abc;
+}
+.btn-info:active:hover,
+.btn-info.active:hover,
+.open > .dropdown-toggle.btn-info:hover,
+.btn-info:active:focus,
+.btn-info.active:focus,
+.open > .dropdown-toggle.btn-info:focus,
+.btn-info:active.focus,
+.btn-info.active.focus,
+.open > .dropdown-toggle.btn-info.focus {
+ color: #fff;
+ background-color: #269abc;
+ border-color: #1b6d85;
+}
+.btn-info:active,
+.btn-info.active,
+.open > .dropdown-toggle.btn-info {
+ background-image: none;
+}
+.btn-info.disabled:hover,
+.btn-info[disabled]:hover,
+fieldset[disabled] .btn-info:hover,
+.btn-info.disabled:focus,
+.btn-info[disabled]:focus,
+fieldset[disabled] .btn-info:focus,
+.btn-info.disabled.focus,
+.btn-info[disabled].focus,
+fieldset[disabled] .btn-info.focus {
+ background-color: #5bc0de;
+ border-color: #46b8da;
+}
+.btn-info .badge {
+ color: #5bc0de;
+ background-color: #fff;
+}
+.btn-warning {
+ color: #fff;
+ background-color: #f0ad4e;
+ border-color: #eea236;
+}
+.btn-warning:focus,
+.btn-warning.focus {
+ color: #fff;
+ background-color: #ec971f;
+ border-color: #985f0d;
+}
+.btn-warning:hover {
+ color: #fff;
+ background-color: #ec971f;
+ border-color: #d58512;
+}
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+ color: #fff;
+ background-color: #ec971f;
+ border-color: #d58512;
+}
+.btn-warning:active:hover,
+.btn-warning.active:hover,
+.open > .dropdown-toggle.btn-warning:hover,
+.btn-warning:active:focus,
+.btn-warning.active:focus,
+.open > .dropdown-toggle.btn-warning:focus,
+.btn-warning:active.focus,
+.btn-warning.active.focus,
+.open > .dropdown-toggle.btn-warning.focus {
+ color: #fff;
+ background-color: #d58512;
+ border-color: #985f0d;
+}
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+ background-image: none;
+}
+.btn-warning.disabled:hover,
+.btn-warning[disabled]:hover,
+fieldset[disabled] .btn-warning:hover,
+.btn-warning.disabled:focus,
+.btn-warning[disabled]:focus,
+fieldset[disabled] .btn-warning:focus,
+.btn-warning.disabled.focus,
+.btn-warning[disabled].focus,
+fieldset[disabled] .btn-warning.focus {
+ background-color: #f0ad4e;
+ border-color: #eea236;
+}
+.btn-warning .badge {
+ color: #f0ad4e;
+ background-color: #fff;
+}
+.btn-danger {
+ color: #fff;
+ background-color: #d9534f;
+ border-color: #d43f3a;
+}
+.btn-danger:focus,
+.btn-danger.focus {
+ color: #fff;
+ background-color: #c9302c;
+ border-color: #761c19;
+}
+.btn-danger:hover {
+ color: #fff;
+ background-color: #c9302c;
+ border-color: #ac2925;
+}
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+ color: #fff;
+ background-color: #c9302c;
+ border-color: #ac2925;
+}
+.btn-danger:active:hover,
+.btn-danger.active:hover,
+.open > .dropdown-toggle.btn-danger:hover,
+.btn-danger:active:focus,
+.btn-danger.active:focus,
+.open > .dropdown-toggle.btn-danger:focus,
+.btn-danger:active.focus,
+.btn-danger.active.focus,
+.open > .dropdown-toggle.btn-danger.focus {
+ color: #fff;
+ background-color: #ac2925;
+ border-color: #761c19;
+}
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+ background-image: none;
+}
+.btn-danger.disabled:hover,
+.btn-danger[disabled]:hover,
+fieldset[disabled] .btn-danger:hover,
+.btn-danger.disabled:focus,
+.btn-danger[disabled]:focus,
+fieldset[disabled] .btn-danger:focus,
+.btn-danger.disabled.focus,
+.btn-danger[disabled].focus,
+fieldset[disabled] .btn-danger.focus {
+ background-color: #d9534f;
+ border-color: #d43f3a;
+}
+.btn-danger .badge {
+ color: #d9534f;
+ background-color: #fff;
+}
+.btn-link {
+ font-weight: normal;
+ color: #337ab7;
+ border-radius: 0;
+}
+.btn-link,
+.btn-link:active,
+.btn-link.active,
+.btn-link[disabled],
+fieldset[disabled] .btn-link {
+ background-color: transparent;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+.btn-link,
+.btn-link:hover,
+.btn-link:focus,
+.btn-link:active {
+ border-color: transparent;
+}
+.btn-link:hover,
+.btn-link:focus {
+ color: #23527c;
+ text-decoration: underline;
+ background-color: transparent;
+}
+.btn-link[disabled]:hover,
+fieldset[disabled] .btn-link:hover,
+.btn-link[disabled]:focus,
+fieldset[disabled] .btn-link:focus {
+ color: #777;
+ text-decoration: none;
+}
+.btn-lg,
+.btn-group-lg > .btn {
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+.btn-sm,
+.btn-group-sm > .btn {
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+.btn-xs,
+.btn-group-xs > .btn {
+ padding: 1px 5px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+.btn-block {
+ display: block;
+ width: 100%;
+}
+.btn-block + .btn-block {
+ margin-top: 5px;
+}
+input[type="submit"].btn-block,
+input[type="reset"].btn-block,
+input[type="button"].btn-block {
+ width: 100%;
+}
+.fade {
+ opacity: 0;
+ -webkit-transition: opacity .15s linear;
+ -o-transition: opacity .15s linear;
+ transition: opacity .15s linear;
+}
+.fade.in {
+ opacity: 1;
+}
+.collapse {
+ display: none;
+}
+.collapse.in {
+ display: block;
+}
+tr.collapse.in {
+ display: table-row;
+}
+tbody.collapse.in {
+ display: table-row-group;
+}
+.collapsing {
+ position: relative;
+ height: 0;
+ overflow: hidden;
+ -webkit-transition-timing-function: ease;
+ -o-transition-timing-function: ease;
+ transition-timing-function: ease;
+ -webkit-transition-duration: .35s;
+ -o-transition-duration: .35s;
+ transition-duration: .35s;
+ -webkit-transition-property: height, visibility;
+ -o-transition-property: height, visibility;
+ transition-property: height, visibility;
+}
+.caret {
+ display: inline-block;
+ width: 0;
+ height: 0;
+ margin-left: 2px;
+ vertical-align: middle;
+ border-top: 4px dashed;
+ border-top: 4px solid \9;
+ border-right: 4px solid transparent;
+ border-left: 4px solid transparent;
+}
+.dropup,
+.dropdown {
+ position: relative;
+}
+.dropdown-toggle:focus {
+ outline: 0;
+}
+.dropdown-menu {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ z-index: 1000;
+ display: none;
+ float: left;
+ min-width: 160px;
+ padding: 5px 0;
+ margin: 2px 0 0;
+ font-size: 14px;
+ text-align: left;
+ list-style: none;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #ccc;
+ border: 1px solid rgba(0, 0, 0, .15);
+ border-radius: 4px;
+ -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+ box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+}
+.dropdown-menu.pull-right {
+ right: 0;
+ left: auto;
+}
+.dropdown-menu .divider {
+ height: 1px;
+ margin: 9px 0;
+ overflow: hidden;
+ background-color: #e5e5e5;
+}
+.dropdown-menu > li > a {
+ display: block;
+ padding: 3px 20px;
+ clear: both;
+ font-weight: normal;
+ line-height: 1.42857143;
+ color: #333;
+ white-space: nowrap;
+}
+.dropdown-menu > li > a:hover,
+.dropdown-menu > li > a:focus {
+ color: #262626;
+ text-decoration: none;
+ background-color: #f5f5f5;
+}
+.dropdown-menu > .active > a,
+.dropdown-menu > .active > a:hover,
+.dropdown-menu > .active > a:focus {
+ color: #fff;
+ text-decoration: none;
+ background-color: #337ab7;
+ outline: 0;
+}
+.dropdown-menu > .disabled > a,
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+ color: #777;
+}
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+ text-decoration: none;
+ cursor: not-allowed;
+ background-color: transparent;
+ background-image: none;
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+}
+.open > .dropdown-menu {
+ display: block;
+}
+.open > a {
+ outline: 0;
+}
+.dropdown-menu-right {
+ right: 0;
+ left: auto;
+}
+.dropdown-menu-left {
+ right: auto;
+ left: 0;
+}
+.dropdown-header {
+ display: block;
+ padding: 3px 20px;
+ font-size: 12px;
+ line-height: 1.42857143;
+ color: #777;
+ white-space: nowrap;
+}
+.dropdown-backdrop {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 990;
+}
+.pull-right > .dropdown-menu {
+ right: 0;
+ left: auto;
+}
+.dropup .caret,
+.navbar-fixed-bottom .dropdown .caret {
+ content: "";
+ border-top: 0;
+ border-bottom: 4px dashed;
+ border-bottom: 4px solid \9;
+}
+.dropup .dropdown-menu,
+.navbar-fixed-bottom .dropdown .dropdown-menu {
+ top: auto;
+ bottom: 100%;
+ margin-bottom: 2px;
+}
+@media (min-width: 768px) {
+ .navbar-right .dropdown-menu {
+ right: 0;
+ left: auto;
+ }
+ .navbar-right .dropdown-menu-left {
+ right: auto;
+ left: 0;
+ }
+}
+.btn-group,
+.btn-group-vertical {
+ position: relative;
+ display: inline-block;
+ vertical-align: middle;
+}
+.btn-group > .btn,
+.btn-group-vertical > .btn {
+ position: relative;
+ float: left;
+}
+.btn-group > .btn:hover,
+.btn-group-vertical > .btn:hover,
+.btn-group > .btn:focus,
+.btn-group-vertical > .btn:focus,
+.btn-group > .btn:active,
+.btn-group-vertical > .btn:active,
+.btn-group > .btn.active,
+.btn-group-vertical > .btn.active {
+ z-index: 2;
+}
+.btn-group .btn + .btn,
+.btn-group .btn + .btn-group,
+.btn-group .btn-group + .btn,
+.btn-group .btn-group + .btn-group {
+ margin-left: -1px;
+}
+.btn-toolbar {
+ margin-left: -5px;
+}
+.btn-toolbar .btn,
+.btn-toolbar .btn-group,
+.btn-toolbar .input-group {
+ float: left;
+}
+.btn-toolbar > .btn,
+.btn-toolbar > .btn-group,
+.btn-toolbar > .input-group {
+ margin-left: 5px;
+}
+.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
+ border-radius: 0;
+}
+.btn-group > .btn:first-child {
+ margin-left: 0;
+}
+.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.btn-group > .btn:last-child:not(:first-child),
+.btn-group > .dropdown-toggle:not(:first-child) {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group > .btn-group {
+ float: left;
+}
+.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
+ border-radius: 0;
+}
+.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group .dropdown-toggle:active,
+.btn-group.open .dropdown-toggle {
+ outline: 0;
+}
+.btn-group > .btn + .dropdown-toggle {
+ padding-right: 8px;
+ padding-left: 8px;
+}
+.btn-group > .btn-lg + .dropdown-toggle {
+ padding-right: 12px;
+ padding-left: 12px;
+}
+.btn-group.open .dropdown-toggle {
+ -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+ box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn-group.open .dropdown-toggle.btn-link {
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+.btn .caret {
+ margin-left: 0;
+}
+.btn-lg .caret {
+ border-width: 5px 5px 0;
+ border-bottom-width: 0;
+}
+.dropup .btn-lg .caret {
+ border-width: 0 5px 5px;
+}
+.btn-group-vertical > .btn,
+.btn-group-vertical > .btn-group,
+.btn-group-vertical > .btn-group > .btn {
+ display: block;
+ float: none;
+ width: 100%;
+ max-width: 100%;
+}
+.btn-group-vertical > .btn-group > .btn {
+ float: none;
+}
+.btn-group-vertical > .btn + .btn,
+.btn-group-vertical > .btn + .btn-group,
+.btn-group-vertical > .btn-group + .btn,
+.btn-group-vertical > .btn-group + .btn-group {
+ margin-top: -1px;
+ margin-left: 0;
+}
+.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
+ border-radius: 0;
+}
+.btn-group-vertical > .btn:first-child:not(:last-child) {
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group-vertical > .btn:last-child:not(:first-child) {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+}
+.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
+ border-radius: 0;
+}
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.btn-group-justified {
+ display: table;
+ width: 100%;
+ table-layout: fixed;
+ border-collapse: separate;
+}
+.btn-group-justified > .btn,
+.btn-group-justified > .btn-group {
+ display: table-cell;
+ float: none;
+ width: 1%;
+}
+.btn-group-justified > .btn-group .btn {
+ width: 100%;
+}
+.btn-group-justified > .btn-group .dropdown-menu {
+ left: auto;
+}
+[data-toggle="buttons"] > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn input[type="checkbox"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
+ position: absolute;
+ clip: rect(0, 0, 0, 0);
+ pointer-events: none;
+}
+.input-group {
+ position: relative;
+ display: table;
+ border-collapse: separate;
+}
+.input-group[class*="col-"] {
+ float: none;
+ padding-right: 0;
+ padding-left: 0;
+}
+.input-group .form-control {
+ position: relative;
+ z-index: 2;
+ float: left;
+ width: 100%;
+ margin-bottom: 0;
+}
+.input-group .form-control:focus {
+ z-index: 3;
+}
+.input-group-lg > .form-control,
+.input-group-lg > .input-group-addon,
+.input-group-lg > .input-group-btn > .btn {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+select.input-group-lg > .form-control,
+select.input-group-lg > .input-group-addon,
+select.input-group-lg > .input-group-btn > .btn {
+ height: 46px;
+ line-height: 46px;
+}
+textarea.input-group-lg > .form-control,
+textarea.input-group-lg > .input-group-addon,
+textarea.input-group-lg > .input-group-btn > .btn,
+select[multiple].input-group-lg > .form-control,
+select[multiple].input-group-lg > .input-group-addon,
+select[multiple].input-group-lg > .input-group-btn > .btn {
+ height: auto;
+}
+.input-group-sm > .form-control,
+.input-group-sm > .input-group-addon,
+.input-group-sm > .input-group-btn > .btn {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+select.input-group-sm > .form-control,
+select.input-group-sm > .input-group-addon,
+select.input-group-sm > .input-group-btn > .btn {
+ height: 30px;
+ line-height: 30px;
+}
+textarea.input-group-sm > .form-control,
+textarea.input-group-sm > .input-group-addon,
+textarea.input-group-sm > .input-group-btn > .btn,
+select[multiple].input-group-sm > .form-control,
+select[multiple].input-group-sm > .input-group-addon,
+select[multiple].input-group-sm > .input-group-btn > .btn {
+ height: auto;
+}
+.input-group-addon,
+.input-group-btn,
+.input-group .form-control {
+ display: table-cell;
+}
+.input-group-addon:not(:first-child):not(:last-child),
+.input-group-btn:not(:first-child):not(:last-child),
+.input-group .form-control:not(:first-child):not(:last-child) {
+ border-radius: 0;
+}
+.input-group-addon,
+.input-group-btn {
+ width: 1%;
+ white-space: nowrap;
+ vertical-align: middle;
+}
+.input-group-addon {
+ padding: 6px 12px;
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 1;
+ color: #555;
+ text-align: center;
+ background-color: #eee;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+}
+.input-group-addon.input-sm {
+ padding: 5px 10px;
+ font-size: 12px;
+ border-radius: 3px;
+}
+.input-group-addon.input-lg {
+ padding: 10px 16px;
+ font-size: 18px;
+ border-radius: 6px;
+}
+.input-group-addon input[type="radio"],
+.input-group-addon input[type="checkbox"] {
+ margin-top: 0;
+}
+.input-group .form-control:first-child,
+.input-group-addon:first-child,
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group > .btn,
+.input-group-btn:first-child > .dropdown-toggle,
+.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
+.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.input-group-addon:first-child {
+ border-right: 0;
+}
+.input-group .form-control:last-child,
+.input-group-addon:last-child,
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group > .btn,
+.input-group-btn:last-child > .dropdown-toggle,
+.input-group-btn:first-child > .btn:not(:first-child),
+.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.input-group-addon:last-child {
+ border-left: 0;
+}
+.input-group-btn {
+ position: relative;
+ font-size: 0;
+ white-space: nowrap;
+}
+.input-group-btn > .btn {
+ position: relative;
+}
+.input-group-btn > .btn + .btn {
+ margin-left: -1px;
+}
+.input-group-btn > .btn:hover,
+.input-group-btn > .btn:focus,
+.input-group-btn > .btn:active {
+ z-index: 2;
+}
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group {
+ margin-right: -1px;
+}
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group {
+ z-index: 2;
+ margin-left: -1px;
+}
+.nav {
+ padding-left: 0;
+ margin-bottom: 0;
+ list-style: none;
+}
+.nav > li {
+ position: relative;
+ display: block;
+}
+.nav > li > a {
+ position: relative;
+ display: block;
+ padding: 10px 15px;
+}
+.nav > li > a:hover,
+.nav > li > a:focus {
+ text-decoration: none;
+ background-color: #eee;
+}
+.nav > li.disabled > a {
+ color: #777;
+}
+.nav > li.disabled > a:hover,
+.nav > li.disabled > a:focus {
+ color: #777;
+ text-decoration: none;
+ cursor: not-allowed;
+ background-color: transparent;
+}
+.nav .open > a,
+.nav .open > a:hover,
+.nav .open > a:focus {
+ background-color: #eee;
+ border-color: #337ab7;
+}
+.nav .nav-divider {
+ height: 1px;
+ margin: 9px 0;
+ overflow: hidden;
+ background-color: #e5e5e5;
+}
+.nav > li > a > img {
+ max-width: none;
+}
+.nav-tabs {
+ border-bottom: 1px solid #ddd;
+}
+.nav-tabs > li {
+ float: left;
+ margin-bottom: -1px;
+}
+.nav-tabs > li > a {
+ margin-right: 2px;
+ line-height: 1.42857143;
+ border: 1px solid transparent;
+ border-radius: 4px 4px 0 0;
+}
+.nav-tabs > li > a:hover {
+ border-color: #eee #eee #ddd;
+}
+.nav-tabs > li.active > a,
+.nav-tabs > li.active > a:hover,
+.nav-tabs > li.active > a:focus {
+ color: #555;
+ cursor: default;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-bottom-color: transparent;
+}
+.nav-tabs.nav-justified {
+ width: 100%;
+ border-bottom: 0;
+}
+.nav-tabs.nav-justified > li {
+ float: none;
+}
+.nav-tabs.nav-justified > li > a {
+ margin-bottom: 5px;
+ text-align: center;
+}
+.nav-tabs.nav-justified > .dropdown .dropdown-menu {
+ top: auto;
+ left: auto;
+}
+@media (min-width: 768px) {
+ .nav-tabs.nav-justified > li {
+ display: table-cell;
+ width: 1%;
+ }
+ .nav-tabs.nav-justified > li > a {
+ margin-bottom: 0;
+ }
+}
+.nav-tabs.nav-justified > li > a {
+ margin-right: 0;
+ border-radius: 4px;
+}
+.nav-tabs.nav-justified > .active > a,
+.nav-tabs.nav-justified > .active > a:hover,
+.nav-tabs.nav-justified > .active > a:focus {
+ border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+ .nav-tabs.nav-justified > li > a {
+ border-bottom: 1px solid #ddd;
+ border-radius: 4px 4px 0 0;
+ }
+ .nav-tabs.nav-justified > .active > a,
+ .nav-tabs.nav-justified > .active > a:hover,
+ .nav-tabs.nav-justified > .active > a:focus {
+ border-bottom-color: #fff;
+ }
+}
+.nav-pills > li {
+ float: left;
+}
+.nav-pills > li > a {
+ border-radius: 4px;
+}
+.nav-pills > li + li {
+ margin-left: 2px;
+}
+.nav-pills > li.active > a,
+.nav-pills > li.active > a:hover,
+.nav-pills > li.active > a:focus {
+ color: #fff;
+ background-color: #337ab7;
+}
+.nav-stacked > li {
+ float: none;
+}
+.nav-stacked > li + li {
+ margin-top: 2px;
+ margin-left: 0;
+}
+.nav-justified {
+ width: 100%;
+}
+.nav-justified > li {
+ float: none;
+}
+.nav-justified > li > a {
+ margin-bottom: 5px;
+ text-align: center;
+}
+.nav-justified > .dropdown .dropdown-menu {
+ top: auto;
+ left: auto;
+}
+@media (min-width: 768px) {
+ .nav-justified > li {
+ display: table-cell;
+ width: 1%;
+ }
+ .nav-justified > li > a {
+ margin-bottom: 0;
+ }
+}
+.nav-tabs-justified {
+ border-bottom: 0;
+}
+.nav-tabs-justified > li > a {
+ margin-right: 0;
+ border-radius: 4px;
+}
+.nav-tabs-justified > .active > a,
+.nav-tabs-justified > .active > a:hover,
+.nav-tabs-justified > .active > a:focus {
+ border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+ .nav-tabs-justified > li > a {
+ border-bottom: 1px solid #ddd;
+ border-radius: 4px 4px 0 0;
+ }
+ .nav-tabs-justified > .active > a,
+ .nav-tabs-justified > .active > a:hover,
+ .nav-tabs-justified > .active > a:focus {
+ border-bottom-color: #fff;
+ }
+}
+.tab-content > .tab-pane {
+ display: none;
+}
+.tab-content > .active {
+ display: block;
+}
+.nav-tabs .dropdown-menu {
+ margin-top: -1px;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.navbar {
+ position: relative;
+ min-height: 50px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+}
+@media (min-width: 768px) {
+ .navbar {
+ border-radius: 4px;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-header {
+ float: left;
+ }
+}
+.navbar-collapse {
+ padding-right: 15px;
+ padding-left: 15px;
+ overflow-x: visible;
+ -webkit-overflow-scrolling: touch;
+ border-top: 1px solid transparent;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+}
+.navbar-collapse.in {
+ overflow-y: auto;
+}
+@media (min-width: 768px) {
+ .navbar-collapse {
+ width: auto;
+ border-top: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+ .navbar-collapse.collapse {
+ display: block !important;
+ height: auto !important;
+ padding-bottom: 0;
+ overflow: visible !important;
+ }
+ .navbar-collapse.in {
+ overflow-y: visible;
+ }
+ .navbar-fixed-top .navbar-collapse,
+ .navbar-static-top .navbar-collapse,
+ .navbar-fixed-bottom .navbar-collapse {
+ padding-right: 0;
+ padding-left: 0;
+ }
+}
+.navbar-fixed-top .navbar-collapse,
+.navbar-fixed-bottom .navbar-collapse {
+ max-height: 340px;
+}
+@media (max-device-width: 480px) and (orientation: landscape) {
+ .navbar-fixed-top .navbar-collapse,
+ .navbar-fixed-bottom .navbar-collapse {
+ max-height: 200px;
+ }
+}
+.container > .navbar-header,
+.container-fluid > .navbar-header,
+.container > .navbar-collapse,
+.container-fluid > .navbar-collapse {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+@media (min-width: 768px) {
+ .container > .navbar-header,
+ .container-fluid > .navbar-header,
+ .container > .navbar-collapse,
+ .container-fluid > .navbar-collapse {
+ margin-right: 0;
+ margin-left: 0;
+ }
+}
+.navbar-static-top {
+ z-index: 1000;
+ border-width: 0 0 1px;
+}
+@media (min-width: 768px) {
+ .navbar-static-top {
+ border-radius: 0;
+ }
+}
+.navbar-fixed-top,
+.navbar-fixed-bottom {
+ position: fixed;
+ right: 0;
+ left: 0;
+ z-index: 1030;
+}
+@media (min-width: 768px) {
+ .navbar-fixed-top,
+ .navbar-fixed-bottom {
+ border-radius: 0;
+ }
+}
+.navbar-fixed-top {
+ top: 0;
+ border-width: 0 0 1px;
+}
+.navbar-fixed-bottom {
+ bottom: 0;
+ margin-bottom: 0;
+ border-width: 1px 0 0;
+}
+.navbar-brand {
+ float: left;
+ height: 50px;
+ padding: 15px 15px;
+ font-size: 18px;
+ line-height: 20px;
+}
+.navbar-brand:hover,
+.navbar-brand:focus {
+ text-decoration: none;
+}
+.navbar-brand > img {
+ display: block;
+}
+@media (min-width: 768px) {
+ .navbar > .container .navbar-brand,
+ .navbar > .container-fluid .navbar-brand {
+ margin-left: -15px;
+ }
+}
+.navbar-toggle {
+ position: relative;
+ float: right;
+ padding: 9px 10px;
+ margin-top: 8px;
+ margin-right: 15px;
+ margin-bottom: 8px;
+ background-color: transparent;
+ background-image: none;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.navbar-toggle:focus {
+ outline: 0;
+}
+.navbar-toggle .icon-bar {
+ display: block;
+ width: 22px;
+ height: 2px;
+ border-radius: 1px;
+}
+.navbar-toggle .icon-bar + .icon-bar {
+ margin-top: 4px;
+}
+@media (min-width: 768px) {
+ .navbar-toggle {
+ display: none;
+ }
+}
+.navbar-nav {
+ margin: 7.5px -15px;
+}
+.navbar-nav > li > a {
+ padding-top: 10px;
+ padding-bottom: 10px;
+ line-height: 20px;
+}
+@media (max-width: 767px) {
+ .navbar-nav .open .dropdown-menu {
+ position: static;
+ float: none;
+ width: auto;
+ margin-top: 0;
+ background-color: transparent;
+ border: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+ .navbar-nav .open .dropdown-menu > li > a,
+ .navbar-nav .open .dropdown-menu .dropdown-header {
+ padding: 5px 15px 5px 25px;
+ }
+ .navbar-nav .open .dropdown-menu > li > a {
+ line-height: 20px;
+ }
+ .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-nav .open .dropdown-menu > li > a:focus {
+ background-image: none;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-nav {
+ float: left;
+ margin: 0;
+ }
+ .navbar-nav > li {
+ float: left;
+ }
+ .navbar-nav > li > a {
+ padding-top: 15px;
+ padding-bottom: 15px;
+ }
+}
+.navbar-form {
+ padding: 10px 15px;
+ margin-top: 8px;
+ margin-right: -15px;
+ margin-bottom: 8px;
+ margin-left: -15px;
+ border-top: 1px solid transparent;
+ border-bottom: 1px solid transparent;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+}
+@media (min-width: 768px) {
+ .navbar-form .form-group {
+ display: inline-block;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .form-control {
+ display: inline-block;
+ width: auto;
+ vertical-align: middle;
+ }
+ .navbar-form .form-control-static {
+ display: inline-block;
+ }
+ .navbar-form .input-group {
+ display: inline-table;
+ vertical-align: middle;
+ }
+ .navbar-form .input-group .input-group-addon,
+ .navbar-form .input-group .input-group-btn,
+ .navbar-form .input-group .form-control {
+ width: auto;
+ }
+ .navbar-form .input-group > .form-control {
+ width: 100%;
+ }
+ .navbar-form .control-label {
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .radio,
+ .navbar-form .checkbox {
+ display: inline-block;
+ margin-top: 0;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .radio label,
+ .navbar-form .checkbox label {
+ padding-left: 0;
+ }
+ .navbar-form .radio input[type="radio"],
+ .navbar-form .checkbox input[type="checkbox"] {
+ position: relative;
+ margin-left: 0;
+ }
+ .navbar-form .has-feedback .form-control-feedback {
+ top: 0;
+ }
+}
+@media (max-width: 767px) {
+ .navbar-form .form-group {
+ margin-bottom: 5px;
+ }
+ .navbar-form .form-group:last-child {
+ margin-bottom: 0;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-form {
+ width: auto;
+ padding-top: 0;
+ padding-bottom: 0;
+ margin-right: 0;
+ margin-left: 0;
+ border: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+}
+.navbar-nav > li > .dropdown-menu {
+ margin-top: 0;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
+ margin-bottom: 0;
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.navbar-btn {
+ margin-top: 8px;
+ margin-bottom: 8px;
+}
+.navbar-btn.btn-sm {
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+.navbar-btn.btn-xs {
+ margin-top: 14px;
+ margin-bottom: 14px;
+}
+.navbar-text {
+ margin-top: 15px;
+ margin-bottom: 15px;
+}
+@media (min-width: 768px) {
+ .navbar-text {
+ float: left;
+ margin-right: 15px;
+ margin-left: 15px;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-left {
+ float: left !important;
+ }
+ .navbar-right {
+ float: right !important;
+ margin-right: -15px;
+ }
+ .navbar-right ~ .navbar-right {
+ margin-right: 0;
+ }
+}
+.navbar-default {
+ background-color: #f8f8f8;
+ border-color: #e7e7e7;
+}
+.navbar-default .navbar-brand {
+ color: #777;
+}
+.navbar-default .navbar-brand:hover,
+.navbar-default .navbar-brand:focus {
+ color: #5e5e5e;
+ background-color: transparent;
+}
+.navbar-default .navbar-text {
+ color: #777;
+}
+.navbar-default .navbar-nav > li > a {
+ color: #777;
+}
+.navbar-default .navbar-nav > li > a:hover,
+.navbar-default .navbar-nav > li > a:focus {
+ color: #333;
+ background-color: transparent;
+}
+.navbar-default .navbar-nav > .active > a,
+.navbar-default .navbar-nav > .active > a:hover,
+.navbar-default .navbar-nav > .active > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+}
+.navbar-default .navbar-nav > .disabled > a,
+.navbar-default .navbar-nav > .disabled > a:hover,
+.navbar-default .navbar-nav > .disabled > a:focus {
+ color: #ccc;
+ background-color: transparent;
+}
+.navbar-default .navbar-toggle {
+ border-color: #ddd;
+}
+.navbar-default .navbar-toggle:hover,
+.navbar-default .navbar-toggle:focus {
+ background-color: #ddd;
+}
+.navbar-default .navbar-toggle .icon-bar {
+ background-color: #888;
+}
+.navbar-default .navbar-collapse,
+.navbar-default .navbar-form {
+ border-color: #e7e7e7;
+}
+.navbar-default .navbar-nav > .open > a,
+.navbar-default .navbar-nav > .open > a:hover,
+.navbar-default .navbar-nav > .open > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+}
+@media (max-width: 767px) {
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a {
+ color: #777;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
+ color: #333;
+ background-color: transparent;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+ color: #ccc;
+ background-color: transparent;
+ }
+}
+.navbar-default .navbar-link {
+ color: #777;
+}
+.navbar-default .navbar-link:hover {
+ color: #333;
+}
+.navbar-default .btn-link {
+ color: #777;
+}
+.navbar-default .btn-link:hover,
+.navbar-default .btn-link:focus {
+ color: #333;
+}
+.navbar-default .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-default .btn-link:hover,
+.navbar-default .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-default .btn-link:focus {
+ color: #ccc;
+}
+.navbar-inverse {
+ background-color: #222;
+ border-color: #080808;
+}
+.navbar-inverse .navbar-brand {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-brand:hover,
+.navbar-inverse .navbar-brand:focus {
+ color: #fff;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-text {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-nav > li > a {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-nav > li > a:hover,
+.navbar-inverse .navbar-nav > li > a:focus {
+ color: #fff;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-nav > .active > a,
+.navbar-inverse .navbar-nav > .active > a:hover,
+.navbar-inverse .navbar-nav > .active > a:focus {
+ color: #fff;
+ background-color: #080808;
+}
+.navbar-inverse .navbar-nav > .disabled > a,
+.navbar-inverse .navbar-nav > .disabled > a:hover,
+.navbar-inverse .navbar-nav > .disabled > a:focus {
+ color: #444;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-toggle {
+ border-color: #333;
+}
+.navbar-inverse .navbar-toggle:hover,
+.navbar-inverse .navbar-toggle:focus {
+ background-color: #333;
+}
+.navbar-inverse .navbar-toggle .icon-bar {
+ background-color: #fff;
+}
+.navbar-inverse .navbar-collapse,
+.navbar-inverse .navbar-form {
+ border-color: #101010;
+}
+.navbar-inverse .navbar-nav > .open > a,
+.navbar-inverse .navbar-nav > .open > a:hover,
+.navbar-inverse .navbar-nav > .open > a:focus {
+ color: #fff;
+ background-color: #080808;
+}
+@media (max-width: 767px) {
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
+ border-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu .divider {
+ background-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
+ color: #9d9d9d;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
+ color: #fff;
+ background-color: transparent;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
+ color: #fff;
+ background-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+ color: #444;
+ background-color: transparent;
+ }
+}
+.navbar-inverse .navbar-link {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-link:hover {
+ color: #fff;
+}
+.navbar-inverse .btn-link {
+ color: #9d9d9d;
+}
+.navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link:focus {
+ color: #fff;
+}
+.navbar-inverse .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-inverse .btn-link:focus {
+ color: #444;
+}
+.breadcrumb {
+ padding: 8px 15px;
+ margin-bottom: 20px;
+ list-style: none;
+ background-color: #f5f5f5;
+ border-radius: 4px;
+}
+.breadcrumb > li {
+ display: inline-block;
+}
+.breadcrumb > li + li:before {
+ padding: 0 5px;
+ color: #ccc;
+ content: "/\00a0";
+}
+.breadcrumb > .active {
+ color: #777;
+}
+.pagination {
+ display: inline-block;
+ padding-left: 0;
+ margin: 20px 0;
+ border-radius: 4px;
+}
+.pagination > li {
+ display: inline;
+}
+.pagination > li > a,
+.pagination > li > span {
+ position: relative;
+ float: left;
+ padding: 6px 12px;
+ margin-left: -1px;
+ line-height: 1.42857143;
+ color: #337ab7;
+ text-decoration: none;
+ background-color: #fff;
+ border: 1px solid #ddd;
+}
+.pagination > li:first-child > a,
+.pagination > li:first-child > span {
+ margin-left: 0;
+ border-top-left-radius: 4px;
+ border-bottom-left-radius: 4px;
+}
+.pagination > li:last-child > a,
+.pagination > li:last-child > span {
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 4px;
+}
+.pagination > li > a:hover,
+.pagination > li > span:hover,
+.pagination > li > a:focus,
+.pagination > li > span:focus {
+ z-index: 2;
+ color: #23527c;
+ background-color: #eee;
+ border-color: #ddd;
+}
+.pagination > .active > a,
+.pagination > .active > span,
+.pagination > .active > a:hover,
+.pagination > .active > span:hover,
+.pagination > .active > a:focus,
+.pagination > .active > span:focus {
+ z-index: 3;
+ color: #fff;
+ cursor: default;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.pagination > .disabled > span,
+.pagination > .disabled > span:hover,
+.pagination > .disabled > span:focus,
+.pagination > .disabled > a,
+.pagination > .disabled > a:hover,
+.pagination > .disabled > a:focus {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #fff;
+ border-color: #ddd;
+}
+.pagination-lg > li > a,
+.pagination-lg > li > span {
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+}
+.pagination-lg > li:first-child > a,
+.pagination-lg > li:first-child > span {
+ border-top-left-radius: 6px;
+ border-bottom-left-radius: 6px;
+}
+.pagination-lg > li:last-child > a,
+.pagination-lg > li:last-child > span {
+ border-top-right-radius: 6px;
+ border-bottom-right-radius: 6px;
+}
+.pagination-sm > li > a,
+.pagination-sm > li > span {
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+}
+.pagination-sm > li:first-child > a,
+.pagination-sm > li:first-child > span {
+ border-top-left-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.pagination-sm > li:last-child > a,
+.pagination-sm > li:last-child > span {
+ border-top-right-radius: 3px;
+ border-bottom-right-radius: 3px;
+}
+.pager {
+ padding-left: 0;
+ margin: 20px 0;
+ text-align: center;
+ list-style: none;
+}
+.pager li {
+ display: inline;
+}
+.pager li > a,
+.pager li > span {
+ display: inline-block;
+ padding: 5px 14px;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 15px;
+}
+.pager li > a:hover,
+.pager li > a:focus {
+ text-decoration: none;
+ background-color: #eee;
+}
+.pager .next > a,
+.pager .next > span {
+ float: right;
+}
+.pager .previous > a,
+.pager .previous > span {
+ float: left;
+}
+.pager .disabled > a,
+.pager .disabled > a:hover,
+.pager .disabled > a:focus,
+.pager .disabled > span {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #fff;
+}
+.label {
+ display: inline;
+ padding: .2em .6em .3em;
+ font-size: 75%;
+ font-weight: bold;
+ line-height: 1;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: baseline;
+ border-radius: .25em;
+}
+a.label:hover,
+a.label:focus {
+ color: #fff;
+ text-decoration: none;
+ cursor: pointer;
+}
+.label:empty {
+ display: none;
+}
+.btn .label {
+ position: relative;
+ top: -1px;
+}
+.label-default {
+ background-color: #777;
+}
+.label-default[href]:hover,
+.label-default[href]:focus {
+ background-color: #5e5e5e;
+}
+.label-primary {
+ background-color: #337ab7;
+}
+.label-primary[href]:hover,
+.label-primary[href]:focus {
+ background-color: #286090;
+}
+.label-success {
+ background-color: #5cb85c;
+}
+.label-success[href]:hover,
+.label-success[href]:focus {
+ background-color: #449d44;
+}
+.label-info {
+ background-color: #5bc0de;
+}
+.label-info[href]:hover,
+.label-info[href]:focus {
+ background-color: #31b0d5;
+}
+.label-warning {
+ background-color: #f0ad4e;
+}
+.label-warning[href]:hover,
+.label-warning[href]:focus {
+ background-color: #ec971f;
+}
+.label-danger {
+ background-color: #d9534f;
+}
+.label-danger[href]:hover,
+.label-danger[href]:focus {
+ background-color: #c9302c;
+}
+.badge {
+ display: inline-block;
+ min-width: 10px;
+ padding: 3px 7px;
+ font-size: 12px;
+ font-weight: bold;
+ line-height: 1;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ background-color: #777;
+ border-radius: 10px;
+}
+.badge:empty {
+ display: none;
+}
+.btn .badge {
+ position: relative;
+ top: -1px;
+}
+.btn-xs .badge,
+.btn-group-xs > .btn .badge {
+ top: 0;
+ padding: 1px 5px;
+}
+a.badge:hover,
+a.badge:focus {
+ color: #fff;
+ text-decoration: none;
+ cursor: pointer;
+}
+.list-group-item.active > .badge,
+.nav-pills > .active > a > .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.list-group-item > .badge {
+ float: right;
+}
+.list-group-item > .badge + .badge {
+ margin-right: 5px;
+}
+.nav-pills > li > a > .badge {
+ margin-left: 3px;
+}
+.jumbotron {
+ padding-top: 30px;
+ padding-bottom: 30px;
+ margin-bottom: 30px;
+ color: inherit;
+ background-color: #eee;
+}
+.jumbotron h1,
+.jumbotron .h1 {
+ color: inherit;
+}
+.jumbotron p {
+ margin-bottom: 15px;
+ font-size: 21px;
+ font-weight: 200;
+}
+.jumbotron > hr {
+ border-top-color: #d5d5d5;
+}
+.container .jumbotron,
+.container-fluid .jumbotron {
+ padding-right: 15px;
+ padding-left: 15px;
+ border-radius: 6px;
+}
+.jumbotron .container {
+ max-width: 100%;
+}
+@media screen and (min-width: 768px) {
+ .jumbotron {
+ padding-top: 48px;
+ padding-bottom: 48px;
+ }
+ .container .jumbotron,
+ .container-fluid .jumbotron {
+ padding-right: 60px;
+ padding-left: 60px;
+ }
+ .jumbotron h1,
+ .jumbotron .h1 {
+ font-size: 63px;
+ }
+}
+.thumbnail {
+ display: block;
+ padding: 4px;
+ margin-bottom: 20px;
+ line-height: 1.42857143;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ -webkit-transition: border .2s ease-in-out;
+ -o-transition: border .2s ease-in-out;
+ transition: border .2s ease-in-out;
+}
+.thumbnail > img,
+.thumbnail a > img {
+ margin-right: auto;
+ margin-left: auto;
+}
+a.thumbnail:hover,
+a.thumbnail:focus,
+a.thumbnail.active {
+ border-color: #337ab7;
+}
+.thumbnail .caption {
+ padding: 9px;
+ color: #333;
+}
+.alert {
+ padding: 15px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.alert h4 {
+ margin-top: 0;
+ color: inherit;
+}
+.alert .alert-link {
+ font-weight: bold;
+}
+.alert > p,
+.alert > ul {
+ margin-bottom: 0;
+}
+.alert > p + p {
+ margin-top: 5px;
+}
+.alert-dismissable,
+.alert-dismissible {
+ padding-right: 35px;
+}
+.alert-dismissable .close,
+.alert-dismissible .close {
+ position: relative;
+ top: -2px;
+ right: -21px;
+ color: inherit;
+}
+.alert-success {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #d6e9c6;
+}
+.alert-success hr {
+ border-top-color: #c9e2b3;
+}
+.alert-success .alert-link {
+ color: #2b542c;
+}
+.alert-info {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.alert-info hr {
+ border-top-color: #a6e1ec;
+}
+.alert-info .alert-link {
+ color: #245269;
+}
+.alert-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.alert-warning hr {
+ border-top-color: #f7e1b5;
+}
+.alert-warning .alert-link {
+ color: #66512c;
+}
+.alert-danger {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.alert-danger hr {
+ border-top-color: #e4b9c0;
+}
+.alert-danger .alert-link {
+ color: #843534;
+}
+@-webkit-keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+@-o-keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+@keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+.progress {
+ height: 20px;
+ margin-bottom: 20px;
+ overflow: hidden;
+ background-color: #f5f5f5;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+}
+.progress-bar {
+ float: left;
+ width: 0;
+ height: 100%;
+ font-size: 12px;
+ line-height: 20px;
+ color: #fff;
+ text-align: center;
+ background-color: #337ab7;
+ -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+ box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+ -webkit-transition: width .6s ease;
+ -o-transition: width .6s ease;
+ transition: width .6s ease;
+}
+.progress-striped .progress-bar,
+.progress-bar-striped {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ -webkit-background-size: 40px 40px;
+ background-size: 40px 40px;
+}
+.progress.active .progress-bar,
+.progress-bar.active {
+ -webkit-animation: progress-bar-stripes 2s linear infinite;
+ -o-animation: progress-bar-stripes 2s linear infinite;
+ animation: progress-bar-stripes 2s linear infinite;
+}
+.progress-bar-success {
+ background-color: #5cb85c;
+}
+.progress-striped .progress-bar-success {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-info {
+ background-color: #5bc0de;
+}
+.progress-striped .progress-bar-info {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-warning {
+ background-color: #f0ad4e;
+}
+.progress-striped .progress-bar-warning {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-danger {
+ background-color: #d9534f;
+}
+.progress-striped .progress-bar-danger {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.media {
+ margin-top: 15px;
+}
+.media:first-child {
+ margin-top: 0;
+}
+.media,
+.media-body {
+ overflow: hidden;
+ zoom: 1;
+}
+.media-body {
+ width: 10000px;
+}
+.media-object {
+ display: block;
+}
+.media-object.img-thumbnail {
+ max-width: none;
+}
+.media-right,
+.media > .pull-right {
+ padding-left: 10px;
+}
+.media-left,
+.media > .pull-left {
+ padding-right: 10px;
+}
+.media-left,
+.media-right,
+.media-body {
+ display: table-cell;
+ vertical-align: top;
+}
+.media-middle {
+ vertical-align: middle;
+}
+.media-bottom {
+ vertical-align: bottom;
+}
+.media-heading {
+ margin-top: 0;
+ margin-bottom: 5px;
+}
+.media-list {
+ padding-left: 0;
+ list-style: none;
+}
+.list-group {
+ padding-left: 0;
+ margin-bottom: 20px;
+}
+.list-group-item {
+ position: relative;
+ display: block;
+ padding: 10px 15px;
+ margin-bottom: -1px;
+ background-color: #fff;
+ border: 1px solid #ddd;
+}
+.list-group-item:first-child {
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+}
+.list-group-item:last-child {
+ margin-bottom: 0;
+ border-bottom-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+}
+a.list-group-item,
+button.list-group-item {
+ color: #555;
+}
+a.list-group-item .list-group-item-heading,
+button.list-group-item .list-group-item-heading {
+ color: #333;
+}
+a.list-group-item:hover,
+button.list-group-item:hover,
+a.list-group-item:focus,
+button.list-group-item:focus {
+ color: #555;
+ text-decoration: none;
+ background-color: #f5f5f5;
+}
+button.list-group-item {
+ width: 100%;
+ text-align: left;
+}
+.list-group-item.disabled,
+.list-group-item.disabled:hover,
+.list-group-item.disabled:focus {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #eee;
+}
+.list-group-item.disabled .list-group-item-heading,
+.list-group-item.disabled:hover .list-group-item-heading,
+.list-group-item.disabled:focus .list-group-item-heading {
+ color: inherit;
+}
+.list-group-item.disabled .list-group-item-text,
+.list-group-item.disabled:hover .list-group-item-text,
+.list-group-item.disabled:focus .list-group-item-text {
+ color: #777;
+}
+.list-group-item.active,
+.list-group-item.active:hover,
+.list-group-item.active:focus {
+ z-index: 2;
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.list-group-item.active .list-group-item-heading,
+.list-group-item.active:hover .list-group-item-heading,
+.list-group-item.active:focus .list-group-item-heading,
+.list-group-item.active .list-group-item-heading > small,
+.list-group-item.active:hover .list-group-item-heading > small,
+.list-group-item.active:focus .list-group-item-heading > small,
+.list-group-item.active .list-group-item-heading > .small,
+.list-group-item.active:hover .list-group-item-heading > .small,
+.list-group-item.active:focus .list-group-item-heading > .small {
+ color: inherit;
+}
+.list-group-item.active .list-group-item-text,
+.list-group-item.active:hover .list-group-item-text,
+.list-group-item.active:focus .list-group-item-text {
+ color: #c7ddef;
+}
+.list-group-item-success {
+ color: #3c763d;
+ background-color: #dff0d8;
+}
+a.list-group-item-success,
+button.list-group-item-success {
+ color: #3c763d;
+}
+a.list-group-item-success .list-group-item-heading,
+button.list-group-item-success .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-success:hover,
+button.list-group-item-success:hover,
+a.list-group-item-success:focus,
+button.list-group-item-success:focus {
+ color: #3c763d;
+ background-color: #d0e9c6;
+}
+a.list-group-item-success.active,
+button.list-group-item-success.active,
+a.list-group-item-success.active:hover,
+button.list-group-item-success.active:hover,
+a.list-group-item-success.active:focus,
+button.list-group-item-success.active:focus {
+ color: #fff;
+ background-color: #3c763d;
+ border-color: #3c763d;
+}
+.list-group-item-info {
+ color: #31708f;
+ background-color: #d9edf7;
+}
+a.list-group-item-info,
+button.list-group-item-info {
+ color: #31708f;
+}
+a.list-group-item-info .list-group-item-heading,
+button.list-group-item-info .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-info:hover,
+button.list-group-item-info:hover,
+a.list-group-item-info:focus,
+button.list-group-item-info:focus {
+ color: #31708f;
+ background-color: #c4e3f3;
+}
+a.list-group-item-info.active,
+button.list-group-item-info.active,
+a.list-group-item-info.active:hover,
+button.list-group-item-info.active:hover,
+a.list-group-item-info.active:focus,
+button.list-group-item-info.active:focus {
+ color: #fff;
+ background-color: #31708f;
+ border-color: #31708f;
+}
+.list-group-item-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+}
+a.list-group-item-warning,
+button.list-group-item-warning {
+ color: #8a6d3b;
+}
+a.list-group-item-warning .list-group-item-heading,
+button.list-group-item-warning .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-warning:hover,
+button.list-group-item-warning:hover,
+a.list-group-item-warning:focus,
+button.list-group-item-warning:focus {
+ color: #8a6d3b;
+ background-color: #faf2cc;
+}
+a.list-group-item-warning.active,
+button.list-group-item-warning.active,
+a.list-group-item-warning.active:hover,
+button.list-group-item-warning.active:hover,
+a.list-group-item-warning.active:focus,
+button.list-group-item-warning.active:focus {
+ color: #fff;
+ background-color: #8a6d3b;
+ border-color: #8a6d3b;
+}
+.list-group-item-danger {
+ color: #a94442;
+ background-color: #f2dede;
+}
+a.list-group-item-danger,
+button.list-group-item-danger {
+ color: #a94442;
+}
+a.list-group-item-danger .list-group-item-heading,
+button.list-group-item-danger .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-danger:hover,
+button.list-group-item-danger:hover,
+a.list-group-item-danger:focus,
+button.list-group-item-danger:focus {
+ color: #a94442;
+ background-color: #ebcccc;
+}
+a.list-group-item-danger.active,
+button.list-group-item-danger.active,
+a.list-group-item-danger.active:hover,
+button.list-group-item-danger.active:hover,
+a.list-group-item-danger.active:focus,
+button.list-group-item-danger.active:focus {
+ color: #fff;
+ background-color: #a94442;
+ border-color: #a94442;
+}
+.list-group-item-heading {
+ margin-top: 0;
+ margin-bottom: 5px;
+}
+.list-group-item-text {
+ margin-bottom: 0;
+ line-height: 1.3;
+}
+.panel {
+ margin-bottom: 20px;
+ background-color: #fff;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+ box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+}
+.panel-body {
+ padding: 15px;
+}
+.panel-heading {
+ padding: 10px 15px;
+ border-bottom: 1px solid transparent;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel-heading > .dropdown .dropdown-toggle {
+ color: inherit;
+}
+.panel-title {
+ margin-top: 0;
+ margin-bottom: 0;
+ font-size: 16px;
+ color: inherit;
+}
+.panel-title > a,
+.panel-title > small,
+.panel-title > .small,
+.panel-title > small > a,
+.panel-title > .small > a {
+ color: inherit;
+}
+.panel-footer {
+ padding: 10px 15px;
+ background-color: #f5f5f5;
+ border-top: 1px solid #ddd;
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .list-group,
+.panel > .panel-collapse > .list-group {
+ margin-bottom: 0;
+}
+.panel > .list-group .list-group-item,
+.panel > .panel-collapse > .list-group .list-group-item {
+ border-width: 1px 0;
+ border-radius: 0;
+}
+.panel > .list-group:first-child .list-group-item:first-child,
+.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
+ border-top: 0;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .list-group:last-child .list-group-item:last-child,
+.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
+ border-bottom: 0;
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.panel-heading + .list-group .list-group-item:first-child {
+ border-top-width: 0;
+}
+.list-group + .panel-footer {
+ border-top-width: 0;
+}
+.panel > .table,
+.panel > .table-responsive > .table,
+.panel > .panel-collapse > .table {
+ margin-bottom: 0;
+}
+.panel > .table caption,
+.panel > .table-responsive > .table caption,
+.panel > .panel-collapse > .table caption {
+ padding-right: 15px;
+ padding-left: 15px;
+}
+.panel > .table:first-child,
+.panel > .table-responsive:first-child > .table:first-child {
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
+ border-top-left-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
+ border-top-right-radius: 3px;
+}
+.panel > .table:last-child,
+.panel > .table-responsive:last-child > .table:last-child {
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
+ border-bottom-right-radius: 3px;
+}
+.panel > .panel-body + .table,
+.panel > .panel-body + .table-responsive,
+.panel > .table + .panel-body,
+.panel > .table-responsive + .panel-body {
+ border-top: 1px solid #ddd;
+}
+.panel > .table > tbody:first-child > tr:first-child th,
+.panel > .table > tbody:first-child > tr:first-child td {
+ border-top: 0;
+}
+.panel > .table-bordered,
+.panel > .table-responsive > .table-bordered {
+ border: 0;
+}
+.panel > .table-bordered > thead > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
+.panel > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-bordered > thead > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
+.panel > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-bordered > tfoot > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+ border-left: 0;
+}
+.panel > .table-bordered > thead > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
+.panel > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-bordered > thead > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
+.panel > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-bordered > tfoot > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+ border-right: 0;
+}
+.panel > .table-bordered > thead > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
+.panel > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-bordered > thead > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
+.panel > .table-bordered > tbody > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
+ border-bottom: 0;
+}
+.panel > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-bordered > tfoot > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
+ border-bottom: 0;
+}
+.panel > .table-responsive {
+ margin-bottom: 0;
+ border: 0;
+}
+.panel-group {
+ margin-bottom: 20px;
+}
+.panel-group .panel {
+ margin-bottom: 0;
+ border-radius: 4px;
+}
+.panel-group .panel + .panel {
+ margin-top: 5px;
+}
+.panel-group .panel-heading {
+ border-bottom: 0;
+}
+.panel-group .panel-heading + .panel-collapse > .panel-body,
+.panel-group .panel-heading + .panel-collapse > .list-group {
+ border-top: 1px solid #ddd;
+}
+.panel-group .panel-footer {
+ border-top: 0;
+}
+.panel-group .panel-footer + .panel-collapse .panel-body {
+ border-bottom: 1px solid #ddd;
+}
+.panel-default {
+ border-color: #ddd;
+}
+.panel-default > .panel-heading {
+ color: #333;
+ background-color: #f5f5f5;
+ border-color: #ddd;
+}
+.panel-default > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #ddd;
+}
+.panel-default > .panel-heading .badge {
+ color: #f5f5f5;
+ background-color: #333;
+}
+.panel-default > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #ddd;
+}
+.panel-primary {
+ border-color: #337ab7;
+}
+.panel-primary > .panel-heading {
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.panel-primary > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #337ab7;
+}
+.panel-primary > .panel-heading .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.panel-primary > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #337ab7;
+}
+.panel-success {
+ border-color: #d6e9c6;
+}
+.panel-success > .panel-heading {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #d6e9c6;
+}
+.panel-success > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #d6e9c6;
+}
+.panel-success > .panel-heading .badge {
+ color: #dff0d8;
+ background-color: #3c763d;
+}
+.panel-success > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #d6e9c6;
+}
+.panel-info {
+ border-color: #bce8f1;
+}
+.panel-info > .panel-heading {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.panel-info > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #bce8f1;
+}
+.panel-info > .panel-heading .badge {
+ color: #d9edf7;
+ background-color: #31708f;
+}
+.panel-info > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #bce8f1;
+}
+.panel-warning {
+ border-color: #faebcc;
+}
+.panel-warning > .panel-heading {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.panel-warning > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #faebcc;
+}
+.panel-warning > .panel-heading .badge {
+ color: #fcf8e3;
+ background-color: #8a6d3b;
+}
+.panel-warning > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #faebcc;
+}
+.panel-danger {
+ border-color: #ebccd1;
+}
+.panel-danger > .panel-heading {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.panel-danger > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #ebccd1;
+}
+.panel-danger > .panel-heading .badge {
+ color: #f2dede;
+ background-color: #a94442;
+}
+.panel-danger > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #ebccd1;
+}
+.embed-responsive {
+ position: relative;
+ display: block;
+ height: 0;
+ padding: 0;
+ overflow: hidden;
+}
+.embed-responsive .embed-responsive-item,
+.embed-responsive iframe,
+.embed-responsive embed,
+.embed-responsive object,
+.embed-responsive video {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ border: 0;
+}
+.embed-responsive-16by9 {
+ padding-bottom: 56.25%;
+}
+.embed-responsive-4by3 {
+ padding-bottom: 75%;
+}
+.well {
+ min-height: 20px;
+ padding: 19px;
+ margin-bottom: 20px;
+ background-color: #f5f5f5;
+ border: 1px solid #e3e3e3;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+}
+.well blockquote {
+ border-color: #ddd;
+ border-color: rgba(0, 0, 0, .15);
+}
+.well-lg {
+ padding: 24px;
+ border-radius: 6px;
+}
+.well-sm {
+ padding: 9px;
+ border-radius: 3px;
+}
+.close {
+ float: right;
+ font-size: 21px;
+ font-weight: bold;
+ line-height: 1;
+ color: #000;
+ text-shadow: 0 1px 0 #fff;
+ filter: alpha(opacity=20);
+ opacity: .2;
+}
+.close:hover,
+.close:focus {
+ color: #000;
+ text-decoration: none;
+ cursor: pointer;
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+button.close {
+ -webkit-appearance: none;
+ padding: 0;
+ cursor: pointer;
+ background: transparent;
+ border: 0;
+}
+.modal-open {
+ overflow: hidden;
+}
+.modal {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1050;
+ display: none;
+ overflow: hidden;
+ -webkit-overflow-scrolling: touch;
+ outline: 0;
+}
+.modal.fade .modal-dialog {
+ -webkit-transition: -webkit-transform .3s ease-out;
+ -o-transition: -o-transform .3s ease-out;
+ transition: transform .3s ease-out;
+ -webkit-transform: translate(0, -25%);
+ -ms-transform: translate(0, -25%);
+ -o-transform: translate(0, -25%);
+ transform: translate(0, -25%);
+}
+.modal.in .modal-dialog {
+ -webkit-transform: translate(0, 0);
+ -ms-transform: translate(0, 0);
+ -o-transform: translate(0, 0);
+ transform: translate(0, 0);
+}
+.modal-open .modal {
+ overflow-x: hidden;
+ overflow-y: auto;
+}
+.modal-dialog {
+ position: relative;
+ width: auto;
+ margin: 10px;
+}
+.modal-content {
+ position: relative;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #999;
+ border: 1px solid rgba(0, 0, 0, .2);
+ border-radius: 6px;
+ outline: 0;
+ -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+ box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+}
+.modal-backdrop {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1040;
+ background-color: #000;
+}
+.modal-backdrop.fade {
+ filter: alpha(opacity=0);
+ opacity: 0;
+}
+.modal-backdrop.in {
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+.modal-header {
+ padding: 15px;
+ border-bottom: 1px solid #e5e5e5;
+}
+.modal-header .close {
+ margin-top: -2px;
+}
+.modal-title {
+ margin: 0;
+ line-height: 1.42857143;
+}
+.modal-body {
+ position: relative;
+ padding: 15px;
+}
+.modal-footer {
+ padding: 15px;
+ text-align: right;
+ border-top: 1px solid #e5e5e5;
+}
+.modal-footer .btn + .btn {
+ margin-bottom: 0;
+ margin-left: 5px;
+}
+.modal-footer .btn-group .btn + .btn {
+ margin-left: -1px;
+}
+.modal-footer .btn-block + .btn-block {
+ margin-left: 0;
+}
+.modal-scrollbar-measure {
+ position: absolute;
+ top: -9999px;
+ width: 50px;
+ height: 50px;
+ overflow: scroll;
+}
+@media (min-width: 768px) {
+ .modal-dialog {
+ width: 600px;
+ margin: 30px auto;
+ }
+ .modal-content {
+ -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+ box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+ }
+ .modal-sm {
+ width: 300px;
+ }
+}
+@media (min-width: 992px) {
+ .modal-lg {
+ width: 900px;
+ }
+}
+.tooltip {
+ position: absolute;
+ z-index: 1070;
+ display: block;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: normal;
+ line-height: 1.42857143;
+ text-align: left;
+ text-align: start;
+ text-decoration: none;
+ text-shadow: none;
+ text-transform: none;
+ letter-spacing: normal;
+ word-break: normal;
+ word-spacing: normal;
+ word-wrap: normal;
+ white-space: normal;
+ filter: alpha(opacity=0);
+ opacity: 0;
+
+ line-break: auto;
+}
+.tooltip.in {
+ filter: alpha(opacity=90);
+ opacity: .9;
+}
+.tooltip.top {
+ padding: 5px 0;
+ margin-top: -3px;
+}
+.tooltip.right {
+ padding: 0 5px;
+ margin-left: 3px;
+}
+.tooltip.bottom {
+ padding: 5px 0;
+ margin-top: 3px;
+}
+.tooltip.left {
+ padding: 0 5px;
+ margin-left: -3px;
+}
+.tooltip-inner {
+ max-width: 200px;
+ padding: 3px 8px;
+ color: #fff;
+ text-align: center;
+ background-color: #000;
+ border-radius: 4px;
+}
+.tooltip-arrow {
+ position: absolute;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+}
+.tooltip.top .tooltip-arrow {
+ bottom: 0;
+ left: 50%;
+ margin-left: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.top-left .tooltip-arrow {
+ right: 5px;
+ bottom: 0;
+ margin-bottom: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.top-right .tooltip-arrow {
+ bottom: 0;
+ left: 5px;
+ margin-bottom: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.right .tooltip-arrow {
+ top: 50%;
+ left: 0;
+ margin-top: -5px;
+ border-width: 5px 5px 5px 0;
+ border-right-color: #000;
+}
+.tooltip.left .tooltip-arrow {
+ top: 50%;
+ right: 0;
+ margin-top: -5px;
+ border-width: 5px 0 5px 5px;
+ border-left-color: #000;
+}
+.tooltip.bottom .tooltip-arrow {
+ top: 0;
+ left: 50%;
+ margin-left: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.tooltip.bottom-left .tooltip-arrow {
+ top: 0;
+ right: 5px;
+ margin-top: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.tooltip.bottom-right .tooltip-arrow {
+ top: 0;
+ left: 5px;
+ margin-top: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.popover {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 1060;
+ display: none;
+ max-width: 276px;
+ padding: 1px;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ font-style: normal;
+ font-weight: normal;
+ line-height: 1.42857143;
+ text-align: left;
+ text-align: start;
+ text-decoration: none;
+ text-shadow: none;
+ text-transform: none;
+ letter-spacing: normal;
+ word-break: normal;
+ word-spacing: normal;
+ word-wrap: normal;
+ white-space: normal;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #ccc;
+ border: 1px solid rgba(0, 0, 0, .2);
+ border-radius: 6px;
+ -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
+ box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
+
+ line-break: auto;
+}
+.popover.top {
+ margin-top: -10px;
+}
+.popover.right {
+ margin-left: 10px;
+}
+.popover.bottom {
+ margin-top: 10px;
+}
+.popover.left {
+ margin-left: -10px;
+}
+.popover-title {
+ padding: 8px 14px;
+ margin: 0;
+ font-size: 14px;
+ background-color: #f7f7f7;
+ border-bottom: 1px solid #ebebeb;
+ border-radius: 5px 5px 0 0;
+}
+.popover-content {
+ padding: 9px 14px;
+}
+.popover > .arrow,
+.popover > .arrow:after {
+ position: absolute;
+ display: block;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+}
+.popover > .arrow {
+ border-width: 11px;
+}
+.popover > .arrow:after {
+ content: "";
+ border-width: 10px;
+}
+.popover.top > .arrow {
+ bottom: -11px;
+ left: 50%;
+ margin-left: -11px;
+ border-top-color: #999;
+ border-top-color: rgba(0, 0, 0, .25);
+ border-bottom-width: 0;
+}
+.popover.top > .arrow:after {
+ bottom: 1px;
+ margin-left: -10px;
+ content: " ";
+ border-top-color: #fff;
+ border-bottom-width: 0;
+}
+.popover.right > .arrow {
+ top: 50%;
+ left: -11px;
+ margin-top: -11px;
+ border-right-color: #999;
+ border-right-color: rgba(0, 0, 0, .25);
+ border-left-width: 0;
+}
+.popover.right > .arrow:after {
+ bottom: -10px;
+ left: 1px;
+ content: " ";
+ border-right-color: #fff;
+ border-left-width: 0;
+}
+.popover.bottom > .arrow {
+ top: -11px;
+ left: 50%;
+ margin-left: -11px;
+ border-top-width: 0;
+ border-bottom-color: #999;
+ border-bottom-color: rgba(0, 0, 0, .25);
+}
+.popover.bottom > .arrow:after {
+ top: 1px;
+ margin-left: -10px;
+ content: " ";
+ border-top-width: 0;
+ border-bottom-color: #fff;
+}
+.popover.left > .arrow {
+ top: 50%;
+ right: -11px;
+ margin-top: -11px;
+ border-right-width: 0;
+ border-left-color: #999;
+ border-left-color: rgba(0, 0, 0, .25);
+}
+.popover.left > .arrow:after {
+ right: 1px;
+ bottom: -10px;
+ content: " ";
+ border-right-width: 0;
+ border-left-color: #fff;
+}
+.carousel {
+ position: relative;
+}
+.carousel-inner {
+ position: relative;
+ width: 100%;
+ overflow: hidden;
+}
+.carousel-inner > .item {
+ position: relative;
+ display: none;
+ -webkit-transition: .6s ease-in-out left;
+ -o-transition: .6s ease-in-out left;
+ transition: .6s ease-in-out left;
+}
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
+ line-height: 1;
+}
+@media all and (transform-3d), (-webkit-transform-3d) {
+ .carousel-inner > .item {
+ -webkit-transition: -webkit-transform .6s ease-in-out;
+ -o-transition: -o-transform .6s ease-in-out;
+ transition: transform .6s ease-in-out;
+
+ -webkit-backface-visibility: hidden;
+ backface-visibility: hidden;
+ -webkit-perspective: 1000px;
+ perspective: 1000px;
+ }
+ .carousel-inner > .item.next,
+ .carousel-inner > .item.active.right {
+ left: 0;
+ -webkit-transform: translate3d(100%, 0, 0);
+ transform: translate3d(100%, 0, 0);
+ }
+ .carousel-inner > .item.prev,
+ .carousel-inner > .item.active.left {
+ left: 0;
+ -webkit-transform: translate3d(-100%, 0, 0);
+ transform: translate3d(-100%, 0, 0);
+ }
+ .carousel-inner > .item.next.left,
+ .carousel-inner > .item.prev.right,
+ .carousel-inner > .item.active {
+ left: 0;
+ -webkit-transform: translate3d(0, 0, 0);
+ transform: translate3d(0, 0, 0);
+ }
+}
+.carousel-inner > .active,
+.carousel-inner > .next,
+.carousel-inner > .prev {
+ display: block;
+}
+.carousel-inner > .active {
+ left: 0;
+}
+.carousel-inner > .next,
+.carousel-inner > .prev {
+ position: absolute;
+ top: 0;
+ width: 100%;
+}
+.carousel-inner > .next {
+ left: 100%;
+}
+.carousel-inner > .prev {
+ left: -100%;
+}
+.carousel-inner > .next.left,
+.carousel-inner > .prev.right {
+ left: 0;
+}
+.carousel-inner > .active.left {
+ left: -100%;
+}
+.carousel-inner > .active.right {
+ left: 100%;
+}
+.carousel-control {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 15%;
+ font-size: 20px;
+ color: #fff;
+ text-align: center;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+ background-color: rgba(0, 0, 0, 0);
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+.carousel-control.left {
+ background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
+ background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
+ background-repeat: repeat-x;
+}
+.carousel-control.right {
+ right: 0;
+ left: auto;
+ background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
+ background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
+ background-repeat: repeat-x;
+}
+.carousel-control:hover,
+.carousel-control:focus {
+ color: #fff;
+ text-decoration: none;
+ filter: alpha(opacity=90);
+ outline: 0;
+ opacity: .9;
+}
+.carousel-control .icon-prev,
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-left,
+.carousel-control .glyphicon-chevron-right {
+ position: absolute;
+ top: 50%;
+ z-index: 5;
+ display: inline-block;
+ margin-top: -10px;
+}
+.carousel-control .icon-prev,
+.carousel-control .glyphicon-chevron-left {
+ left: 50%;
+ margin-left: -10px;
+}
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-right {
+ right: 50%;
+ margin-right: -10px;
+}
+.carousel-control .icon-prev,
+.carousel-control .icon-next {
+ width: 20px;
+ height: 20px;
+ font-family: serif;
+ line-height: 1;
+}
+.carousel-control .icon-prev:before {
+ content: '\2039';
+}
+.carousel-control .icon-next:before {
+ content: '\203a';
+}
+.carousel-indicators {
+ position: absolute;
+ bottom: 10px;
+ left: 50%;
+ z-index: 15;
+ width: 60%;
+ padding-left: 0;
+ margin-left: -30%;
+ text-align: center;
+ list-style: none;
+}
+.carousel-indicators li {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ margin: 1px;
+ text-indent: -999px;
+ cursor: pointer;
+ background-color: #000 \9;
+ background-color: rgba(0, 0, 0, 0);
+ border: 1px solid #fff;
+ border-radius: 10px;
+}
+.carousel-indicators .active {
+ width: 12px;
+ height: 12px;
+ margin: 0;
+ background-color: #fff;
+}
+.carousel-caption {
+ position: absolute;
+ right: 15%;
+ bottom: 20px;
+ left: 15%;
+ z-index: 10;
+ padding-top: 20px;
+ padding-bottom: 20px;
+ color: #fff;
+ text-align: center;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+}
+.carousel-caption .btn {
+ text-shadow: none;
+}
+@media screen and (min-width: 768px) {
+ .carousel-control .glyphicon-chevron-left,
+ .carousel-control .glyphicon-chevron-right,
+ .carousel-control .icon-prev,
+ .carousel-control .icon-next {
+ width: 30px;
+ height: 30px;
+ margin-top: -10px;
+ font-size: 30px;
+ }
+ .carousel-control .glyphicon-chevron-left,
+ .carousel-control .icon-prev {
+ margin-left: -10px;
+ }
+ .carousel-control .glyphicon-chevron-right,
+ .carousel-control .icon-next {
+ margin-right: -10px;
+ }
+ .carousel-caption {
+ right: 20%;
+ left: 20%;
+ padding-bottom: 30px;
+ }
+ .carousel-indicators {
+ bottom: 20px;
+ }
+}
+.clearfix:before,
+.clearfix:after,
+.dl-horizontal dd:before,
+.dl-horizontal dd:after,
+.container:before,
+.container:after,
+.container-fluid:before,
+.container-fluid:after,
+.row:before,
+.row:after,
+.form-horizontal .form-group:before,
+.form-horizontal .form-group:after,
+.btn-toolbar:before,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:before,
+.btn-group-vertical > .btn-group:after,
+.nav:before,
+.nav:after,
+.navbar:before,
+.navbar:after,
+.navbar-header:before,
+.navbar-header:after,
+.navbar-collapse:before,
+.navbar-collapse:after,
+.pager:before,
+.pager:after,
+.panel-body:before,
+.panel-body:after,
+.modal-header:before,
+.modal-header:after,
+.modal-footer:before,
+.modal-footer:after {
+ display: table;
+ content: " ";
+}
+.clearfix:after,
+.dl-horizontal dd:after,
+.container:after,
+.container-fluid:after,
+.row:after,
+.form-horizontal .form-group:after,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:after,
+.nav:after,
+.navbar:after,
+.navbar-header:after,
+.navbar-collapse:after,
+.pager:after,
+.panel-body:after,
+.modal-header:after,
+.modal-footer:after {
+ clear: both;
+}
+.center-block {
+ display: block;
+ margin-right: auto;
+ margin-left: auto;
+}
+.pull-right {
+ float: right !important;
+}
+.pull-left {
+ float: left !important;
+}
+.hide {
+ display: none !important;
+}
+.show {
+ display: block !important;
+}
+.invisible {
+ visibility: hidden;
+}
+.text-hide {
+ font: 0/0 a;
+ color: transparent;
+ text-shadow: none;
+ background-color: transparent;
+ border: 0;
+}
+.hidden {
+ display: none !important;
+}
+.affix {
+ position: fixed;
+}
+@-ms-viewport {
+ width: device-width;
+}
+.visible-xs,
+.visible-sm,
+.visible-md,
+.visible-lg {
+ display: none !important;
+}
+.visible-xs-block,
+.visible-xs-inline,
+.visible-xs-inline-block,
+.visible-sm-block,
+.visible-sm-inline,
+.visible-sm-inline-block,
+.visible-md-block,
+.visible-md-inline,
+.visible-md-inline-block,
+.visible-lg-block,
+.visible-lg-inline,
+.visible-lg-inline-block {
+ display: none !important;
+}
+@media (max-width: 767px) {
+ .visible-xs {
+ display: block !important;
+ }
+ table.visible-xs {
+ display: table !important;
+ }
+ tr.visible-xs {
+ display: table-row !important;
+ }
+ th.visible-xs,
+ td.visible-xs {
+ display: table-cell !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-block {
+ display: block !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-inline {
+ display: inline !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm {
+ display: block !important;
+ }
+ table.visible-sm {
+ display: table !important;
+ }
+ tr.visible-sm {
+ display: table-row !important;
+ }
+ th.visible-sm,
+ td.visible-sm {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-block {
+ display: block !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md {
+ display: block !important;
+ }
+ table.visible-md {
+ display: table !important;
+ }
+ tr.visible-md {
+ display: table-row !important;
+ }
+ th.visible-md,
+ td.visible-md {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-block {
+ display: block !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg {
+ display: block !important;
+ }
+ table.visible-lg {
+ display: table !important;
+ }
+ tr.visible-lg {
+ display: table-row !important;
+ }
+ th.visible-lg,
+ td.visible-lg {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-block {
+ display: block !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (max-width: 767px) {
+ .hidden-xs {
+ display: none !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .hidden-sm {
+ display: none !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .hidden-md {
+ display: none !important;
+ }
+}
+@media (min-width: 1200px) {
+ .hidden-lg {
+ display: none !important;
+ }
+}
+.visible-print {
+ display: none !important;
+}
+@media print {
+ .visible-print {
+ display: block !important;
+ }
+ table.visible-print {
+ display: table !important;
+ }
+ tr.visible-print {
+ display: table-row !important;
+ }
+ th.visible-print,
+ td.visible-print {
+ display: table-cell !important;
+ }
+}
+.visible-print-block {
+ display: none !important;
+}
+@media print {
+ .visible-print-block {
+ display: block !important;
+ }
+}
+.visible-print-inline {
+ display: none !important;
+}
+@media print {
+ .visible-print-inline {
+ display: inline !important;
+ }
+}
+.visible-print-inline-block {
+ display: none !important;
+}
+@media print {
+ .visible-print-inline-block {
+ display: inline-block !important;
+ }
+}
+@media print {
+ .hidden-print {
+ display: none !important;
+ }
+}
+/*# sourceMappingURL=bootstrap.css.map */
+
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables-dark.css b/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables-dark.css
new file mode 100644
index 0000000..98ded91
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables-dark.css
@@ -0,0 +1,461 @@
+/*
+ * Table styles
+ */
+table.dataTable {
+ width: 100%;
+ margin: 0 auto;
+ clear: both;
+ border-collapse: separate;
+ border-spacing: 0;
+ /*
+ * Header and footer styles
+ */
+ /*
+ * Body styles
+ */
+}
+
+
+table.dataTable thead th,
+table.dataTable tfoot th {
+ font-weight: bold;
+}
+table.dataTable thead th,
+table.dataTable thead td {
+ padding: 10px 18px;
+ border-bottom: 1px solid #dddddd;
+}
+table.dataTable thead th:active,
+table.dataTable thead td:active {
+ outline: none;
+}
+table.dataTable tfoot th,
+table.dataTable tfoot td {
+ padding: 10px 18px 6px 18px;
+ border-top: 1px solid #dddddd;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc,
+table.dataTable thead .sorting_asc_disabled,
+table.dataTable thead .sorting_desc_disabled {
+ cursor: pointer;
+ *cursor: hand;
+ background-repeat: no-repeat;
+ background-position: center right;
+}
+table.dataTable thead .sorting {
+ background-image: url("../images/sort_both.png");
+}
+table.dataTable thead .sorting_asc {
+ background-image: url("../images/sort_asc.png") !important;
+}
+table.dataTable thead .sorting_desc {
+ background-image: url("../images/sort_desc.png") !important;
+}
+table.dataTable thead .sorting_asc_disabled {
+ background-image: url("../images/sort_asc_disabled.png");
+}
+table.dataTable thead .sorting_desc_disabled {
+ background-image: url("../images/sort_desc_disabled.png");
+}
+table.dataTable tbody tr {
+ background-color: #333333;
+}
+table.dataTable tbody tr.selected {
+ background-color: #666666;
+}
+table.dataTable tbody th,
+table.dataTable tbody td {
+ padding: 8px 10px;
+}
+table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
+ border-top: 1px solid #111111;
+}
+table.dataTable.row-border tbody tr:first-child th,
+table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
+table.dataTable.display tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
+ border-top: 1px solid #111111;
+ border-right: 1px solid #111111;
+}
+table.dataTable.cell-border tbody tr th:first-child,
+table.dataTable.cell-border tbody tr td:first-child {
+ border-left: 1px solid #111111;
+}
+table.dataTable.cell-border tbody tr:first-child th,
+table.dataTable.cell-border tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
+ background-color: #323232;
+}
+table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
+ background-color: #646464;
+}
+table.dataTable.hover tbody tr:hover, table.dataTable.display tbody tr:hover {
+ background-color: #313131;
+}
+table.dataTable.hover tbody tr:hover.selected, table.dataTable.display tbody tr:hover.selected {
+ background-color: #626262;
+}
+table.dataTable.order-column tbody tr > .sorting_1,
+table.dataTable.order-column tbody tr > .sorting_2,
+table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
+table.dataTable.display tbody tr > .sorting_2,
+table.dataTable.display tbody tr > .sorting_3 {
+ background-color: #323232;
+}
+table.dataTable.order-column tbody tr.selected > .sorting_1,
+table.dataTable.order-column tbody tr.selected > .sorting_2,
+table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
+table.dataTable.display tbody tr.selected > .sorting_2,
+table.dataTable.display tbody tr.selected > .sorting_3 {
+ background-color: #646464;
+}
+table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
+ background-color: #303030;
+}
+table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
+ background-color: #313131;
+}
+table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
+ background-color: #313131;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
+ background-color: #606060;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
+ background-color: #616161;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
+ background-color: #626262;
+}
+table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
+ background-color: #323232;
+}
+table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
+ background-color: #323232;
+}
+table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
+ background-color: #333333;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
+ background-color: #646464;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
+ background-color: #656565;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
+ background-color: #666666;
+}
+table.dataTable.display tbody tr:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1 {
+ background-color: #2f2f2f;
+}
+table.dataTable.display tbody tr:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2 {
+ background-color: #2f2f2f;
+}
+table.dataTable.display tbody tr:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3 {
+ background-color: #303030;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1 {
+ background-color: #5e5e5e;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2 {
+ background-color: #5e5e5e;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3 {
+ background-color: #606060;
+}
+table.dataTable.no-footer {
+ border-bottom: 1px solid #dddddd;
+}
+table.dataTable.nowrap th, table.dataTable.nowrap td {
+ white-space: nowrap;
+}
+table.dataTable.compact thead th,
+table.dataTable.compact thead td {
+ padding: 4px 17px;
+}
+table.dataTable.compact tfoot th,
+table.dataTable.compact tfoot td {
+ padding: 4px;
+}
+table.dataTable.compact tbody th,
+table.dataTable.compact tbody td {
+ padding: 4px;
+}
+table.dataTable th.dt-left,
+table.dataTable td.dt-left {
+ text-align: left;
+}
+table.dataTable th.dt-center,
+table.dataTable td.dt-center,
+table.dataTable td.dataTables_empty {
+ text-align: center;
+}
+table.dataTable th.dt-right,
+table.dataTable td.dt-right {
+ text-align: right;
+}
+table.dataTable th.dt-justify,
+table.dataTable td.dt-justify {
+ text-align: justify;
+}
+table.dataTable th.dt-nowrap,
+table.dataTable td.dt-nowrap {
+ white-space: nowrap;
+}
+table.dataTable thead th.dt-head-left,
+table.dataTable thead td.dt-head-left,
+table.dataTable tfoot th.dt-head-left,
+table.dataTable tfoot td.dt-head-left {
+ text-align: left;
+}
+table.dataTable thead th.dt-head-center,
+table.dataTable thead td.dt-head-center,
+table.dataTable tfoot th.dt-head-center,
+table.dataTable tfoot td.dt-head-center {
+ text-align: center;
+}
+table.dataTable thead th.dt-head-right,
+table.dataTable thead td.dt-head-right,
+table.dataTable tfoot th.dt-head-right,
+table.dataTable tfoot td.dt-head-right {
+ text-align: right;
+}
+table.dataTable thead th.dt-head-justify,
+table.dataTable thead td.dt-head-justify,
+table.dataTable tfoot th.dt-head-justify,
+table.dataTable tfoot td.dt-head-justify {
+ text-align: justify;
+}
+table.dataTable thead th.dt-head-nowrap,
+table.dataTable thead td.dt-head-nowrap,
+table.dataTable tfoot th.dt-head-nowrap,
+table.dataTable tfoot td.dt-head-nowrap {
+ white-space: nowrap;
+}
+table.dataTable tbody th.dt-body-left,
+table.dataTable tbody td.dt-body-left {
+ text-align: left;
+}
+table.dataTable tbody th.dt-body-center,
+table.dataTable tbody td.dt-body-center {
+ text-align: center;
+}
+table.dataTable tbody th.dt-body-right,
+table.dataTable tbody td.dt-body-right {
+ text-align: right;
+}
+table.dataTable tbody th.dt-body-justify,
+table.dataTable tbody td.dt-body-justify {
+ text-align: justify;
+}
+table.dataTable tbody th.dt-body-nowrap,
+table.dataTable tbody td.dt-body-nowrap {
+ white-space: nowrap;
+}
+
+table.dataTable,
+table.dataTable th,
+table.dataTable td {
+ box-sizing: content-box;
+}
+
+/*
+ * Control feature layout
+ */
+.dataTables_wrapper {
+ position: relative;
+ clear: both;
+ *zoom: 1;
+ zoom: 1;
+}
+.dataTables_wrapper .dataTables_length {
+ float: left;
+}
+.dataTables_wrapper .dataTables_length select {
+ border: 1px solid #aaa;
+ border-radius: 3px;
+ padding: 5px;
+ background-color: transparent;
+ padding: 4px;
+}
+.dataTables_wrapper .dataTables_filter {
+ float: right;
+ text-align: right;
+}
+.dataTables_wrapper .dataTables_filter input {
+ border: 1px solid #aaa;
+ border-radius: 3px;
+ padding: 5px;
+ background-color: transparent;
+ margin-left: 3px;
+}
+.dataTables_wrapper .dataTables_info {
+ clear: both;
+ float: left;
+ padding-top: 0.755em;
+}
+.dataTables_wrapper .dataTables_paginate {
+ float: right;
+ text-align: right;
+ padding-top: 0.25em;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button {
+ box-sizing: border-box;
+ display: inline-block;
+ min-width: 1.5em;
+ padding: 0.5em 1em;
+ margin-left: 2px;
+ text-align: center;
+ text-decoration: none !important;
+ cursor: pointer;
+ *cursor: hand;
+ color: #aaaaaa !important;
+ border: 1px solid transparent;
+ border-radius: 2px;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
+ color: #aaaaaa !important;
+ border: 1px solid #979797;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, #dcdcdc));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, white 0%, #dcdcdc 100%);
+ /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
+ cursor: default;
+ color: #666 !important;
+ border: 1px solid transparent;
+ background: transparent;
+ box-shadow: none;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
+ color: white !important;
+ border: 1px solid #375a7f;
+ background-color: #7ea1c7;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #7ea1c7), color-stop(100%, #375a7f));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #7ea1c7 0%, #375a7f 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #7ea1c7 0%, #375a7f 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #7ea1c7 0%, #375a7f 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #7ea1c7 0%, #375a7f 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #7ea1c7 0%, #375a7f 100%);
+ /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:active {
+ outline: none;
+ background-color: #4673a3;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #4673a3), color-stop(100%, #345578));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #4673a3 0%, #345578 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #4673a3 0%, #345578 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #4673a3 0%, #345578 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #4673a3 0%, #345578 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #4673a3 0%, #345578 100%);
+ /* W3C */
+ box-shadow: inset 0 0 3px #111;
+}
+.dataTables_wrapper .dataTables_paginate .ellipsis {
+ padding: 0 1em;
+}
+.dataTables_wrapper .dataTables_processing {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 100%;
+ height: 90px;
+ margin-left: -50%;
+ margin-top: -25px;
+ padding-top: 20px;
+ text-align: center;
+ font-size: 2.0em;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(51, 51, 51, 0)), color-stop(25%, rgba(51, 51, 51, 0.9)), color-stop(75%, rgba(51, 51, 51, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
+ background: -webkit-linear-gradient(left, rgba(51, 51, 51, 0) 0%, rgba(51, 51, 51, 0.9) 25%, rgba(51, 51, 51, 0.9) 75%, rgba(51, 51, 51, 0) 100%);
+ background: -moz-linear-gradient(left, rgba(51, 51, 51, 0) 0%, rgba(51, 51, 51, 0.9) 25%, rgba(51, 51, 51, 0.9) 75%, rgba(51, 51, 51, 0) 100%);
+ background: -ms-linear-gradient(left, rgba(51, 51, 51, 0) 0%, rgba(51, 51, 51, 0.9) 25%, rgba(51, 51, 51, 0.9) 75%, rgba(51, 51, 51, 0) 100%);
+ background: -o-linear-gradient(left, rgba(51, 51, 51, 0) 0%, rgba(51, 51, 51, 0.9) 25%, rgba(51, 51, 51, 0.9) 75%, rgba(51, 51, 51, 0) 100%);
+ background: linear-gradient(to right, rgba(51, 51, 51, 0) 0%, rgba(51, 51, 51, 0.9) 25%, rgba(51, 51, 51, 0.9) 75%, rgba(51, 51, 51, 0) 100%);
+}
+.dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter,
+.dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_processing,
+.dataTables_wrapper .dataTables_paginate {
+ color: #aaaaaa;
+}
+.dataTables_wrapper .dataTables_scroll {
+ clear: both;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
+ *margin-top: -1px;
+ -webkit-overflow-scrolling: touch;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > td, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > td {
+ vertical-align: middle;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > th > div.dataTables_sizing,
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > thead > tr > td > div.dataTables_sizing, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > th > div.dataTables_sizing,
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody > table > tbody > tr > td > div.dataTables_sizing {
+ height: 0;
+ overflow: hidden;
+ margin: 0 !important;
+ padding: 0 !important;
+}
+.dataTables_wrapper.no-footer .dataTables_scrollBody {
+ border-bottom: 1px solid #dddddd;
+}
+.dataTables_wrapper.no-footer div.dataTables_scrollHead table.dataTable,
+.dataTables_wrapper.no-footer div.dataTables_scrollBody > table {
+ border-bottom: none;
+}
+.dataTables_wrapper:after {
+ visibility: hidden;
+ display: block;
+ content: "";
+ clear: both;
+ height: 0;
+}
+
+@media screen and (max-width: 767px) {
+ .dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_paginate {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_paginate {
+ margin-top: 0.5em;
+ }
+}
+@media screen and (max-width: 640px) {
+ .dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_filter {
+ margin-top: 0.5em;
+ }
+} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables.css b/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables.css
new file mode 100644
index 0000000..91cc0b5
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/datatables/jquery.dataTables.css
@@ -0,0 +1,453 @@
+/*
+ * Table styles
+ */
+table.dataTable {
+ width: 100%;
+ margin: 0 auto;
+ clear: both;
+ border-collapse: separate;
+ border-spacing: 0;
+ /*
+ * Header and footer styles
+ */
+ /*
+ * Body styles
+ */
+}
+table.dataTable thead th,
+table.dataTable tfoot th {
+ font-weight: bold;
+}
+table.dataTable thead th,
+table.dataTable thead td {
+ padding: 10px 18px;
+ border-bottom: 1px solid #111;
+}
+table.dataTable thead th:active,
+table.dataTable thead td:active {
+ outline: none;
+}
+table.dataTable tfoot th,
+table.dataTable tfoot td {
+ padding: 10px 18px 6px 18px;
+ border-top: 1px solid #111;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc {
+ cursor: pointer;
+ *cursor: hand;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc,
+table.dataTable thead .sorting_asc_disabled,
+table.dataTable thead .sorting_desc_disabled {
+ background-repeat: no-repeat;
+ background-position: center right;
+}
+table.dataTable thead .sorting {
+ background-image: url("../images/sort_both.png");
+}
+table.dataTable thead .sorting_asc {
+ background-image: url("../images/sort_asc.png");
+}
+table.dataTable thead .sorting_desc {
+ background-image: url("../images/sort_desc.png");
+}
+table.dataTable thead .sorting_asc_disabled {
+ background-image: url("../images/sort_asc_disabled.png");
+}
+table.dataTable thead .sorting_desc_disabled {
+ background-image: url("../images/sort_desc_disabled.png");
+}
+table.dataTable tbody tr {
+ background-color: #ffffff;
+}
+table.dataTable tbody tr.selected {
+ background-color: #B0BED9;
+}
+table.dataTable tbody th,
+table.dataTable tbody td {
+ padding: 8px 10px;
+}
+table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
+ border-top: 1px solid #ddd;
+}
+table.dataTable.row-border tbody tr:first-child th,
+table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
+table.dataTable.display tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
+ border-top: 1px solid #ddd;
+ border-right: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr th:first-child,
+table.dataTable.cell-border tbody tr td:first-child {
+ border-left: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr:first-child th,
+table.dataTable.cell-border tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
+ background-color: #f9f9f9;
+}
+table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
+ background-color: #acbad4;
+}
+table.dataTable.hover tbody tr:hover, table.dataTable.display tbody tr:hover {
+ background-color: #f6f6f6;
+}
+table.dataTable.hover tbody tr:hover.selected, table.dataTable.display tbody tr:hover.selected {
+ background-color: #aab7d1;
+}
+table.dataTable.order-column tbody tr > .sorting_1,
+table.dataTable.order-column tbody tr > .sorting_2,
+table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
+table.dataTable.display tbody tr > .sorting_2,
+table.dataTable.display tbody tr > .sorting_3 {
+ background-color: #fafafa;
+}
+table.dataTable.order-column tbody tr.selected > .sorting_1,
+table.dataTable.order-column tbody tr.selected > .sorting_2,
+table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
+table.dataTable.display tbody tr.selected > .sorting_2,
+table.dataTable.display tbody tr.selected > .sorting_3 {
+ background-color: #acbad5;
+}
+table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
+ background-color: #f1f1f1;
+}
+table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
+ background-color: #f3f3f3;
+}
+table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
+ background-color: whitesmoke;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
+ background-color: #a6b4cd;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
+ background-color: #a8b5cf;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
+ background-color: #a9b7d1;
+}
+table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
+ background-color: #fafafa;
+}
+table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
+ background-color: #fcfcfc;
+}
+table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
+ background-color: #fefefe;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
+ background-color: #acbad5;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
+ background-color: #aebcd6;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
+ background-color: #afbdd8;
+}
+table.dataTable.display tbody tr:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1 {
+ background-color: #eaeaea;
+}
+table.dataTable.display tbody tr:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2 {
+ background-color: #ececec;
+}
+table.dataTable.display tbody tr:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3 {
+ background-color: #efefef;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1 {
+ background-color: #a2aec7;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2 {
+ background-color: #a3b0c9;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3 {
+ background-color: #a5b2cb;
+}
+table.dataTable.no-footer {
+ border-bottom: 1px solid #111;
+}
+table.dataTable.nowrap th, table.dataTable.nowrap td {
+ white-space: nowrap;
+}
+table.dataTable.compact thead th,
+table.dataTable.compact thead td {
+ padding: 4px 17px 4px 4px;
+}
+table.dataTable.compact tfoot th,
+table.dataTable.compact tfoot td {
+ padding: 4px;
+}
+table.dataTable.compact tbody th,
+table.dataTable.compact tbody td {
+ padding: 4px;
+}
+table.dataTable th.dt-left,
+table.dataTable td.dt-left {
+ text-align: left;
+}
+table.dataTable th.dt-center,
+table.dataTable td.dt-center,
+table.dataTable td.dataTables_empty {
+ text-align: center;
+}
+table.dataTable th.dt-right,
+table.dataTable td.dt-right {
+ text-align: right;
+}
+table.dataTable th.dt-justify,
+table.dataTable td.dt-justify {
+ text-align: justify;
+}
+table.dataTable th.dt-nowrap,
+table.dataTable td.dt-nowrap {
+ white-space: nowrap;
+}
+table.dataTable thead th.dt-head-left,
+table.dataTable thead td.dt-head-left,
+table.dataTable tfoot th.dt-head-left,
+table.dataTable tfoot td.dt-head-left {
+ text-align: left;
+}
+table.dataTable thead th.dt-head-center,
+table.dataTable thead td.dt-head-center,
+table.dataTable tfoot th.dt-head-center,
+table.dataTable tfoot td.dt-head-center {
+ text-align: center;
+}
+table.dataTable thead th.dt-head-right,
+table.dataTable thead td.dt-head-right,
+table.dataTable tfoot th.dt-head-right,
+table.dataTable tfoot td.dt-head-right {
+ text-align: right;
+}
+table.dataTable thead th.dt-head-justify,
+table.dataTable thead td.dt-head-justify,
+table.dataTable tfoot th.dt-head-justify,
+table.dataTable tfoot td.dt-head-justify {
+ text-align: justify;
+}
+table.dataTable thead th.dt-head-nowrap,
+table.dataTable thead td.dt-head-nowrap,
+table.dataTable tfoot th.dt-head-nowrap,
+table.dataTable tfoot td.dt-head-nowrap {
+ white-space: nowrap;
+}
+table.dataTable tbody th.dt-body-left,
+table.dataTable tbody td.dt-body-left {
+ text-align: left;
+}
+table.dataTable tbody th.dt-body-center,
+table.dataTable tbody td.dt-body-center {
+ text-align: center;
+}
+table.dataTable tbody th.dt-body-right,
+table.dataTable tbody td.dt-body-right {
+ text-align: right;
+}
+table.dataTable tbody th.dt-body-justify,
+table.dataTable tbody td.dt-body-justify {
+ text-align: justify;
+}
+table.dataTable tbody th.dt-body-nowrap,
+table.dataTable tbody td.dt-body-nowrap {
+ white-space: nowrap;
+}
+
+table.dataTable,
+table.dataTable th,
+table.dataTable td {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+
+/*
+ * Control feature layout
+ */
+.dataTables_wrapper {
+ position: relative;
+ clear: both;
+ *zoom: 1;
+ zoom: 1;
+}
+.dataTables_wrapper .dataTables_length {
+ float: left;
+}
+.dataTables_wrapper .dataTables_filter {
+ float: right;
+ text-align: right;
+}
+.dataTables_wrapper .dataTables_filter input {
+ margin-left: 0.5em;
+}
+.dataTables_wrapper .dataTables_info {
+ clear: both;
+ float: left;
+ padding-top: 0.755em;
+}
+.dataTables_wrapper .dataTables_paginate {
+ float: right;
+ text-align: right;
+ padding-top: 0.25em;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button {
+ box-sizing: border-box;
+ display: inline-block;
+ min-width: 1.5em;
+ padding: 0.5em 1em;
+ margin-left: 2px;
+ text-align: center;
+ text-decoration: none !important;
+ cursor: pointer;
+ *cursor: hand;
+ color: #333 !important;
+ border: 1px solid transparent;
+ border-radius: 2px;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
+ color: #333 !important;
+ border: 1px solid #979797;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, #dcdcdc));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, white 0%, #dcdcdc 100%);
+ /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
+ cursor: default;
+ color: #666 !important;
+ border: 1px solid transparent;
+ background: transparent;
+ box-shadow: none;
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
+ color: white !important;
+ border: 1px solid #111;
+ background-color: #585858;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #585858 0%, #111 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #585858 0%, #111 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #585858 0%, #111 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #585858 0%, #111 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #585858 0%, #111 100%);
+ /* W3C */
+}
+.dataTables_wrapper .dataTables_paginate .paginate_button:active {
+ outline: none;
+ background-color: #2b2b2b;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);
+ /* W3C */
+ box-shadow: inset 0 0 3px #111;
+}
+.dataTables_wrapper .dataTables_paginate .ellipsis {
+ padding: 0 1em;
+}
+.dataTables_wrapper .dataTables_processing {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 100%;
+ height: 40px;
+ margin-left: -50%;
+ margin-top: -25px;
+ padding-top: 20px;
+ text-align: center;
+ font-size: 1.2em;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
+ background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+}
+.dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter,
+.dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_processing,
+.dataTables_wrapper .dataTables_paginate {
+ color: #333;
+}
+.dataTables_wrapper .dataTables_scroll {
+ clear: both;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
+ *margin-top: -1px;
+ -webkit-overflow-scrolling: touch;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th, .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td {
+ vertical-align: middle;
+}
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th > div.dataTables_sizing,
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td > div.dataTables_sizing {
+ height: 0;
+ overflow: hidden;
+ margin: 0 !important;
+ padding: 0 !important;
+}
+.dataTables_wrapper.no-footer .dataTables_scrollBody {
+ border-bottom: 1px solid #111;
+}
+.dataTables_wrapper.no-footer div.dataTables_scrollHead table,
+.dataTables_wrapper.no-footer div.dataTables_scrollBody table {
+ border-bottom: none;
+}
+.dataTables_wrapper:after {
+ visibility: hidden;
+ display: block;
+ content: "";
+ clear: both;
+ height: 0;
+}
+
+@media screen and (max-width: 767px) {
+ .dataTables_wrapper .dataTables_info,
+ .dataTables_wrapper .dataTables_paginate {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_paginate {
+ margin-top: 0.5em;
+ }
+}
+@media screen and (max-width: 640px) {
+ .dataTables_wrapper .dataTables_length,
+ .dataTables_wrapper .dataTables_filter {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_filter {
+ margin-top: 0.5em;
+ }
+} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc.png b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc.png
new file mode 100644
index 0000000..e1ba61a
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc_disabled.png b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc_disabled.png
new file mode 100644
index 0000000..fb11dfe
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_asc_disabled.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_both.png b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_both.png
new file mode 100644
index 0000000..af5bc7c
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_both.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc.png b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc.png
new file mode 100644
index 0000000..0e156de
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc_disabled.png b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc_disabled.png
new file mode 100644
index 0000000..c9fdd8a
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/images/sort_desc_disabled.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/css/op25.css b/op25/gr-op25_repeater/apps/oplog/op25/static/css/op25.css
new file mode 100644
index 0000000..48bbb28
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/css/op25.css
@@ -0,0 +1,237 @@
+body {
+/* min-height: 2000px; */
+/* padding: 0px 25px 0px 25px; */
+ margin: 5px 10px 5px 10px !important;
+/* background-color: #0f0; */
+}
+
+.li-text {
+ padding: 10px 15px 5px 15px;
+ color: #ddd;
+}
+
+.sel-date {
+ color: black;
+ width: 150px;
+ height: 33px;
+}
+
+/* Clear floats after the columns */
+.row:after {
+ content: "";
+ display: table;
+ clear: both;
+}
+ */
+
+/*
+#container {
+ width: 1000px;
+ min-height: 2000px;
+ margin: 0 auto;
+ border: 1px solid;
+ background-color: #f00; }
+
+#primary {
+ min-height: 2000px; float: left;
+ width: 15%;
+ padding: 5px;
+ background-color: #222;}
+
+#content {
+ min-height: 2000px; float: left;
+ width: 70%;
+ padding: 5px;
+ background-color: #fff; }
+
+#secondary {
+ min-height: 2000px; float: left;
+ width: 15%;
+ padding: 5px;
+ background-color: #eee;}
+ */
+
+#footer {
+ clear: both;
+ background-color: #375a7f;
+ min-height: 50px;
+ color: white;
+}
+
+.btnMain {
+ margin: 2px;
+ padding: 2px;
+ width: 210px;
+}
+
+.dataTables_length select {
+ color: #fff;
+}
+
+.dataTables_length select option {
+ background-color: #111;
+}
+
+.dataTables_filter input[type=search] {
+ color: #fff;
+}
+
+#systemSelect {
+ color: #000;
+ height: 33px;
+}
+
+#navSelect {
+ color: #000;
+ height: 30px;
+}
+
+.op-input {
+ display: inline-block;
+ font-weight: 400;
+ line-height: 1.5;
+ color: #fff;
+ text-align: center;
+ text-decoration: none;
+ vertical-align: middle;
+ cursor: pointer;
+ background-color: transparent;
+ border: 1px solid transparent;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ border-radius: 0.25rem;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+/*
+
+The Modal (background).modal {
+ display: none; Hidden by default position: fixed; Stay in place z-index: 1; Sit on top left: 0;
+ top: 0;
+ width: 100%; Full width height: 100%; Full height overflow: auto; Enable scroll if needed background-color: rgb(0,0,0); Fallback color background-color: rgba(0,0,0,0.4); Black w/ opacity}
+
+Modal Content/Box.modal-content {
+ background-color: #fefefe;
+ margin: 15% auto; 15% from the top and centered padding: 20px;
+ border: 1px solid #888;
+ width: 80%; Could be more or less, depending on screen size}
+
+The Close Button.close {
+ color: #aaa;
+ float: right;
+ font-size: 28px;
+ font-weight: bold;
+}
+
+.close:hover,
+.close:focus {
+ color: black;
+ text-decoration: none;
+ cursor: pointer;
+}
+ */
+
+#loading {
+ position: fixed;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ left: 0;
+ opacity: 0.5;
+ background-color: #fff;
+ z-index: 99;
+}
+
+#loading-image {
+ z-index: 100;
+}
+
+
+/* New layout stuff */
+
+/* Style the body */
+/*
+body {
+ font-family: Arial;
+ margin: 0;
+}
+ */
+
+/* Header/logo Title */
+/*
+.header {
+ padding: 60px;
+ text-align: center;
+ background: #1abc9c;
+ color: white;
+}
+
+Style the top navigation bar.navbar {
+ display: flex;
+ background-color: #333;
+}
+
+Style the navigation bar links.navbar a {
+ color: white;
+ padding: 14px 20px;
+ text-decoration: none;
+ text-align: center;
+}
+
+Change color on hover.navbar a:hover {
+ background-color: #ddd;
+ color: black;
+}
+ */
+
+/* Column container */
+.row-main {
+ display: flex;
+ flex-wrap: wrap;
+}
+
+/* Sidebar/left column */
+.side {
+ flex: 15%;
+/* flex: 0 0 275px; */
+/* width: 200px; */
+/* background-color: #111; */
+ padding: 0px;
+}
+
+/* Main column */
+.main {
+ flex: 70%;
+/* background-color: white; */
+ padding: 5px;
+}
+
+
+
+/* Footer */
+.footer {
+/* padding: 20px; */
+ text-align: center;
+/* background: #ddd; */
+}
+
+/* Responsive layout - when the screen is less than 700px wide, make the two columns stack on top of each other instead of next to each other */
+@media screen and (max-width: 790px) {
+ .row, .navbar {
+ flex-direction: column;
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/dtpick2.js b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/dtpick2.js
new file mode 100644
index 0000000..cb4da12
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/dtpick2.js
@@ -0,0 +1,2930 @@
+/*!
+ * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2016
+ * @version 1.3.4
+ *
+ * Date formatter utility library that allows formatting date/time variables or Date objects using PHP DateTime format.
+ * @see http://php.net/manual/en/function.date.php
+ *
+ * For more JQuery plugins visit http://plugins.krajee.com
+ * For more Yii related demos visit http://demos.krajee.com
+ */var DateFormatter;!function(){"use strict";var t,e,r,n,a,u,i;u=864e5,i=3600,t=function(t,e){return"string"==typeof t&&"string"==typeof e&&t.toLowerCase()===e.toLowerCase()},e=function(t,r,n){var a=n||"0",u=t.toString();return u.length<r?e(a+u,r):u},r=function(t){var e,n;for(t=t||{},e=1;e<arguments.length;e++)if(n=arguments[e])for(var a in n)n.hasOwnProperty(a)&&("object"==typeof n[a]?r(t[a],n[a]):t[a]=n[a]);return t},n=function(t,e){for(var r=0;r<e.length;r++)if(e[r].toLowerCase()===t.toLowerCase())return r;return-1},a={dateSettings:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],meridiem:["AM","PM"],ordinal:function(t){var e=t%10,r={1:"st",2:"nd",3:"rd"};return 1!==Math.floor(t%100/10)&&r[e]?r[e]:"th"}},separators:/[ \-+\/\.T:@]/g,validParts:/[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g,intParts:/[djwNzmnyYhHgGis]/g,tzParts:/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,tzClip:/[^-+\dA-Z]/g},DateFormatter=function(t){var e=this,n=r(a,t);e.dateSettings=n.dateSettings,e.separators=n.separators,e.validParts=n.validParts,e.intParts=n.intParts,e.tzParts=n.tzParts,e.tzClip=n.tzClip},DateFormatter.prototype={constructor:DateFormatter,getMonth:function(t){var e,r=this;return e=n(t,r.dateSettings.monthsShort)+1,0===e&&(e=n(t,r.dateSettings.months)+1),e},parseDate:function(e,r){var n,a,u,i,s,o,c,f,l,h,d=this,g=!1,m=!1,p=d.dateSettings,y={date:null,year:null,month:null,day:null,hour:0,min:0,sec:0};if(!e)return null;if(e instanceof Date)return e;if("U"===r)return u=parseInt(e),u?new Date(1e3*u):e;switch(typeof e){case"number":return new Date(e);case"string":break;default:return null}if(n=r.match(d.validParts),!n||0===n.length)throw new Error("Invalid date format definition.");for(a=e.replace(d.separators,"\x00").split("\x00"),u=0;u<a.length;u++)switch(i=a[u],s=parseInt(i),n[u]){case"y":case"Y":if(!s)return null;l=i.length,y.year=2===l?parseInt((70>s?"20":"19")+i):s,g=!0;break;case"m":case"n":case"M":case"F":if(isNaN(s)){if(o=d.getMonth(i),!(o>0))return null;y.month=o}else{if(!(s>=1&&12>=s))return null;y.month=s}g=!0;break;case"d":case"j":if(!(s>=1&&31>=s))return null;y.day=s,g=!0;break;case"g":case"h":if(c=n.indexOf("a")>-1?n.indexOf("a"):n.indexOf("A")>-1?n.indexOf("A"):-1,h=a[c],c>-1)f=t(h,p.meridiem[0])?0:t(h,p.meridiem[1])?12:-1,s>=1&&12>=s&&f>-1?y.hour=s+f-1:s>=0&&23>=s&&(y.hour=s);else{if(!(s>=0&&23>=s))return null;y.hour=s}m=!0;break;case"G":case"H":if(!(s>=0&&23>=s))return null;y.hour=s,m=!0;break;case"i":if(!(s>=0&&59>=s))return null;y.min=s,m=!0;break;case"s":if(!(s>=0&&59>=s))return null;y.sec=s,m=!0}if(g===!0&&y.year&&y.month&&y.day)y.date=new Date(y.year,y.month-1,y.day,y.hour,y.min,y.sec,0);else{if(m!==!0)return null;y.date=new Date(0,0,0,y.hour,y.min,y.sec,0)}return y.date},guessDate:function(t,e){if("string"!=typeof t)return t;var r,n,a,u,i,s,o=this,c=t.replace(o.separators,"\x00").split("\x00"),f=/^[djmn]/g,l=e.match(o.validParts),h=new Date,d=0;if(!f.test(l[0]))return t;for(a=0;a<c.length;a++){if(d=2,i=c[a],s=parseInt(i.substr(0,2)),isNaN(s))return null;switch(a){case 0:"m"===l[0]||"n"===l[0]?h.setMonth(s-1):h.setDate(s);break;case 1:"m"===l[0]||"n"===l[0]?h.setDate(s):h.setMonth(s-1);break;case 2:if(n=h.getFullYear(),r=i.length,d=4>r?r:4,n=parseInt(4>r?n.toString().substr(0,4-r)+i:i.substr(0,4)),!n)return null;h.setFullYear(n);break;case 3:h.setHours(s);break;case 4:h.setMinutes(s);break;case 5:h.setSeconds(s)}u=i.substr(d),u.length>0&&c.splice(a+1,0,u)}return h},parseFormat:function(t,r){var n,a=this,s=a.dateSettings,o=/\\?(.?)/gi,c=function(t,e){return n[t]?n[t]():e};return n={d:function(){return e(n.j(),2)},D:function(){return s.daysShort[n.w()]},j:function(){return r.getDate()},l:function(){return s.days[n.w()]},N:function(){return n.w()||7},w:function(){return r.getDay()},z:function(){var t=new Date(n.Y(),n.n()-1,n.j()),e=new Date(n.Y(),0,1);return Math.round((t-e)/u)},W:function(){var t=new Date(n.Y(),n.n()-1,n.j()-n.N()+3),r=new Date(t.getFullYear(),0,4);return e(1+Math.round((t-r)/u/7),2)},F:function(){return s.months[r.getMonth()]},m:function(){return e(n.n(),2)},M:function(){return s.monthsShort[r.getMonth()]},n:function(){return r.getMonth()+1},t:function(){return new Date(n.Y(),n.n(),0).getDate()},L:function(){var t=n.Y();return t%4===0&&t%100!==0||t%400===0?1:0},o:function(){var t=n.n(),e=n.W(),r=n.Y();return r+(12===t&&9>e?1:1===t&&e>9?-1:0)},Y:function(){return r.getFullYear()},y:function(){return n.Y().toString().slice(-2)},a:function(){return n.A().toLowerCase()},A:function(){var t=n.G()<12?0:1;return s.meridiem[t]},B:function(){var t=r.getUTCHours()*i,n=60*r.getUTCMinutes(),a=r.getUTCSeconds();return e(Math.floor((t+n+a+i)/86.4)%1e3,3)},g:function(){return n.G()%12||12},G:function(){return r.getHours()},h:function(){return e(n.g(),2)},H:function(){return e(n.G(),2)},i:function(){return e(r.getMinutes(),2)},s:function(){return e(r.getSeconds(),2)},u:function(){return e(1e3*r.getMilliseconds(),6)},e:function(){var t=/\((.*)\)/.exec(String(r))[1];return t||"Coordinated Universal Time"},I:function(){var t=new Date(n.Y(),0),e=Date.UTC(n.Y(),0),r=new Date(n.Y(),6),a=Date.UTC(n.Y(),6);return t-e!==r-a?1:0},O:function(){var t=r.getTimezoneOffset(),n=Math.abs(t);return(t>0?"-":"+")+e(100*Math.floor(n/60)+n%60,4)},P:function(){var t=n.O();return t.substr(0,3)+":"+t.substr(3,2)},T:function(){var t=(String(r).match(a.tzParts)||[""]).pop().replace(a.tzClip,"");return t||"UTC"},Z:function(){return 60*-r.getTimezoneOffset()},c:function(){return"Y-m-d\\TH:i:sP".replace(o,c)},r:function(){return"D, d M Y H:i:s O".replace(o,c)},U:function(){return r.getTime()/1e3||0}},c(t,t)},formatDate:function(t,e){var r,n,a,u,i,s=this,o="",c="\\";if("string"==typeof t&&(t=s.parseDate(t,e),!t))return null;if(t instanceof Date){for(a=e.length,r=0;a>r;r++)i=e.charAt(r),"S"!==i&&i!==c&&(r>0&&e.charAt(r-1)===c?o+=i:(u=s.parseFormat(i,t),r!==a-1&&s.intParts.test(i)&&"S"===e.charAt(r+1)&&(n=parseInt(u)||0,u+=s.dateSettings.ordinal(n)),o+=u));return o}return""}}}();
+/**
+ * @preserve jQuery DateTimePicker
+ * @homepage http://xdsoft.net/jqplugins/datetimepicker/
+ * @author Chupurnov Valeriy (<chupurnov@gmail.com>)
+ */
+
+/**
+ * @param {jQuery} $
+ */
+var datetimepickerFactory = function ($) {
+ 'use strict';
+
+ var default_options = {
+ i18n: {
+ ar: { // Arabic
+ months: [
+ "كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
+ ],
+ dayOfWeekShort: [
+ "ن", "ث", "ع", "خ", "ج", "س", "ح"
+ ],
+ dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
+ },
+ ro: { // Romanian
+ months: [
+ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
+ ],
+ dayOfWeekShort: [
+ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
+ ],
+ dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
+ },
+ id: { // Indonesian
+ months: [
+ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
+ ],
+ dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
+ },
+ is: { // Icelandic
+ months: [
+ "Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
+ ],
+ dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
+ },
+ bg: { // Bulgarian
+ months: [
+ "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
+ ],
+ dayOfWeekShort: [
+ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
+ },
+ fa: { // Persian/Farsi
+ months: [
+ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
+ ],
+ dayOfWeekShort: [
+ 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
+ ],
+ dayOfWeek: ["یک‌شنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه", "شنبه", "یک‌شنبه"]
+ },
+ ru: { // Russian
+ months: [
+ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
+ ],
+ dayOfWeekShort: [
+ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
+ },
+ uk: { // Ukrainian
+ months: [
+ 'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
+ ],
+ dayOfWeekShort: [
+ "Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
+ ],
+ dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
+ },
+ en: { // English
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ el: { // Ελληνικά
+ months: [
+ "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
+ ],
+ dayOfWeekShort: [
+ "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
+ ],
+ dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
+ },
+ de: { // German
+ months: [
+ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
+ ],
+ dayOfWeekShort: [
+ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
+ ],
+ dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
+ },
+ nl: { // Dutch
+ months: [
+ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
+ ],
+ dayOfWeekShort: [
+ "zo", "ma", "di", "wo", "do", "vr", "za"
+ ],
+ dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
+ },
+ tr: { // Turkish
+ months: [
+ "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
+ ],
+ dayOfWeekShort: [
+ "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
+ ],
+ dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
+ },
+ fr: { //French
+ months: [
+ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
+ ],
+ dayOfWeekShort: [
+ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
+ ],
+ dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
+ },
+ es: { // Spanish
+ months: [
+ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
+ },
+ th: { // Thai
+ months: [
+ 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
+ ],
+ dayOfWeekShort: [
+ 'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
+ ],
+ dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
+ },
+ pl: { // Polish
+ months: [
+ "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
+ ],
+ dayOfWeekShort: [
+ "nd", "pn", "wt", "śr", "cz", "pt", "sb"
+ ],
+ dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
+ },
+ pt: { // Portuguese
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ ch: { // Simplified Chinese
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ]
+ },
+ se: { // Swedish
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ]
+ },
+ km: { // Khmer (ភាសាខ្មែរ)
+ months: [
+ "មករា​", "កុម្ភៈ", "មិនា​", "មេសា​", "ឧសភា​", "មិថុនា​", "កក្កដា​", "សីហា​", "កញ្ញា​", "តុលា​", "វិច្ឆិកា", "ធ្នូ​"
+ ],
+ dayOfWeekShort: ["អាទិ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហ​​", "សុក្រ​", "សៅរ៍"],
+ dayOfWeek: ["អាទិត្យ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហស្បតិ៍​", "សុក្រ​", "សៅរ៍"]
+ },
+ kr: { // Korean
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ it: { // Italian
+ months: [
+ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
+ },
+ da: { // Dansk
+ months: [
+ "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
+ },
+ no: { // Norwegian
+ months: [
+ "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
+ },
+ ja: { // Japanese
+ months: [
+ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
+ ],
+ dayOfWeekShort: [
+ "日", "月", "火", "水", "木", "金", "土"
+ ],
+ dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
+ },
+ vi: { // Vietnamese
+ months: [
+ "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
+ ],
+ dayOfWeekShort: [
+ "CN", "T2", "T3", "T4", "T5", "T6", "T7"
+ ],
+ dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
+ },
+ sl: { // Slovenščina
+ months: [
+ "Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
+ ],
+ dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
+ },
+ cs: { // Čeština
+ months: [
+ "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Út", "St", "Čt", "Pá", "So"
+ ]
+ },
+ hu: { // Hungarian
+ months: [
+ "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
+ ],
+ dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
+ },
+ az: { //Azerbaijanian (Azeri)
+ months: [
+ "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
+ ],
+ dayOfWeekShort: [
+ "B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
+ ],
+ dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
+ },
+ bs: { //Bosanski
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ca: { //Català
+ months: [
+ "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
+ ],
+ dayOfWeekShort: [
+ "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
+ ],
+ dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
+ },
+ 'en-GB': { //English (British)
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ et: { //"Eesti"
+ months: [
+ "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
+ ],
+ dayOfWeekShort: [
+ "P", "E", "T", "K", "N", "R", "L"
+ ],
+ dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
+ },
+ eu: { //Euskara
+ months: [
+ "Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
+ ],
+ dayOfWeekShort: [
+ "Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
+ ],
+ dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
+ },
+ fi: { //Finnish (Suomi)
+ months: [
+ "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
+ ],
+ dayOfWeekShort: [
+ "Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
+ ],
+ dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
+ },
+ gl: { //Galego
+ months: [
+ "Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
+ },
+ hr: { //Hrvatski
+ months: [
+ "Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ko: { //Korean (한국어)
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ lt: { //Lithuanian (lietuvių)
+ months: [
+ "Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
+ ],
+ dayOfWeekShort: [
+ "Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
+ ],
+ dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
+ },
+ lv: { //Latvian (Latviešu)
+ months: [
+ "Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
+ ],
+ dayOfWeekShort: [
+ "Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
+ ],
+ dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
+ },
+ mk: { //Macedonian (Македонски)
+ months: [
+ "јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "вто", "сре", "чет", "пет", "саб"
+ ],
+ dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
+ },
+ mn: { //Mongolian (Монгол)
+ months: [
+ "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
+ ],
+ dayOfWeekShort: [
+ "Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
+ ],
+ dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
+ },
+ 'pt-BR': { //Português(Brasil)
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ sk: { //Slovenčina
+ months: [
+ "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Ut", "St", "Št", "Pi", "So"
+ ],
+ dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
+ },
+ sq: { //Albanian (Shqip)
+ months: [
+ "Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
+ ],
+ dayOfWeekShort: [
+ "Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
+ ],
+ dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
+ },
+ 'sr-YU': { //Serbian (Srpski)
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
+ },
+ sr: { //Serbian Cyrillic (Српски)
+ months: [
+ "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "уто", "сре", "чет", "пет", "суб"
+ ],
+ dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
+ },
+ sv: { //Svenska
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ],
+ dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
+ },
+ 'zh-TW': { //Traditional Chinese (繁體中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ zh: { //Simplified Chinese (简体中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ ug:{ // Uyghur(ئۇيغۇرچە)
+ months: [
+ "1-ئاي","2-ئاي","3-ئاي","4-ئاي","5-ئاي","6-ئاي","7-ئاي","8-ئاي","9-ئاي","10-ئاي","11-ئاي","12-ئاي"
+ ],
+ dayOfWeek: [
+ "يەكشەنبە", "دۈشەنبە","سەيشەنبە","چارشەنبە","پەيشەنبە","جۈمە","شەنبە"
+ ]
+ },
+ he: { //Hebrew (עברית)
+ months: [
+ 'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
+ ],
+ dayOfWeekShort: [
+ 'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
+ ],
+ dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
+ },
+ hy: { // Armenian
+ months: [
+ "Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
+ ],
+ dayOfWeekShort: [
+ "Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
+ ],
+ dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
+ },
+ kg: { // Kyrgyz
+ months: [
+ 'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
+ ],
+ dayOfWeekShort: [
+ "Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
+ ],
+ dayOfWeek: [
+ "Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
+ ]
+ },
+ rm: { // Romansh
+ months: [
+ "Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
+ ],
+ dayOfWeek: [
+ "Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
+ ]
+ },
+ ka: { // Georgian
+ months: [
+ 'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
+ ],
+ dayOfWeekShort: [
+ "კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
+ ],
+ dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
+ }
+ },
+
+ ownerDocument: document,
+ contentWindow: window,
+
+ value: '',
+ rtl: false,
+
+ format: 'Y/m/d H:i',
+ formatTime: 'H:i',
+ formatDate: 'Y/m/d',
+
+ startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
+ step: 60,
+ monthChangeSpinner: true,
+
+ closeOnDateSelect: false,
+ closeOnTimeSelect: true,
+ closeOnWithoutClick: true,
+ closeOnInputClick: true,
+ openOnFocus: true,
+
+ timepicker: true,
+ datepicker: true,
+ weeks: false,
+
+ defaultTime: false, // use formatTime format (ex. '10:00' for formatTime: 'H:i')
+ defaultDate: false, // use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')
+
+ minDate: false,
+ maxDate: false,
+ minTime: false,
+ maxTime: false,
+ minDateTime: false,
+ maxDateTime: false,
+
+ allowTimes: [],
+ opened: false,
+ initTime: true,
+ inline: false,
+ theme: '',
+ touchMovedThreshold: 5,
+
+ onSelectDate: function () {},
+ onSelectTime: function () {},
+ onChangeMonth: function () {},
+ onGetWeekOfYear: function () {},
+ onChangeYear: function () {},
+ onChangeDateTime: function () {},
+ onShow: function () {},
+ onClose: function () {},
+ onGenerate: function () {},
+
+ withoutCopyright: true,
+ inverseButton: false,
+ hours12: false,
+ next: 'xdsoft_next',
+ prev : 'xdsoft_prev',
+ dayOfWeekStart: 0,
+ parentID: 'body',
+ timeHeightInTimePicker: 25,
+ timepickerScrollbar: true,
+ todayButton: true,
+ prevButton: true,
+ nextButton: true,
+ defaultSelect: true,
+
+ scrollMonth: true,
+ scrollTime: true,
+ scrollInput: true,
+
+ lazyInit: false,
+ mask: false,
+ validateOnBlur: true,
+ allowBlank: true,
+ yearStart: 1950,
+ yearEnd: 2050,
+ monthStart: 0,
+ monthEnd: 11,
+ style: '',
+ id: '',
+ fixed: false,
+ roundTime: 'round', // ceil, floor
+ className: '',
+ weekends: [],
+ highlightedDates: [],
+ highlightedPeriods: [],
+ allowDates : [],
+ allowDateRe : null,
+ disabledDates : [],
+ disabledWeekDays: [],
+ yearOffset: 0,
+ beforeShowDay: null,
+
+ enterLikeTab: true,
+ showApplyButton: false,
+ insideParent: false,
+ };
+
+ var dateHelper = null,
+ defaultDateHelper = null,
+ globalLocaleDefault = 'en',
+ globalLocale = 'en';
+
+ var dateFormatterOptionsDefault = {
+ meridiem: ['AM', 'PM']
+ };
+
+ var initDateFormatter = function(){
+ var locale = default_options.i18n[globalLocale],
+ opts = {
+ days: locale.dayOfWeek,
+ daysShort: locale.dayOfWeekShort,
+ months: locale.months,
+ monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) })
+ };
+
+ if (typeof DateFormatter === 'function') {
+ dateHelper = defaultDateHelper = new DateFormatter({
+ dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
+ });
+ }
+ };
+
+ var dateFormatters = {
+ moment: {
+ default_options:{
+ format: 'YYYY/MM/DD HH:mm',
+ formatDate: 'YYYY/MM/DD',
+ formatTime: 'HH:mm',
+ },
+ formatter: {
+ parseDate: function (date, format) {
+ if(isFormatStandard(format)){
+ return defaultDateHelper.parseDate(date, format);
+ }
+ var d = moment(date, format);
+ return d.isValid() ? d.toDate() : false;
+ },
+
+ formatDate: function (date, format) {
+ if(isFormatStandard(format)){
+ return defaultDateHelper.formatDate(date, format);
+ }
+ return moment(date).format(format);
+ },
+
+ formatMask: function(format){
+ return format
+ .replace(/Y{4}/g, '9999')
+ .replace(/Y{2}/g, '99')
+ .replace(/M{2}/g, '19')
+ .replace(/D{2}/g, '39')
+ .replace(/H{2}/g, '29')
+ .replace(/m{2}/g, '59')
+ .replace(/s{2}/g, '59');
+ },
+ }
+ }
+ }
+
+ // for locale settings
+ $.datetimepicker = {
+ setLocale: function(locale){
+ var newLocale = default_options.i18n[locale] ? locale : globalLocaleDefault;
+ if (globalLocale !== newLocale) {
+ globalLocale = newLocale;
+ // reinit date formatter
+ initDateFormatter();
+ }
+ },
+
+ setDateFormatter: function(dateFormatter) {
+ if(typeof dateFormatter === 'string' && dateFormatters.hasOwnProperty(dateFormatter)){
+ var df = dateFormatters[dateFormatter];
+ $.extend(default_options, df.default_options);
+ dateHelper = df.formatter;
+ }
+ else {
+ dateHelper = dateFormatter;
+ }
+ },
+ };
+
+ var standardFormats = {
+ RFC_2822: 'D, d M Y H:i:s O',
+ ATOM: 'Y-m-d\TH:i:sP',
+ ISO_8601: 'Y-m-d\TH:i:sO',
+ RFC_822: 'D, d M y H:i:s O',
+ RFC_850: 'l, d-M-y H:i:s T',
+ RFC_1036: 'D, d M y H:i:s O',
+ RFC_1123: 'D, d M Y H:i:s O',
+ RSS: 'D, d M Y H:i:s O',
+ W3C: 'Y-m-d\TH:i:sP'
+ }
+
+ var isFormatStandard = function(format){
+ return Object.values(standardFormats).indexOf(format) === -1 ? false : true;
+ }
+
+ $.extend($.datetimepicker, standardFormats);
+
+ // first init date formatter
+ initDateFormatter();
+
+ // fix for ie8
+ if (!window.getComputedStyle) {
+ window.getComputedStyle = function (el) {
+ this.el = el;
+ this.getPropertyValue = function (prop) {
+ var re = /(-([a-z]))/g;
+ if (prop === 'float') {
+ prop = 'styleFloat';
+ }
+ if (re.test(prop)) {
+ prop = prop.replace(re, function (a, b, c) {
+ return c.toUpperCase();
+ });
+ }
+ return el.currentStyle[prop] || null;
+ };
+ return this;
+ };
+ }
+ if (!Array.prototype.indexOf) {
+ Array.prototype.indexOf = function (obj, start) {
+ var i, j;
+ for (i = (start || 0), j = this.length; i < j; i += 1) {
+ if (this[i] === obj) { return i; }
+ }
+ return -1;
+ };
+ }
+
+ Date.prototype.countDaysInMonth = function () {
+ return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
+ };
+
+ $.fn.xdsoftScroller = function (options, percent) {
+ return this.each(function () {
+ var timeboxparent = $(this),
+ pointerEventToXY = function (e) {
+ var out = {x: 0, y: 0},
+ touch;
+ if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
+ touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
+ out.x = touch.clientX;
+ out.y = touch.clientY;
+ } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
+ out.x = e.clientX;
+ out.y = e.clientY;
+ }
+ return out;
+ },
+ getWheelDelta = function (e) {
+ var deltaY = 0;
+
+ if ('detail' in e) { deltaY = e.detail; }
+ if ('wheelDelta' in e) { deltaY = -e.wheelDelta / 120; }
+ if ('wheelDeltaY' in e) { deltaY = -e.wheelDeltaY / 120; }
+ if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) { deltaY = 0; }
+
+ deltaY *= 10;
+
+ if ('deltaY' in e) { deltaY = e.deltaY; }
+
+ if (deltaY && e.deltaMode) {
+ if (e.deltaMode === 1) {
+ deltaY *= 40;
+ } else {
+ deltaY *= 800;
+ }
+ }
+
+ return deltaY;
+ },
+ timebox,
+ timeboxTop = 0,
+ parentHeight,
+ height,
+ scrollbar,
+ scroller,
+ maximumOffset = 100,
+ start = false,
+ startY = 0,
+ startTop = 0,
+ h1 = 0,
+ touchStart = false,
+ startTopScroll = 0,
+ calcOffset = function () {};
+
+ if (percent === 'hide') {
+ timeboxparent.find('.xdsoft_scrollbar').hide();
+ return;
+ }
+
+ if (!$(this).hasClass('xdsoft_scroller_box')) {
+ timebox = timeboxparent.children().eq(0);
+ timeboxTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ scrollbar = $('<div class="xdsoft_scrollbar"></div>');
+ scroller = $('<div class="xdsoft_scroller"></div>');
+ scrollbar.append(scroller);
+
+ timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
+ calcOffset = function calcOffset(event) {
+ var offset = pointerEventToXY(event).y - startY + startTopScroll;
+ if (offset < 0) {
+ offset = 0;
+ }
+ if (offset + scroller[0].offsetHeight > h1) {
+ offset = h1 - scroller[0].offsetHeight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
+ };
+
+ scroller
+ .on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ }
+
+ startY = pointerEventToXY(event).y;
+ startTopScroll = parseInt(scroller.css('marginTop'), 10);
+ h1 = scrollbar[0].offsetHeight;
+
+ if (event.type === 'mousedown' || event.type === 'touchstart') {
+ if (options.ownerDocument) {
+ $(options.ownerDocument.body).addClass('xdsoft_noselect');
+ }
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
+ $([options.ownerDocument.body, options.contentWindow]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
+ .off('mousemove.xdsoft_scroller', calcOffset)
+ .removeClass('xdsoft_noselect');
+ });
+ $(options.ownerDocument.body).on('mousemove.xdsoft_scroller', calcOffset);
+ } else {
+ touchStart = true;
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ })
+ .on('touchmove', function (event) {
+ if (touchStart) {
+ event.preventDefault();
+ calcOffset(event);
+ }
+ })
+ .on('touchend touchcancel', function () {
+ touchStart = false;
+ startTopScroll = 0;
+ });
+
+ timeboxparent
+ .on('scroll_element.xdsoft_scroller', function (event, percentage) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
+ }
+ percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;
+ timeboxTop = parseFloat(Math.abs((timebox[0].offsetHeight - parentHeight) * percentage).toFixed(4));
+
+ scroller.css('marginTop', maximumOffset * percentage);
+ timebox.css('marginTop', -timeboxTop);
+ })
+ .on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
+ var percent, sh;
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ percent = parentHeight / height;
+ sh = percent * scrollbar[0].offsetHeight;
+ if (percent > 1) {
+ scroller.hide();
+ } else {
+ scroller.show();
+ scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
+ maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
+ if (noTriggerScroll !== true) {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || timeboxTop / (height - parentHeight)]);
+ }
+ }
+ });
+
+ timeboxparent.on('mousewheel', function (event) {
+ var deltaY = getWheelDelta(event.originalEvent);
+ var top = Math.max(0, timeboxTop - deltaY);
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
+ event.stopPropagation();
+ return false;
+ });
+
+ timeboxparent.on('touchstart', function (event) {
+ start = pointerEventToXY(event);
+ startTop = timeboxTop;
+ });
+
+ timeboxparent.on('touchmove', function (event) {
+ if (start) {
+ event.preventDefault();
+ var coord = pointerEventToXY(event);
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
+ }
+ });
+
+ timeboxparent.on('touchend touchcancel', function () {
+ start = false;
+ startTop = 0;
+ });
+ }
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ });
+ };
+
+ $.fn.datetimepicker = function (opt, opt2) {
+ var result = this,
+ KEY0 = 48,
+ KEY9 = 57,
+ _KEY0 = 96,
+ _KEY9 = 105,
+ CTRLKEY = 17,
+ CMDKEY = 91,
+ DEL = 46,
+ ENTER = 13,
+ ESC = 27,
+ BACKSPACE = 8,
+ ARROWLEFT = 37,
+ ARROWUP = 38,
+ ARROWRIGHT = 39,
+ ARROWDOWN = 40,
+ TAB = 9,
+ F5 = 116,
+ AKEY = 65,
+ CKEY = 67,
+ VKEY = 86,
+ ZKEY = 90,
+ YKEY = 89,
+ ctrlDown = false,
+ cmdDown = false,
+ options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),
+
+ lazyInitTimer = 0,
+ createDateTimePicker,
+ destroyDateTimePicker,
+
+ lazyInit = function (input) {
+ input
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
+ if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
+ return;
+ }
+ clearTimeout(lazyInitTimer);
+ lazyInitTimer = setTimeout(function () {
+
+ if (!input.data('xdsoft_datetimepicker')) {
+ createDateTimePicker(input);
+ }
+ input
+ .off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
+ .trigger('open.xdsoft');
+ }, 100);
+ });
+ };
+
+ createDateTimePicker = function (input) {
+ var datetimepicker = $('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'),
+ xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
+ datepicker = $('<div class="xdsoft_datepicker active"></div>'),
+ month_picker = $('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button>' +
+ '<div class="xdsoft_label xdsoft_month"><span></span><i></i></div>' +
+ '<div class="xdsoft_label xdsoft_year"><span></span><i></i></div>' +
+ '<button type="button" class="xdsoft_next"></button></div>'),
+ calendar = $('<div class="xdsoft_calendar"></div>'),
+ timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
+ timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
+ timebox = $('<div class="xdsoft_time_variant"></div>'),
+ applyButton = $('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'),
+
+ monthselect = $('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
+ yearselect = $('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'),
+ triggerAfterOpen = false,
+ XDSoft_datetime,
+
+ xchangeTimer,
+ timerclick,
+ current_time_index,
+ setPos,
+ timer = 0,
+ _xdsoft_datetime,
+ forEachAncestorOf;
+
+ if (options.id) {
+ datetimepicker.attr('id', options.id);
+ }
+ if (options.style) {
+ datetimepicker.attr('style', options.style);
+ }
+ if (options.weeks) {
+ datetimepicker.addClass('xdsoft_showweeks');
+ }
+ if (options.rtl) {
+ datetimepicker.addClass('xdsoft_rtl');
+ }
+
+ datetimepicker.addClass('xdsoft_' + options.theme);
+ datetimepicker.addClass(options.className);
+
+ month_picker
+ .find('.xdsoft_month span')
+ .after(monthselect);
+ month_picker
+ .find('.xdsoft_year span')
+ .after(yearselect);
+
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .on('touchstart mousedown.xdsoft', function (event) {
+ var select = $(this).find('.xdsoft_select').eq(0),
+ val = 0,
+ top = 0,
+ visible = select.is(':visible'),
+ items,
+ i;
+
+ month_picker
+ .find('.xdsoft_select')
+ .hide();
+ if (_xdsoft_datetime.currentTime) {
+ val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
+ }
+
+ select[visible ? 'hide' : 'show']();
+ for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
+ if (items.eq(i).data('value') === val) {
+ break;
+ } else {
+ top += items[0].offsetHeight;
+ }
+ }
+
+ select.xdsoftScroller(options, top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
+ event.stopPropagation();
+ return false;
+ });
+
+ var handleTouchMoved = function (event) {
+ var evt = event.originalEvent;
+ var touchPosition = evt.touches ? evt.touches[0] : evt;
+ this.touchStartPosition = this.touchStartPosition || touchPosition;
+ var xMovement = Math.abs(this.touchStartPosition.clientX - touchPosition.clientX);
+ var yMovement = Math.abs(this.touchStartPosition.clientY - touchPosition.clientY);
+ var distance = Math.sqrt(xMovement * xMovement + yMovement * yMovement);
+ if(distance > options.touchMovedThreshold) {
+ this.touchMoved = true;
+ }
+ }
+
+ month_picker
+ .find('.xdsoft_select')
+ .xdsoftScroller(options)
+ .on('touchstart mousedown.xdsoft', function (event) {
+ var evt = event.originalEvent;
+ this.touchMoved = false;
+ this.touchStartPosition = evt.touches ? evt.touches[0] : evt;
+ event.stopPropagation();
+ event.preventDefault();
+ })
+ .on('touchmove', '.xdsoft_option', handleTouchMoved)
+ .on('touchend mousedown.xdsoft', '.xdsoft_option', function () {
+ if (!this.touchMoved) {
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var year = _xdsoft_datetime.currentTime.getFullYear();
+ if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
+ _xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
+ }
+
+ $(this).parent().parent().hide();
+
+ datetimepicker.trigger('xchange.xdsoft');
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ }
+ });
+
+ datetimepicker.getValue = function () {
+ return _xdsoft_datetime.getCurrentTime();
+ };
+
+ datetimepicker.setOptions = function (_options) {
+ var highlightedDates = {};
+
+ options = $.extend(true, {}, options, _options);
+
+ if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
+ options.allowTimes = $.extend(true, [], _options.allowTimes);
+ }
+
+ if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
+ options.weekends = $.extend(true, [], _options.weekends);
+ }
+
+ if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
+ options.allowDates = $.extend(true, [], _options.allowDates);
+ }
+
+ if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
+ options.allowDateRe = new RegExp(_options.allowDateRe);
+ }
+
+ if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
+ $.each(_options.highlightedDates, function (index, value) {
+ var splitData = $.map(value.split(','), $.trim),
+ exDesc,
+ hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
+ keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
+ highlightedDates = $.extend(true, [], options.highlightedDates);
+ $.each(_options.highlightedPeriods, function (index, value) {
+ var dateTest, // start date
+ dateEnd,
+ desc,
+ hDate,
+ keyDate,
+ exDesc,
+ style;
+ if ($.isArray(value)) {
+ dateTest = value[0];
+ dateEnd = value[1];
+ desc = value[2];
+ style = value[3];
+ }
+ else {
+ var splitData = $.map(value.split(','), $.trim);
+ dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
+ dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
+ desc = splitData[2];
+ style = splitData[3];
+ }
+
+ while (dateTest <= dateEnd) {
+ hDate = new HighlightedDate(dateTest, desc, style);
+ keyDate = dateHelper.formatDate(dateTest, options.formatDate);
+ dateTest.setDate(dateTest.getDate() + 1);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
+ options.disabledDates = $.extend(true, [], _options.disabledDates);
+ }
+
+ if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
+ options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
+ }
+
+ if ((options.open || options.opened) && (!options.inline)) {
+ input.trigger('open.xdsoft');
+ }
+
+ if (options.inline) {
+ triggerAfterOpen = true;
+ datetimepicker.addClass('xdsoft_inline');
+ input.after(datetimepicker).hide();
+ }
+
+ if (options.inverseButton) {
+ options.next = 'xdsoft_prev';
+ options.prev = 'xdsoft_next';
+ }
+
+ if (options.datepicker) {
+ datepicker.addClass('active');
+ } else {
+ datepicker.removeClass('active');
+ }
+
+ if (options.timepicker) {
+ timepicker.addClass('active');
+ } else {
+ timepicker.removeClass('active');
+ }
+
+ if (options.value) {
+ _xdsoft_datetime.setCurrentTime(options.value);
+ if (input && input.val) {
+ input.val(_xdsoft_datetime.str);
+ }
+ }
+
+ if (isNaN(options.dayOfWeekStart)) {
+ options.dayOfWeekStart = 0;
+ } else {
+ options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
+ }
+
+ if (!options.timepickerScrollbar) {
+ timeboxparent.xdsoftScroller(options, 'hide');
+ }
+
+ if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
+ options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
+ }
+
+ if (options.maxDate && /^[\+\-](.*)$/.test(options.maxDate)) {
+ options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
+ }
+
+ if (options.minDateTime && /^\+(.*)$/.test(options.minDateTime)) {
+ options.minDateTime = _xdsoft_datetime.strToDateTime(options.minDateTime).dateFormat(options.formatDate);
+ }
+
+ if (options.maxDateTime && /^\+(.*)$/.test(options.maxDateTime)) {
+ options.maxDateTime = _xdsoft_datetime.strToDateTime(options.maxDateTime).dateFormat(options.formatDate);
+ }
+
+ applyButton.toggle(options.showApplyButton);
+
+ month_picker
+ .find('.xdsoft_today_button')
+ .css('visibility', !options.todayButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.prev)
+ .css('visibility', !options.prevButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.next)
+ .css('visibility', !options.nextButton ? 'hidden' : 'visible');
+
+ setMask(options);
+
+ if (options.validateOnBlur) {
+ input
+ .off('blur.xdsoft')
+ .on('blur.xdsoft', function () {
+ if (options.allowBlank && (!$.trim($(this).val()).length ||
+ (typeof options.mask === "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
+ $(this).val(null);
+ datetimepicker.data('xdsoft_datetime').empty();
+ } else {
+ var d = dateHelper.parseDate($(this).val(), options.format);
+ if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
+ $(this).val(dateHelper.formatDate(d, options.format));
+ } else {
+ var splittedHours = +([$(this).val()[0], $(this).val()[1]].join('')),
+ splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
+
+ // parse the numbers as 0312 => 03:12
+ if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
+ $(this).val([splittedHours, splittedMinutes].map(function (item) {
+ return item > 9 ? item : '0' + item;
+ }).join(':'));
+ } else {
+ $(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
+ }
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
+ }
+
+ datetimepicker.trigger('changedatetime.xdsoft');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ }
+ options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;
+
+ datetimepicker
+ .trigger('xchange.xdsoft')
+ .trigger('afterOpen.xdsoft');
+ };
+
+ datetimepicker
+ .data('options', options)
+ .on('touchstart mousedown.xdsoft', function (event) {
+ event.stopPropagation();
+ event.preventDefault();
+ yearselect.hide();
+ monthselect.hide();
+ return false;
+ });
+
+ //scroll_element = timepicker.find('.xdsoft_time_box');
+ timeboxparent.append(timebox);
+ timeboxparent.xdsoftScroller(options);
+
+ datetimepicker.on('afterOpen.xdsoft', function () {
+ timeboxparent.xdsoftScroller(options);
+ });
+
+ datetimepicker
+ .append(datepicker)
+ .append(timepicker);
+
+ if (options.withoutCopyright !== true) {
+ datetimepicker
+ .append(xdsoft_copyright);
+ }
+
+ datepicker
+ .append(month_picker)
+ .append(calendar)
+ .append(applyButton);
+
+ if (options.insideParent) {
+ $(input).parent().append(datetimepicker);
+ } else {
+ $(options.parentID).append(datetimepicker);
+ }
+
+ XDSoft_datetime = function () {
+ var _this = this;
+ _this.now = function (norecursion) {
+ var d = new Date(),
+ date,
+ time;
+
+ if (!norecursion && options.defaultDate) {
+ date = _this.strToDateTime(options.defaultDate);
+ d.setFullYear(date.getFullYear());
+ d.setMonth(date.getMonth());
+ d.setDate(date.getDate());
+ }
+
+ d.setFullYear(d.getFullYear());
+
+ if (!norecursion && options.defaultTime) {
+ time = _this.strtotime(options.defaultTime);
+ d.setHours(time.getHours());
+ d.setMinutes(time.getMinutes());
+ d.setSeconds(time.getSeconds());
+ d.setMilliseconds(time.getMilliseconds());
+ }
+ return d;
+ };
+
+ _this.isValidDate = function (d) {
+ if (Object.prototype.toString.call(d) !== "[object Date]") {
+ return false;
+ }
+ return !isNaN(d.getTime());
+ };
+
+ _this.setCurrentTime = function (dTime, requireValidDate) {
+ if (typeof dTime === 'string') {
+ _this.currentTime = _this.strToDateTime(dTime);
+ }
+ else if (_this.isValidDate(dTime)) {
+ _this.currentTime = dTime;
+ }
+ else if (!dTime && !requireValidDate && options.allowBlank && !options.inline) {
+ _this.currentTime = null;
+ }
+ else {
+ _this.currentTime = _this.now();
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ };
+
+ _this.empty = function () {
+ _this.currentTime = null;
+ };
+
+ _this.getCurrentTime = function () {
+ return _this.currentTime;
+ };
+
+ _this.nextMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() + 1,
+ year;
+ if (month === 12) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
+ month = 0;
+ }
+
+ year = _this.currentTime.getFullYear();
+
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.prevMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() - 1;
+ if (month === -1) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
+ month = 11;
+ }
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.getWeekOfYear = function (datetime) {
+ if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
+ var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
+ if (typeof week !== 'undefined') {
+ return week;
+ }
+ }
+ var onejan = new Date(datetime.getFullYear(), 0, 1);
+
+ //First week of the year is th one with the first Thursday according to ISO8601
+ if (onejan.getDay() !== 4) {
+ onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
+ }
+
+ return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
+ };
+
+ _this.strToDateTime = function (sDateTime) {
+ var tmpDate = [], timeOffset, currentTime;
+
+ if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
+ return sDateTime;
+ }
+
+ tmpDate = /^([+-]{1})(.*)$/.exec(sDateTime);
+
+ if (tmpDate) {
+ tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
+ }
+
+ if (tmpDate && tmpDate[2]) {
+ timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
+ currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
+ } else {
+ currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
+ }
+
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now();
+ }
+
+ return currentTime;
+ };
+
+ _this.strToDate = function (sDate) {
+ if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
+ return sDate;
+ }
+
+ var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.strtotime = function (sTime) {
+ if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
+ return sTime;
+ }
+ var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.str = function () {
+ var format = options.format;
+ if (options.yearOffset) {
+ format = format.replace('Y', _this.currentTime.getFullYear() + options.yearOffset);
+ format = format.replace('y', String(_this.currentTime.getFullYear() + options.yearOffset).substring(2, 4));
+ }
+ return dateHelper.formatDate(_this.currentTime, format);
+ };
+ _this.currentTime = this.now();
+ };
+
+ _xdsoft_datetime = new XDSoft_datetime();
+
+ applyButton.on('touchend click', function (e) {//pathbrite
+ e.preventDefault();
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+ input.val(_xdsoft_datetime.str());
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_today_button')
+ .on('touchend mousedown.xdsoft', function () {
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(0, true);
+ datetimepicker.trigger('afterOpen.xdsoft');
+ }).on('dblclick.xdsoft', function () {
+ var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
+ currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ if (currentDate < minDate) {
+ return;
+ }
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
+ if (currentDate > maxDate) {
+ return;
+ }
+ input.val(_xdsoft_datetime.str());
+ input.trigger('change');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false;
+
+ (function arguments_callee1(v) {
+ if ($this.hasClass(options.next)) {
+ _xdsoft_datetime.nextMonth();
+ } else if ($this.hasClass(options.prev)) {
+ _xdsoft_datetime.prevMonth();
+ }
+ if (options.monthChangeSpinner) {
+ if (!stop) {
+ timer = setTimeout(arguments_callee1, v || 100);
+ }
+ }
+ }(500));
+
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft', function arguments_callee2() {
+ clearTimeout(timer);
+ stop = true;
+ $([options.ownerDocument.body, options.contentWindow]).off('touchend mouseup.xdsoft', arguments_callee2);
+ });
+ });
+
+ timepicker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false,
+ period = 110;
+ (function arguments_callee4(v) {
+ var pheight = timeboxparent[0].clientHeight,
+ height = timebox[0].offsetHeight,
+ top = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
+ timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
+ } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
+ timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
+ }
+ /**
+ * Fixed bug:
+ * When using css3 transition, it will cause a bug that you cannot scroll the timepicker list.
+ * The reason is that the transition-duration time, if you set it to 0, all things fine, otherwise, this
+ * would cause a bug when you use jquery.css method.
+ * Let's say: * { transition: all .5s ease; }
+ * jquery timebox.css('marginTop') will return the original value which is before you clicking the next/prev button,
+ * meanwhile the timebox[0].style.marginTop will return the right value which is after you clicking the
+ * next/prev button.
+ *
+ * What we should do:
+ * Replace timebox.css('marginTop') with timebox[0].style.marginTop.
+ */
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]);
+ period = (period > 10) ? 10 : period - 10;
+ if (!stop) {
+ timer = setTimeout(arguments_callee4, v || period);
+ }
+ }(500));
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft', function arguments_callee5() {
+ clearTimeout(timer);
+ stop = true;
+ $([options.ownerDocument.body, options.contentWindow])
+ .off('touchend mouseup.xdsoft', arguments_callee5);
+ });
+ });
+
+ xchangeTimer = 0;
+ // base handler - generating a calendar and timepicker
+ datetimepicker
+ .on('xchange.xdsoft', function (event) {
+ clearTimeout(xchangeTimer);
+ xchangeTimer = setTimeout(function () {
+
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var table = '',
+ start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
+ i = 0,
+ j,
+ today = _xdsoft_datetime.now(),
+ maxDate = false,
+ minDate = false,
+ minDateTime = false,
+ maxDateTime = false,
+ hDate,
+ day,
+ d,
+ y,
+ m,
+ w,
+ classes = [],
+ customDateSettings,
+ newRow = true,
+ time = '',
+ h,
+ line_time,
+ description;
+
+ while (start.getDay() !== options.dayOfWeekStart) {
+ start.setDate(start.getDate() - 1);
+ }
+
+ table += '<table><thead><tr>';
+
+ if (options.weeks) {
+ table += '<th></th>';
+ }
+
+ for (j = 0; j < 7; j += 1) {
+ table += '<th>' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + '</th>';
+ }
+
+ table += '</tr></thead>';
+ table += '<tbody>';
+
+ if (options.maxDate !== false) {
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
+ }
+
+ if (options.minDate !== false) {
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ }
+
+ if (options.minDateTime !== false) {
+ minDateTime = _xdsoft_datetime.strToDate(options.minDateTime);
+ minDateTime = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), minDateTime.getHours(), minDateTime.getMinutes(), minDateTime.getSeconds());
+ }
+
+ if (options.maxDateTime !== false) {
+ maxDateTime = _xdsoft_datetime.strToDate(options.maxDateTime);
+ maxDateTime = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), maxDateTime.getHours(), maxDateTime.getMinutes(), maxDateTime.getSeconds());
+ }
+
+ var maxDateTimeDay;
+ if (maxDateTime !== false) {
+ maxDateTimeDay = ((maxDateTime.getFullYear() * 12) + maxDateTime.getMonth()) * 31 + maxDateTime.getDate();
+ }
+
+ while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
+ classes = [];
+ i += 1;
+
+ day = start.getDay();
+ d = start.getDate();
+ y = start.getFullYear();
+ m = start.getMonth();
+ w = _xdsoft_datetime.getWeekOfYear(start);
+ description = '';
+
+ classes.push('xdsoft_date');
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
+ customDateSettings = options.beforeShowDay.call(datetimepicker, start);
+ } else {
+ customDateSettings = null;
+ }
+
+ if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
+ if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
+ classes.push('xdsoft_disabled');
+ }
+ }
+
+ if(options.allowDates && options.allowDates.length>0){
+ if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
+ classes.push('xdsoft_disabled');
+ }
+ }
+
+ var currentDay = ((start.getFullYear() * 12) + start.getMonth()) * 31 + start.getDate();
+ if ((maxDate !== false && start > maxDate) || (minDateTime !== false && start < minDateTime) || (minDate !== false && start < minDate) || (maxDateTime !== false && currentDay > maxDateTimeDay) || (customDateSettings && customDateSettings[0] === false)) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (options.disabledWeekDays.indexOf(day) !== -1) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (input.is('[disabled]')) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (customDateSettings && customDateSettings[1] !== "") {
+ classes.push(customDateSettings[1]);
+ }
+
+ if (_xdsoft_datetime.currentTime.getMonth() !== m) {
+ classes.push('xdsoft_other_month');
+ }
+
+ if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_current');
+ }
+
+ if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_today');
+ }
+
+ if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_weekend');
+ }
+
+ if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
+ hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
+ classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
+ description = hDate.desc === undefined ? '' : hDate.desc;
+ }
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
+ classes.push(options.beforeShowDay(start));
+ }
+
+ if (newRow) {
+ table += '<tr>';
+ newRow = false;
+ if (options.weeks) {
+ table += '<th>' + w + '</th>';
+ }
+ }
+
+ table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="xdsoft_date xdsoft_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '" title="' + description + '">' +
+ '<div>' + d + '</div>' +
+ '</td>';
+
+ if (start.getDay() === options.dayOfWeekStartPrev) {
+ table += '</tr>';
+ newRow = true;
+ }
+
+ start.setDate(d + 1);
+ }
+ table += '</tbody></table>';
+
+ calendar.html(table);
+
+ month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
+ month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear() + options.yearOffset);
+
+ // generate timebox
+ time = '';
+ h = '';
+ m = '';
+
+ var minTimeMinutesOfDay = 0;
+ if (options.minTime !== false) {
+ var t = _xdsoft_datetime.strtotime(options.minTime);
+ minTimeMinutesOfDay = 60 * t.getHours() + t.getMinutes();
+ }
+ var maxTimeMinutesOfDay = 24 * 60;
+ if (options.maxTime !== false) {
+ var t = _xdsoft_datetime.strtotime(options.maxTime);
+ maxTimeMinutesOfDay = 60 * t.getHours() + t.getMinutes();
+ }
+
+ if (options.minDateTime !== false) {
+ var t = _xdsoft_datetime.strToDateTime(options.minDateTime);
+ var currentDayIsMinDateTimeDay = dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(t, options.formatDate);
+ if (currentDayIsMinDateTimeDay) {
+ var m = 60 * t.getHours() + t.getMinutes();
+ if (m > minTimeMinutesOfDay) minTimeMinutesOfDay = m;
+ }
+ }
+
+ if (options.maxDateTime !== false) {
+ var t = _xdsoft_datetime.strToDateTime(options.maxDateTime);
+ var currentDayIsMaxDateTimeDay = dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(t, options.formatDate);
+ if (currentDayIsMaxDateTimeDay) {
+ var m = 60 * t.getHours() + t.getMinutes();
+ if (m < maxTimeMinutesOfDay) maxTimeMinutesOfDay = m;
+ }
+ }
+
+ line_time = function line_time(h, m) {
+ var now = _xdsoft_datetime.now(), current_time,
+ isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
+ now.setHours(h);
+ h = parseInt(now.getHours(), 10);
+ now.setMinutes(m);
+ m = parseInt(now.getMinutes(), 10);
+ classes = [];
+ var currentMinutesOfDay = 60 * h + m;
+ if (input.is('[disabled]') || (currentMinutesOfDay >= maxTimeMinutesOfDay) || (currentMinutesOfDay < minTimeMinutesOfDay)) {
+ classes.push('xdsoft_disabled');
+ }
+
+ current_time = new Date(_xdsoft_datetime.currentTime);
+ current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));
+
+ if (!isALlowTimesInit) {
+ current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
+ }
+
+ if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
+ if (options.defaultSelect || datetimepicker.data('changed')) {
+ classes.push('xdsoft_current');
+ } else if (options.initTime) {
+ classes.push('xdsoft_init_time');
+ }
+ }
+ if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
+ classes.push('xdsoft_today');
+ }
+ time += '<div class="xdsoft_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + dateHelper.formatDate(now, options.formatTime) + '</div>';
+ };
+
+ if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
+ for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
+ for (j = 0; j < 60; j += options.step) {
+ var currentMinutesOfDay = i * 60 + j;
+ if (currentMinutesOfDay < minTimeMinutesOfDay) continue;
+ if (currentMinutesOfDay >= maxTimeMinutesOfDay) continue;
+ h = (i < 10 ? '0' : '') + i;
+ m = (j < 10 ? '0' : '') + j;
+ line_time(h, m);
+ }
+ }
+ } else {
+ for (i = 0; i < options.allowTimes.length; i += 1) {
+ h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
+ m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
+ line_time(h, m);
+ }
+ }
+
+ timebox.html(time);
+
+ opt = '';
+
+ for (i = parseInt(options.yearStart, 10); i <= parseInt(options.yearEnd, 10); i += 1) {
+ opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getFullYear() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + (i + options.yearOffset) + '</div>';
+ }
+ yearselect.children().eq(0)
+ .html(opt);
+
+ for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
+ opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getMonth() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + options.i18n[globalLocale].months[i] + '</div>';
+ }
+ monthselect.children().eq(0).html(opt);
+ $(datetimepicker)
+ .trigger('generate.xdsoft');
+ }, 10);
+ event.stopPropagation();
+ })
+ .on('afterOpen.xdsoft', function () {
+ if (options.timepicker) {
+ var classType, pheight, height, top;
+ if (timebox.find('.xdsoft_current').length) {
+ classType = '.xdsoft_current';
+ } else if (timebox.find('.xdsoft_init_time').length) {
+ classType = '.xdsoft_init_time';
+ }
+ if (classType) {
+ pheight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
+ if ((height - pheight) < top) {
+ top = height - pheight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
+ } else {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
+ }
+ }
+ });
+
+ timerclick = 0;
+ calendar
+ .on('touchend click.xdsoft', 'td', function (xdevent) {
+ xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
+ timerclick += 1;
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+
+ currentTime.setDate(1);
+ currentTime.setFullYear($this.data('year'));
+ currentTime.setMonth($this.data('month'));
+ currentTime.setDate($this.data('date'));
+
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ input.val(_xdsoft_datetime.str());
+
+ if (options.onSelectDate && $.isFunction(options.onSelectDate)) {
+ options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ setTimeout(function () {
+ timerclick = 0;
+ }, 200);
+ });
+
+ timebox
+ .on('touchstart', 'div', function (xdevent) {
+ this.touchMoved = false;
+ })
+ .on('touchmove', 'div', handleTouchMoved)
+ .on('touchend click.xdsoft', 'div', function (xdevent) {
+ if (!this.touchMoved) {
+ xdevent.stopPropagation();
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+ currentTime.setHours($this.data('hour'));
+ currentTime.setMinutes($this.data('minute'));
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ datetimepicker.data('input').val(_xdsoft_datetime.str());
+
+ if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
+ options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if (options.inline !== true && options.closeOnTimeSelect === true) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ }
+ });
+
+ datepicker
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollMonth) {
+ return true;
+ }
+ if (event.deltaY < 0) {
+ _xdsoft_datetime.nextMonth();
+ } else {
+ _xdsoft_datetime.prevMonth();
+ }
+ return false;
+ });
+
+ input
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollInput) {
+ return true;
+ }
+ if (!options.datepicker && options.timepicker) {
+ current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
+ if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
+ current_time_index += event.deltaY;
+ }
+ if (timebox.children().eq(current_time_index).length) {
+ timebox.children().eq(current_time_index).trigger('mousedown');
+ }
+ return false;
+ }
+ if (options.datepicker && !options.timepicker) {
+ datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
+ if (input.val) {
+ input.val(_xdsoft_datetime.str());
+ }
+ datetimepicker.trigger('changedatetime.xdsoft');
+ return false;
+ }
+ });
+
+ datetimepicker
+ .on('changedatetime.xdsoft', function (event) {
+ if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
+ var $input = datetimepicker.data('input');
+ options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
+ delete options.value;
+ $input.trigger('change');
+ }
+ })
+ .on('generate.xdsoft', function () {
+ if (options.onGenerate && $.isFunction(options.onGenerate)) {
+ options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ if (triggerAfterOpen) {
+ datetimepicker.trigger('afterOpen.xdsoft');
+ triggerAfterOpen = false;
+ }
+ })
+ .on('click.xdsoft', function (xdevent) {
+ xdevent.stopPropagation();
+ });
+
+ current_time_index = 0;
+
+ /**
+ * Runs the callback for each of the specified node's ancestors.
+ *
+ * Return FALSE from the callback to stop ascending.
+ *
+ * @param {DOMNode} node
+ * @param {Function} callback
+ * @returns {undefined}
+ */
+ forEachAncestorOf = function (node, callback) {
+ do {
+ node = node.parentNode;
+
+ if (!node || callback(node) === false) {
+ break;
+ }
+ } while (node.nodeName !== 'HTML');
+ };
+
+ /**
+ * Sets the position of the picker.
+ *
+ * @returns {undefined}
+ */
+ setPos = function () {
+ var dateInputOffset,
+ dateInputElem,
+ verticalPosition,
+ left,
+ position,
+ datetimepickerElem,
+ dateInputHasFixedAncestor,
+ $dateInput,
+ windowWidth,
+ verticalAnchorEdge,
+ datetimepickerCss,
+ windowHeight,
+ windowScrollTop;
+
+ $dateInput = datetimepicker.data('input');
+ dateInputOffset = $dateInput.offset();
+ dateInputElem = $dateInput[0];
+
+ verticalAnchorEdge = 'top';
+ verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
+ left = dateInputOffset.left;
+ position = "absolute";
+
+ windowWidth = $(options.contentWindow).width();
+ windowHeight = $(options.contentWindow).height();
+ windowScrollTop = $(options.contentWindow).scrollTop();
+
+ if ((options.ownerDocument.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
+ var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
+ left = left - diff;
+ }
+
+ if ($dateInput.parent().css('direction') === 'rtl') {
+ left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
+ }
+
+ if (options.fixed) {
+ verticalPosition -= windowScrollTop;
+ left -= $(options.contentWindow).scrollLeft();
+ position = "fixed";
+ } else {
+ dateInputHasFixedAncestor = false;
+
+ forEachAncestorOf(dateInputElem, function (ancestorNode) {
+ if (ancestorNode === null) {
+ return false;
+ }
+
+ if (options.contentWindow.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
+ dateInputHasFixedAncestor = true;
+ return false;
+ }
+ });
+
+ if (dateInputHasFixedAncestor && !options.insideParent) {
+ position = 'fixed';
+
+ //If the picker won't fit entirely within the viewport then display it above the date input.
+ if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
+ verticalAnchorEdge = 'bottom';
+ verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
+ } else {
+ verticalPosition -= windowScrollTop;
+ }
+ } else {
+ if (verticalPosition + datetimepicker[0].offsetHeight > windowHeight + windowScrollTop) {
+ verticalPosition = dateInputOffset.top - datetimepicker[0].offsetHeight + 1;
+ }
+ }
+
+ if (verticalPosition < 0) {
+ verticalPosition = 0;
+ }
+
+ if (left + dateInputElem.offsetWidth > windowWidth) {
+ left = windowWidth - dateInputElem.offsetWidth;
+ }
+ }
+
+ datetimepickerElem = datetimepicker[0];
+
+ forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
+ var ancestorNodePosition;
+
+ ancestorNodePosition = options.contentWindow.getComputedStyle(ancestorNode).getPropertyValue('position');
+
+ if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
+ left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
+ return false;
+ }
+ });
+
+ datetimepickerCss = {
+ position: position,
+ left: options.insideParent ? dateInputElem.offsetLeft : left,
+ top: '', //Initialize to prevent previous values interfering with new ones.
+ bottom: '' //Initialize to prevent previous values interfering with new ones.
+ };
+
+ if (options.insideParent) {
+ datetimepickerCss[verticalAnchorEdge] = dateInputElem.offsetTop + dateInputElem.offsetHeight;
+ } else {
+ datetimepickerCss[verticalAnchorEdge] = verticalPosition;
+ }
+
+ datetimepicker.css(datetimepickerCss);
+ };
+
+ datetimepicker
+ .on('open.xdsoft', function (event) {
+ var onShow = true;
+ if (options.onShow && $.isFunction(options.onShow)) {
+ onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onShow !== false) {
+ datetimepicker.show();
+ setPos();
+ $(options.contentWindow)
+ .off('resize.xdsoft', setPos)
+ .on('resize.xdsoft', setPos);
+
+ if (options.closeOnWithoutClick) {
+ $([options.ownerDocument.body, options.contentWindow]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
+ datetimepicker.trigger('close.xdsoft');
+ $([options.ownerDocument.body, options.contentWindow]).off('touchstart mousedown.xdsoft', arguments_callee6);
+ });
+ }
+ }
+ })
+ .on('close.xdsoft', function (event) {
+ var onClose = true;
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .find('.xdsoft_select')
+ .hide();
+ if (options.onClose && $.isFunction(options.onClose)) {
+ onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onClose !== false && !options.opened && !options.inline) {
+ datetimepicker.hide();
+ }
+ event.stopPropagation();
+ })
+ .on('toggle.xdsoft', function () {
+ if (datetimepicker.is(':visible')) {
+ datetimepicker.trigger('close.xdsoft');
+ } else {
+ datetimepicker.trigger('open.xdsoft');
+ }
+ })
+ .data('input', input);
+
+ timer = 0;
+
+ datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
+ datetimepicker.setOptions(options);
+
+ function getCurrentValue() {
+ var ct = false, time;
+
+ if (options.startDate) {
+ ct = _xdsoft_datetime.strToDate(options.startDate);
+ } else {
+ ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
+ if (ct) {
+ ct = _xdsoft_datetime.strToDateTime(ct);
+ if (options.yearOffset) {
+ ct = new Date(ct.getFullYear() - options.yearOffset, ct.getMonth(), ct.getDate(), ct.getHours(), ct.getMinutes(), ct.getSeconds(), ct.getMilliseconds());
+ }
+ } else if (options.defaultDate) {
+ ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
+ if (options.defaultTime) {
+ time = _xdsoft_datetime.strtotime(options.defaultTime);
+ ct.setHours(time.getHours());
+ ct.setMinutes(time.getMinutes());
+ }
+ }
+ }
+
+ if (ct && _xdsoft_datetime.isValidDate(ct)) {
+ datetimepicker.data('changed', true);
+ } else {
+ ct = '';
+ }
+
+ return ct || 0;
+ }
+
+ function setMask(options) {
+
+ var isValidValue = function (mask, value) {
+ var reg = mask
+ .replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
+ .replace(/_/g, '{digit+}')
+ .replace(/([0-9]{1})/g, '{digit$1}')
+ .replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
+ .replace(/\{digit[\+]\}/g, '[0-9_]{1}');
+ return (new RegExp(reg)).test(value);
+ },
+ getCaretPos = function (input) {
+ try {
+ if (options.ownerDocument.selection && options.ownerDocument.selection.createRange) {
+ var range = options.ownerDocument.selection.createRange();
+ return range.getBookmark().charCodeAt(2) - 2;
+ }
+ if (input.setSelectionRange) {
+ return input.selectionStart;
+ }
+ } catch (e) {
+ return 0;
+ }
+ },
+ setCaretPos = function (node, pos) {
+ node = (typeof node === "string" || node instanceof String) ? options.ownerDocument.getElementById(node) : node;
+ if (!node) {
+ return false;
+ }
+ if (node.createTextRange) {
+ var textRange = node.createTextRange();
+ textRange.collapse(true);
+ textRange.moveEnd('character', pos);
+ textRange.moveStart('character', pos);
+ textRange.select();
+ return true;
+ }
+ if (node.setSelectionRange) {
+ node.setSelectionRange(pos, pos);
+ return true;
+ }
+ return false;
+ };
+
+ if(options.mask) {
+ input.off('keydown.xdsoft');
+ }
+
+ if (options.mask === true) {
+ if (dateHelper.formatMask) {
+ options.mask = dateHelper.formatMask(options.format)
+ } else {
+ options.mask = options.format
+ .replace(/Y/g, '9999')
+ .replace(/F/g, '9999')
+ .replace(/m/g, '19')
+ .replace(/d/g, '39')
+ .replace(/H/g, '29')
+ .replace(/i/g, '59')
+ .replace(/s/g, '59');
+ }
+ }
+
+ if ($.type(options.mask) === 'string') {
+ if (!isValidValue(options.mask, input.val())) {
+ input.val(options.mask.replace(/[0-9]/g, '_'));
+ setCaretPos(input[0], 0);
+ }
+
+ input.on('paste.xdsoft', function (event) {
+ // couple options here
+ // 1. return false - tell them they can't paste
+ // 2. insert over current characters - minimal validation
+ // 3. full fledged parsing and validation
+ // let's go option 2 for now
+
+ // fires multiple times for some reason
+
+ // https://stackoverflow.com/a/30496488/1366033
+ var clipboardData = event.clipboardData || event.originalEvent.clipboardData || window.clipboardData,
+ pastedData = clipboardData.getData('text'),
+ val = this.value,
+ pos = this.selectionStart
+
+ var valueBeforeCursor = val.substr(0, pos);
+ var valueAfterPaste = val.substr(pos + pastedData.length);
+
+ val = valueBeforeCursor + pastedData + valueAfterPaste;
+ pos += pastedData.length;
+
+ if (isValidValue(options.mask, val)) {
+ this.value = val;
+ setCaretPos(this, pos);
+ } else if ($.trim(val) === '') {
+ this.value = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ input.trigger('error_input.xdsoft');
+ }
+
+ event.preventDefault();
+ return false;
+ });
+
+ input.on('keydown.xdsoft', function (event) {
+ var val = this.value,
+ key = event.which,
+ pos = this.selectionStart,
+ selEnd = this.selectionEnd,
+ hasSel = pos !== selEnd,
+ digit;
+
+ // only alow these characters
+ if (((key >= KEY0 && key <= KEY9) ||
+ (key >= _KEY0 && key <= _KEY9)) ||
+ (key === BACKSPACE || key === DEL)) {
+
+ // get char to insert which is new character or placeholder ('_')
+ digit = (key === BACKSPACE || key === DEL) ? '_' :
+ String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key);
+
+ // we're deleting something, we're not at the start, and have normal cursor, move back one
+ // if we have a selection length, cursor actually sits behind deletable char, not in front
+ if (key === BACKSPACE && pos && !hasSel) {
+ pos -= 1;
+ }
+
+ // don't stop on a separator, continue whatever direction you were going
+ // value char - keep incrementing position while on separator char and we still have room
+ // del char - keep decrementing position while on separator char and we still have room
+ while (true) {
+ var maskValueAtCurPos = options.mask.substr(pos, 1);
+ var posShorterThanMaskLength = pos < options.mask.length;
+ var posGreaterThanZero = pos > 0;
+ var notNumberOrPlaceholder = /[^0-9_]/;
+ var curPosOnSep = notNumberOrPlaceholder.test(maskValueAtCurPos);
+ var continueMovingPosition = curPosOnSep && posShorterThanMaskLength && posGreaterThanZero
+
+ // if we hit a real char, stay where we are
+ if (!continueMovingPosition) break;
+
+ // hitting backspace in a selection, you can possibly go back any further - go forward
+ pos += (key === BACKSPACE && !hasSel) ? -1 : 1;
+
+ }
+
+ if (event.metaKey) { // cmd has been pressed
+ pos = 0;
+ hasSel = true;
+ }
+
+ if (hasSel) {
+ // pos might have moved so re-calc length
+ var selLength = selEnd - pos
+
+ // if we have a selection length we will wipe out entire selection and replace with default template for that range
+ var defaultBlank = options.mask.replace(/[0-9]/g, '_');
+ var defaultBlankSelectionReplacement = defaultBlank.substr(pos, selLength);
+ var selReplacementRemainder = defaultBlankSelectionReplacement.substr(1) // might be empty
+
+ var valueBeforeSel = val.substr(0, pos);
+ var insertChars = digit + selReplacementRemainder;
+ var charsAfterSelection = val.substr(pos + selLength);
+
+ val = valueBeforeSel + insertChars + charsAfterSelection
+
+ } else {
+ var valueBeforeCursor = val.substr(0, pos);
+ var insertChar = digit;
+ var valueAfterNextChar = val.substr(pos + 1);
+
+ val = valueBeforeCursor + insertChar + valueAfterNextChar
+ }
+
+ if ($.trim(val) === '') {
+ // if empty, set to default
+ val = defaultBlank
+ } else {
+ // if at the last character don't need to do anything
+ if (pos === options.mask.length) {
+ event.preventDefault();
+ return false;
+ }
+ }
+
+ // resume cursor location
+ pos += (key === BACKSPACE) ? 0 : 1;
+ // don't stop on a separator, continue whatever direction you were going
+ while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
+ pos += (key === BACKSPACE) ? 0 : 1;
+ }
+
+ if (isValidValue(options.mask, val)) {
+ this.value = val;
+ setCaretPos(this, pos);
+ } else if ($.trim(val) === '') {
+ this.value = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ input.trigger('error_input.xdsoft');
+ }
+ } else {
+ if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
+ return true;
+ }
+ }
+
+ event.preventDefault();
+ return false;
+ });
+ }
+ }
+
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+
+ input
+ .data('xdsoft_datetimepicker', datetimepicker)
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
+ if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
+ return;
+ }
+ if (!options.openOnFocus) {
+ return;
+ }
+ clearTimeout(timer);
+ timer = setTimeout(function () {
+ if (input.is(':disabled')) {
+ return;
+ }
+
+ triggerAfterOpen = true;
+ _xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
+ if(options.mask) {
+ setMask(options);
+ }
+ datetimepicker.trigger('open.xdsoft');
+ }, 100);
+ })
+ .on('keydown.xdsoft', function (event) {
+ var elementSelector,
+ key = event.which;
+ if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
+ elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
+ datetimepicker.trigger('close.xdsoft');
+ elementSelector.eq(elementSelector.index(this) + 1).focus();
+ return false;
+ }
+ if ([TAB].indexOf(key) !== -1) {
+ datetimepicker.trigger('close.xdsoft');
+ return true;
+ }
+ })
+ .on('blur.xdsoft', function () {
+ datetimepicker.trigger('close.xdsoft');
+ });
+ };
+ destroyDateTimePicker = function (input) {
+ var datetimepicker = input.data('xdsoft_datetimepicker');
+ if (datetimepicker) {
+ datetimepicker.data('xdsoft_datetime', null);
+ datetimepicker.remove();
+ input
+ .data('xdsoft_datetimepicker', null)
+ .off('.xdsoft');
+ $(options.contentWindow).off('resize.xdsoft');
+ $([options.contentWindow, options.ownerDocument.body]).off('mousedown.xdsoft touchstart');
+ if (input.unmousewheel) {
+ input.unmousewheel();
+ }
+ }
+ };
+ $(options.ownerDocument)
+ .off('keydown.xdsoftctrl keyup.xdsoftctrl')
+ .off('keydown.xdsoftcmd keyup.xdsoftcmd')
+ .on('keydown.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = true;
+ }
+ })
+ .on('keyup.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = false;
+ }
+ })
+ .on('keydown.xdsoftcmd', function (e) {
+ if (e.keyCode === CMDKEY) {
+ cmdDown = true;
+ }
+ })
+ .on('keyup.xdsoftcmd', function (e) {
+ if (e.keyCode === CMDKEY) {
+ cmdDown = false;
+ }
+ });
+
+ this.each(function () {
+ var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
+ if (datetimepicker) {
+ if ($.type(opt) === 'string') {
+ switch (opt) {
+ case 'show':
+ $(this).select().focus();
+ datetimepicker.trigger('open.xdsoft');
+ break;
+ case 'hide':
+ datetimepicker.trigger('close.xdsoft');
+ break;
+ case 'toggle':
+ datetimepicker.trigger('toggle.xdsoft');
+ break;
+ case 'destroy':
+ destroyDateTimePicker($(this));
+ break;
+ case 'reset':
+ this.value = this.defaultValue;
+ if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
+ datetimepicker.data('changed', false);
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
+ break;
+ case 'validate':
+ $input = datetimepicker.data('input');
+ $input.trigger('blur.xdsoft');
+ break;
+ default:
+ if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
+ result = datetimepicker[opt](opt2);
+ }
+ }
+ } else {
+ datetimepicker
+ .setOptions(opt);
+ }
+ return 0;
+ }
+ if ($.type(opt) !== 'string') {
+ if (!options.lazyInit || options.open || options.inline) {
+ createDateTimePicker($(this));
+ } else {
+ lazyInit($(this));
+ }
+ }
+ });
+
+ return result;
+ };
+
+ $.fn.datetimepicker.defaults = default_options;
+
+ function HighlightedDate(date, desc, style) {
+ "use strict";
+ this.date = date;
+ this.desc = desc;
+ this.style = style;
+ }
+};
+;(function (factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery', 'jquery-mousewheel'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory(require('jquery'));;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(datetimepickerFactory));
+
+
+
+/*!
+ * jQuery Mousewheel 3.1.13
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ */
+
+(function (factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(function ($) {
+
+ var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
+ toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
+ ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
+ slice = Array.prototype.slice,
+ nullLowestDeltaTimeout, lowestDelta;
+
+ if ( $.event.fixHooks ) {
+ for ( var i = toFix.length; i; ) {
+ $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
+ }
+ }
+
+ var special = $.event.special.mousewheel = {
+ version: '3.1.12',
+
+ setup: function() {
+ if ( this.addEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.addEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = handler;
+ }
+ // Store the line height and page height for this particular element
+ $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
+ $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
+ },
+
+ teardown: function() {
+ if ( this.removeEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.removeEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = null;
+ }
+ // Clean up the data we added to the element
+ $.removeData(this, 'mousewheel-line-height');
+ $.removeData(this, 'mousewheel-page-height');
+ },
+
+ getLineHeight: function(elem) {
+ var $elem = $(elem),
+ $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
+ if (!$parent.length) {
+ $parent = $('body');
+ }
+ return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
+ },
+
+ getPageHeight: function(elem) {
+ return $(elem).height();
+ },
+
+ settings: {
+ adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
+ normalizeOffset: true // calls getBoundingClientRect for each event
+ }
+ };
+
+ $.fn.extend({
+ mousewheel: function(fn) {
+ return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
+ },
+
+ unmousewheel: function(fn) {
+ return this.unbind('mousewheel', fn);
+ }
+ });
+
+
+ function handler(event) {
+ var orgEvent = event || window.event,
+ args = slice.call(arguments, 1),
+ delta = 0,
+ deltaX = 0,
+ deltaY = 0,
+ absDelta = 0,
+ offsetX = 0,
+ offsetY = 0;
+ event = $.event.fix(orgEvent);
+ event.type = 'mousewheel';
+
+ // Old school scrollwheel delta
+ if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; }
+ if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; }
+ if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; }
+ if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
+
+ // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
+ if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
+ deltaX = deltaY * -1;
+ deltaY = 0;
+ }
+
+ // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
+ delta = deltaY === 0 ? deltaX : deltaY;
+
+ // New school wheel delta (wheel event)
+ if ( 'deltaY' in orgEvent ) {
+ deltaY = orgEvent.deltaY * -1;
+ delta = deltaY;
+ }
+ if ( 'deltaX' in orgEvent ) {
+ deltaX = orgEvent.deltaX;
+ if ( deltaY === 0 ) { delta = deltaX * -1; }
+ }
+
+ // No change actually happened, no reason to go any further
+ if ( deltaY === 0 && deltaX === 0 ) { return; }
+
+ // Need to convert lines and pages to pixels if we aren't already in pixels
+ // There are three delta modes:
+ // * deltaMode 0 is by pixels, nothing to do
+ // * deltaMode 1 is by lines
+ // * deltaMode 2 is by pages
+ if ( orgEvent.deltaMode === 1 ) {
+ var lineHeight = $.data(this, 'mousewheel-line-height');
+ delta *= lineHeight;
+ deltaY *= lineHeight;
+ deltaX *= lineHeight;
+ } else if ( orgEvent.deltaMode === 2 ) {
+ var pageHeight = $.data(this, 'mousewheel-page-height');
+ delta *= pageHeight;
+ deltaY *= pageHeight;
+ deltaX *= pageHeight;
+ }
+
+ // Store lowest absolute delta to normalize the delta values
+ absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
+
+ if ( !lowestDelta || absDelta < lowestDelta ) {
+ lowestDelta = absDelta;
+
+ // Adjust older deltas if necessary
+ if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
+ lowestDelta /= 40;
+ }
+ }
+
+ // Adjust older deltas if necessary
+ if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
+ // Divide all the things by 40!
+ delta /= 40;
+ deltaX /= 40;
+ deltaY /= 40;
+ }
+
+ // Get a whole, normalized value for the deltas
+ delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
+ deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
+ deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
+
+ // Normalise offsetX and offsetY properties
+ if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
+ var boundingRect = this.getBoundingClientRect();
+ offsetX = event.clientX - boundingRect.left;
+ offsetY = event.clientY - boundingRect.top;
+ }
+
+ // Add information to the event object
+ event.deltaX = deltaX;
+ event.deltaY = deltaY;
+ event.deltaFactor = lowestDelta;
+ event.offsetX = offsetX;
+ event.offsetY = offsetY;
+ // Go ahead and set deltaMode to 0 since we converted to pixels
+ // Although this is a little odd since we overwrite the deltaX/Y
+ // properties with normalized deltas.
+ event.deltaMode = 0;
+
+ // Add event and delta to the front of the arguments
+ args.unshift(event, delta, deltaX, deltaY);
+
+ // Clearout lowestDelta after sometime to better
+ // handle multiple device types that give different
+ // a different lowestDelta
+ // Ex: trackpad = 3 and mouse wheel = 120
+ if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
+ nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
+
+ return ($.event.dispatch || $.event.handle).apply(this, args);
+ }
+
+ function nullLowestDelta() {
+ lowestDelta = null;
+ }
+
+ function shouldAdjustOldDeltas(orgEvent, absDelta) {
+ // If this is an older event and the delta is divisable by 120,
+ // then we are assuming that the browser is treating this as an
+ // older mouse wheel event and that we should divide the deltas
+ // by 40 to try and get a more usable deltaFactor.
+ // Side note, this actually impacts the reported scroll distance
+ // in older browsers and can cause scrolling to be slower than native.
+ // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
+ return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
+ }
+
+})); \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.css b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.css
new file mode 100644
index 0000000..4ed981a
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.css
@@ -0,0 +1,568 @@
+.xdsoft_datetimepicker {
+ box-shadow: 0 5px 15px -5px rgba(0, 0, 0, 0.506);
+ background: #fff;
+ border-bottom: 1px solid #bbb;
+ border-left: 1px solid #ccc;
+ border-right: 1px solid #ccc;
+ border-top: 1px solid #ccc;
+ color: #333;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ padding: 8px;
+ padding-left: 0;
+ padding-top: 2px;
+ position: absolute;
+ z-index: 9999;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ display: none;
+}
+.xdsoft_datetimepicker.xdsoft_rtl {
+ padding: 8px 0 8px 8px;
+}
+
+.xdsoft_datetimepicker iframe {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 75px;
+ height: 210px;
+ background: transparent;
+ border: none;
+}
+
+/*For IE8 or lower*/
+.xdsoft_datetimepicker button {
+ border: none !important;
+}
+
+.xdsoft_noselect {
+ -webkit-touch-callout: none;
+ -webkit-user-select: none;
+ -khtml-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ -o-user-select: none;
+ user-select: none;
+}
+
+.xdsoft_noselect::selection { background: transparent }
+.xdsoft_noselect::-moz-selection { background: transparent }
+
+.xdsoft_datetimepicker.xdsoft_inline {
+ display: inline-block;
+ position: static;
+ box-shadow: none;
+}
+
+.xdsoft_datetimepicker * {
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ padding: 0;
+ margin: 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_datepicker, .xdsoft_datetimepicker .xdsoft_timepicker {
+ display: none;
+}
+
+.xdsoft_datetimepicker .xdsoft_datepicker.active, .xdsoft_datetimepicker .xdsoft_timepicker.active {
+ display: block;
+}
+
+.xdsoft_datetimepicker .xdsoft_datepicker {
+ width: 224px;
+ float: left;
+ margin-left: 8px;
+}
+.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_datepicker {
+ float: right;
+ margin-right: 8px;
+ margin-left: 0;
+}
+
+.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_datepicker {
+ width: 256px;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker {
+ width: 58px;
+ float: left;
+ text-align: center;
+ margin-left: 8px;
+ margin-top: 0;
+}
+.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker {
+ float: right;
+ margin-right: 8px;
+ margin-left: 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_datepicker.active+.xdsoft_timepicker {
+ margin-top: 8px;
+ margin-bottom: 3px
+}
+
+.xdsoft_datetimepicker .xdsoft_monthpicker {
+ position: relative;
+ text-align: center;
+}
+
+.xdsoft_datetimepicker .xdsoft_label i,
+.xdsoft_datetimepicker .xdsoft_prev,
+.xdsoft_datetimepicker .xdsoft_next,
+.xdsoft_datetimepicker .xdsoft_today_button {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6Q0NBRjI1NjM0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6Q0NBRjI1NjQ0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpDQ0FGMjU2MTQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpDQ0FGMjU2MjQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PoNEP54AAAIOSURBVHja7Jq9TsMwEMcxrZD4WpBYeKUCe+kTMCACHZh4BFfHO/AAIHZGFhYkBBsSEqxsLCAgXKhbXYOTxh9pfJVP+qutnZ5s/5Lz2Y5I03QhWji2GIcgAokWgfCxNvcOCCGKqiSqhUp0laHOne05vdEyGMfkdxJDVjgwDlEQgYQBgx+ULJaWSXXS6r/ER5FBVR8VfGftTKcITNs+a1XpcFoExREIDF14AVIFxgQUS+h520cdud6wNkC0UBw6BCO/HoCYwBhD8QCkQ/x1mwDyD4plh4D6DDV0TAGyo4HcawLIBBSLDkHeH0Mg2yVP3l4TQMZQDDsEOl/MgHQqhMNuE0D+oBh0CIr8MAKyazBH9WyBuKxDWgbXfjNf32TZ1KWm/Ap1oSk/R53UtQ5xTh3LUlMmT8gt6g51Q9p+SobxgJQ/qmsfZhWywGFSl0yBjCLJCMgXail3b7+rumdVJ2YRss4cN+r6qAHDkPWjPjdJCF4n9RmAD/V9A/Wp4NQassDjwlB6XBiCxcJQWmZZb8THFilfy/lfrTvLghq2TqTHrRMTKNJ0sIhdo15RT+RpyWwFdY96UZ/LdQKBGjcXpcc1AlSFEfLmouD+1knuxBDUVrvOBmoOC/rEcN7OQxKVeJTCiAdUzUJhA2Oez9QTkp72OTVcxDcXY8iKNkxGAJXmJCOQwOa6dhyXsOa6XwEGAKdeb5ET3rQdAAAAAElFTkSuQmCC);
+}
+
+.xdsoft_datetimepicker .xdsoft_label i {
+ opacity: 0.5;
+ background-position: -92px -19px;
+ display: inline-block;
+ width: 9px;
+ height: 20px;
+ vertical-align: middle;
+}
+
+.xdsoft_datetimepicker .xdsoft_prev {
+ float: left;
+ background-position: -20px 0;
+}
+.xdsoft_datetimepicker .xdsoft_today_button {
+ float: left;
+ background-position: -70px 0;
+ margin-left: 5px;
+}
+
+.xdsoft_datetimepicker .xdsoft_next {
+ float: right;
+ background-position: 0 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_next,
+.xdsoft_datetimepicker .xdsoft_prev ,
+.xdsoft_datetimepicker .xdsoft_today_button {
+ background-color: transparent;
+ background-repeat: no-repeat;
+ border: 0 none;
+ cursor: pointer;
+ display: block;
+ height: 30px;
+ opacity: 0.5;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
+ outline: medium none;
+ overflow: hidden;
+ padding: 0;
+ position: relative;
+ text-indent: 100%;
+ white-space: nowrap;
+ width: 20px;
+ min-width: 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev,
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_next {
+ float: none;
+ background-position: -40px -15px;
+ height: 15px;
+ width: 30px;
+ display: block;
+ margin-left: 14px;
+ margin-top: 7px;
+}
+.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker .xdsoft_prev,
+.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker .xdsoft_next {
+ float: none;
+ margin-left: 0;
+ margin-right: 14px;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev {
+ background-position: -40px 0;
+ margin-bottom: 7px;
+ margin-top: 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box {
+ height: 151px;
+ overflow: hidden;
+ border-bottom: 1px solid #ddd;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div {
+ background: #f5f5f5;
+ border-top: 1px solid #ddd;
+ color: #666;
+ font-size: 12px;
+ text-align: center;
+ border-collapse: collapse;
+ cursor: pointer;
+ border-bottom-width: 0;
+ height: 25px;
+ line-height: 25px;
+}
+
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div > div:first-child {
+ border-top-width: 0;
+}
+
+.xdsoft_datetimepicker .xdsoft_today_button:hover,
+.xdsoft_datetimepicker .xdsoft_next:hover,
+.xdsoft_datetimepicker .xdsoft_prev:hover {
+ opacity: 1;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
+}
+
+.xdsoft_datetimepicker .xdsoft_label {
+ display: inline;
+ position: relative;
+ z-index: 9999;
+ margin: 0;
+ padding: 5px 3px;
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: bold;
+ background-color: #fff;
+ float: left;
+ width: 182px;
+ text-align: center;
+ cursor: pointer;
+}
+
+.xdsoft_datetimepicker .xdsoft_label:hover>span {
+ text-decoration: underline;
+}
+
+.xdsoft_datetimepicker .xdsoft_label:hover i {
+ opacity: 1.0;
+}
+
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select {
+ border: 1px solid #ccc;
+ position: absolute;
+ right: 0;
+ top: 30px;
+ z-index: 101;
+ display: none;
+ background: #fff;
+ max-height: 160px;
+ overflow-y: hidden;
+}
+
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_monthselect{ right: -7px }
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_yearselect{ right: 2px }
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option:hover {
+ color: #fff;
+ background: #ff8000;
+}
+
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option {
+ padding: 2px 10px 2px 5px;
+ text-decoration: none !important;
+}
+
+.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option.xdsoft_current {
+ background: #33aaff;
+ box-shadow: #178fe5 0 1px 3px 0 inset;
+ color: #fff;
+ font-weight: 700;
+}
+
+.xdsoft_datetimepicker .xdsoft_month {
+ width: 100px;
+ text-align: right;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar {
+ clear: both;
+}
+
+.xdsoft_datetimepicker .xdsoft_year{
+ width: 48px;
+ margin-left: 5px;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar table {
+ border-collapse: collapse;
+ width: 100%;
+
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td > div {
+ padding-right: 5px;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar th {
+ height: 25px;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td,.xdsoft_datetimepicker .xdsoft_calendar th {
+ width: 14.2857142%;
+ background: #f5f5f5;
+ border: 1px solid #ddd;
+ color: #666;
+ font-size: 12px;
+ text-align: right;
+ vertical-align: middle;
+ padding: 0;
+ border-collapse: collapse;
+ cursor: pointer;
+ height: 25px;
+}
+.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_calendar td,.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_calendar th {
+ width: 12.5%;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar th {
+ background: #f1f1f1;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_today {
+ color: #33aaff;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_highlighted_default {
+ background: #ffe9d2;
+ box-shadow: #ffb871 0 1px 4px 0 inset;
+ color: #000;
+}
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_highlighted_mint {
+ background: #c1ffc9;
+ box-shadow: #00dd1c 0 1px 4px 0 inset;
+ color: #000;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_default,
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_current,
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_current {
+ background: #33aaff;
+ box-shadow: #178fe5 0 1px 3px 0 inset;
+ color: #fff;
+ font-weight: 700;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month,
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled,
+.xdsoft_datetimepicker .xdsoft_time_box >div >div.xdsoft_disabled {
+ opacity: 0.5;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
+ cursor: default;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month.xdsoft_disabled {
+ opacity: 0.2;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td:hover,
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div:hover {
+ color: #fff !important;
+ background: #ff8000 !important;
+ box-shadow: none !important;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_current.xdsoft_disabled:hover,
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box>div>div.xdsoft_current.xdsoft_disabled:hover {
+ background: #33aaff !important;
+ box-shadow: #178fe5 0 1px 3px 0 inset !important;
+ color: #fff !important;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled:hover,
+.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_disabled:hover {
+ color: inherit !important;
+ background: inherit !important;
+ box-shadow: inherit !important;
+}
+
+.xdsoft_datetimepicker .xdsoft_calendar th {
+ font-weight: 700;
+ text-align: center;
+ color: #999;
+ cursor: default;
+}
+
+.xdsoft_datetimepicker .xdsoft_copyright {
+ color: #ccc !important;
+ font-size: 10px;
+ clear: both;
+ float: none;
+ margin-left: 8px;
+}
+
+.xdsoft_datetimepicker .xdsoft_copyright a { color: #eee !important }
+.xdsoft_datetimepicker .xdsoft_copyright a:hover { color: #aaa !important }
+
+.xdsoft_time_box {
+ position: relative;
+ border: 1px solid #ccc;
+}
+.xdsoft_scrollbar >.xdsoft_scroller {
+ background: #ccc !important;
+ height: 20px;
+ border-radius: 3px;
+}
+.xdsoft_scrollbar {
+ position: absolute;
+ width: 7px;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ cursor: pointer;
+}
+.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_scrollbar {
+ left: 0;
+ right: auto;
+}
+.xdsoft_scroller_box {
+ position: relative;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark {
+ box-shadow: 0 5px 15px -5px rgba(255, 255, 255, 0.506);
+ background: #000;
+ border-bottom: 1px solid #444;
+ border-left: 1px solid #333;
+ border-right: 1px solid #333;
+ border-top: 1px solid #333;
+ color: #ccc;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box {
+ border-bottom: 1px solid #222;
+}
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div {
+ background: #0a0a0a;
+ border-top: 1px solid #222;
+ color: #999;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label {
+ background-color: #000;
+}
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select {
+ border: 1px solid #333;
+ background: #000;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select > div > .xdsoft_option:hover {
+ color: #000;
+ background: #007fff;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select > div > .xdsoft_option.xdsoft_current {
+ background: #cc5500;
+ box-shadow: #b03e00 0 1px 3px 0 inset;
+ color: #000;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label i,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_prev,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_next,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_today_button {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUExQUUzOTA0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUExQUUzOTE0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQTFBRTM4RTQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQTFBRTM4RjQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp0VxGEAAAIASURBVHja7JrNSgMxEMebtgh+3MSLr1T1Xn2CHoSKB08+QmR8Bx9A8e7RixdB9CKCoNdexIugxFlJa7rNZneTbLIpM/CnNLsdMvNjM8l0mRCiQ9Ye61IKCAgZAUnH+mU3MMZaHYChBnJUDzWOFZdVfc5+ZFLbrWDeXPwbxIqrLLfaeS0hEBVGIRQCEiZoHQwtlGSByCCdYBl8g8egTTAWoKQMRBRBcZxYlhzhKegqMOageErsCHVkk3hXIFooDgHB1KkHIHVgzKB4ADJQ/A1jAFmAYhkQqA5TOBtocrKrgXwQA8gcFIuAIO8sQSA7hidvPwaQGZSaAYHOUWJABhWWw2EMIH9QagQERU4SArJXo0ZZL18uvaxejXt/Em8xjVBXmvFr1KVm/AJ10tRe2XnraNqaJvKE3KHuUbfK1E+VHB0q40/y3sdQSxY4FHWeKJCunP8UyDdqJZenT3ntVV5jIYCAh20vT7ioP8tpf6E2lfEMwERe+whV1MHjwZB7PBiCxcGQWwKZKD62lfGNnP/1poFAA60T7rF1UgcKd2id3KDeUS+oLWV8DfWAepOfq00CgQabi9zjcgJVYVD7PVzQUAUGAQkbNJTBICDhgwYTjDYD6XeW08ZKh+A4pYkzenOxXUbvZcWz7E8ykRMnIHGX1XPl+1m2vPYpL+2qdb8CDAARlKFEz/ZVkAAAAABJRU5ErkJggg==);
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
+ background: #0a0a0a;
+ border: 1px solid #222;
+ color: #999;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
+ background: #0e0e0e;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_today {
+ color: #cc5500;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_highlighted_default {
+ background: #ffe9d2;
+ box-shadow: #ffb871 0 1px 4px 0 inset;
+ color:#000;
+}
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_highlighted_mint {
+ background: #c1ffc9;
+ box-shadow: #00dd1c 0 1px 4px 0 inset;
+ color:#000;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_default,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_current,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_current {
+ background: #cc5500;
+ box-shadow: #b03e00 0 1px 3px 0 inset;
+ color: #000;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td:hover,
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div:hover {
+ color: #000 !important;
+ background: #007fff !important;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
+ color: #666;
+}
+
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_copyright { color: #333 !important }
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_copyright a { color: #111 !important }
+.xdsoft_datetimepicker.xdsoft_dark .xdsoft_copyright a:hover { color: #555 !important }
+
+.xdsoft_dark .xdsoft_time_box {
+ border: 1px solid #333;
+}
+
+.xdsoft_dark .xdsoft_scrollbar >.xdsoft_scroller {
+ background: #333 !important;
+}
+.xdsoft_datetimepicker .xdsoft_save_selected {
+ display: block;
+ border: 1px solid #dddddd !important;
+ margin-top: 5px;
+ width: 100%;
+ color: #454551;
+ font-size: 13px;
+}
+.xdsoft_datetimepicker .blue-gradient-button {
+ font-family: "museo-sans", "Book Antiqua", sans-serif;
+ font-size: 12px;
+ font-weight: 300;
+ color: #82878c;
+ height: 28px;
+ position: relative;
+ padding: 4px 17px 4px 33px;
+ border: 1px solid #d7d8da;
+ background: -moz-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* FF3.6+ */
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(73%, #f4f8fa));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* Chrome10+,Safari5.1+ */
+ background: -o-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* Opera 11.10+ */
+ background: -ms-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* IE10+ */
+ background: linear-gradient(to bottom, #fff 0%, #f4f8fa 73%);
+ /* W3C */
+ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fff', endColorstr='#f4f8fa',GradientType=0 );
+/* IE6-9 */
+}
+.xdsoft_datetimepicker .blue-gradient-button:hover, .xdsoft_datetimepicker .blue-gradient-button:focus, .xdsoft_datetimepicker .blue-gradient-button:hover span, .xdsoft_datetimepicker .blue-gradient-button:focus span {
+ color: #454551;
+ background: -moz-linear-gradient(top, #f4f8fa 0%, #FFF 73%);
+ /* FF3.6+ */
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f4f8fa), color-stop(73%, #FFF));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #f4f8fa 0%, #FFF 73%);
+ /* Chrome10+,Safari5.1+ */
+ background: -o-linear-gradient(top, #f4f8fa 0%, #FFF 73%);
+ /* Opera 11.10+ */
+ background: -ms-linear-gradient(top, #f4f8fa 0%, #FFF 73%);
+ /* IE10+ */
+ background: linear-gradient(to bottom, #f4f8fa 0%, #FFF 73%);
+ /* W3C */
+ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f8fa', endColorstr='#FFF',GradientType=0 );
+ /* IE6-9 */
+}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.js b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.js
new file mode 100644
index 0000000..7dab44e
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/dtpick/jquery.datetimepicker.js
@@ -0,0 +1,2718 @@
+/**
+ * @preserve jQuery DateTimePicker
+ * @homepage http://xdsoft.net/jqplugins/datetimepicker/
+ * @author Chupurnov Valeriy (<chupurnov@gmail.com>)
+ */
+
+/**
+ * @param {jQuery} $
+ */
+var datetimepickerFactory = function ($) {
+ 'use strict';
+
+ var default_options = {
+ i18n: {
+ ar: { // Arabic
+ months: [
+ "كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
+ ],
+ dayOfWeekShort: [
+ "ن", "ث", "ع", "خ", "ج", "س", "ح"
+ ],
+ dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
+ },
+ ro: { // Romanian
+ months: [
+ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
+ ],
+ dayOfWeekShort: [
+ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
+ ],
+ dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
+ },
+ id: { // Indonesian
+ months: [
+ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
+ ],
+ dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
+ },
+ is: { // Icelandic
+ months: [
+ "Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
+ ],
+ dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
+ },
+ bg: { // Bulgarian
+ months: [
+ "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
+ ],
+ dayOfWeekShort: [
+ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
+ },
+ fa: { // Persian/Farsi
+ months: [
+ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
+ ],
+ dayOfWeekShort: [
+ 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
+ ],
+ dayOfWeek: ["یک‌شنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه", "شنبه", "یک‌شنبه"]
+ },
+ ru: { // Russian
+ months: [
+ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
+ ],
+ dayOfWeekShort: [
+ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
+ },
+ uk: { // Ukrainian
+ months: [
+ 'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
+ ],
+ dayOfWeekShort: [
+ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
+ },
+ en: { // English
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ el: { // Ελληνικά
+ months: [
+ "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
+ ],
+ dayOfWeekShort: [
+ "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
+ ],
+ dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
+ },
+ de: { // German
+ months: [
+ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
+ ],
+ dayOfWeekShort: [
+ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
+ ],
+ dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
+ },
+ nl: { // Dutch
+ months: [
+ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
+ ],
+ dayOfWeekShort: [
+ "zo", "ma", "di", "wo", "do", "vr", "za"
+ ],
+ dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
+ },
+ tr: { // Turkish
+ months: [
+ "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
+ ],
+ dayOfWeekShort: [
+ "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
+ ],
+ dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
+ },
+ fr: { //French
+ months: [
+ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
+ ],
+ dayOfWeekShort: [
+ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
+ ],
+ dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
+ },
+ es: { // Spanish
+ months: [
+ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
+ },
+ th: { // Thai
+ months: [
+ 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
+ ],
+ dayOfWeekShort: [
+ 'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
+ ],
+ dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
+ },
+ pl: { // Polish
+ months: [
+ "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
+ ],
+ dayOfWeekShort: [
+ "nd", "pn", "wt", "śr", "cz", "pt", "sb"
+ ],
+ dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
+ },
+ pt: { // Portuguese
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ ch: { // Simplified Chinese
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ]
+ },
+ se: { // Swedish
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ]
+ },
+ km: { // Khmer (ភាសាខ្មែរ)
+ months: [
+ "មករា​", "កុម្ភៈ", "មិនា​", "មេសា​", "ឧសភា​", "មិថុនា​", "កក្កដា​", "សីហា​", "កញ្ញា​", "តុលា​", "វិច្ឆិកា", "ធ្នូ​"
+ ],
+ dayOfWeekShort: ["អាទិ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហ​​", "សុក្រ​", "សៅរ៍"],
+ dayOfWeek: ["អាទិត្យ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហស្បតិ៍​", "សុក្រ​", "សៅរ៍"]
+ },
+ kr: { // Korean
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ it: { // Italian
+ months: [
+ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
+ },
+ da: { // Dansk
+ months: [
+ "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
+ },
+ no: { // Norwegian
+ months: [
+ "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
+ },
+ ja: { // Japanese
+ months: [
+ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
+ ],
+ dayOfWeekShort: [
+ "日", "月", "火", "水", "木", "金", "土"
+ ],
+ dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
+ },
+ vi: { // Vietnamese
+ months: [
+ "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
+ ],
+ dayOfWeekShort: [
+ "CN", "T2", "T3", "T4", "T5", "T6", "T7"
+ ],
+ dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
+ },
+ sl: { // Slovenščina
+ months: [
+ "Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
+ ],
+ dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
+ },
+ cs: { // Čeština
+ months: [
+ "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Út", "St", "Čt", "Pá", "So"
+ ]
+ },
+ hu: { // Hungarian
+ months: [
+ "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
+ ],
+ dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
+ },
+ az: { //Azerbaijanian (Azeri)
+ months: [
+ "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
+ ],
+ dayOfWeekShort: [
+ "B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
+ ],
+ dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
+ },
+ bs: { //Bosanski
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ca: { //Català
+ months: [
+ "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
+ ],
+ dayOfWeekShort: [
+ "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
+ ],
+ dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
+ },
+ 'en-GB': { //English (British)
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ et: { //"Eesti"
+ months: [
+ "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
+ ],
+ dayOfWeekShort: [
+ "P", "E", "T", "K", "N", "R", "L"
+ ],
+ dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
+ },
+ eu: { //Euskara
+ months: [
+ "Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
+ ],
+ dayOfWeekShort: [
+ "Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
+ ],
+ dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
+ },
+ fi: { //Finnish (Suomi)
+ months: [
+ "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
+ ],
+ dayOfWeekShort: [
+ "Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
+ ],
+ dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
+ },
+ gl: { //Galego
+ months: [
+ "Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
+ },
+ hr: { //Hrvatski
+ months: [
+ "Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ko: { //Korean (한국어)
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ lt: { //Lithuanian (lietuvių)
+ months: [
+ "Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
+ ],
+ dayOfWeekShort: [
+ "Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
+ ],
+ dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
+ },
+ lv: { //Latvian (Latviešu)
+ months: [
+ "Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
+ ],
+ dayOfWeekShort: [
+ "Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
+ ],
+ dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
+ },
+ mk: { //Macedonian (Македонски)
+ months: [
+ "јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "вто", "сре", "чет", "пет", "саб"
+ ],
+ dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
+ },
+ mn: { //Mongolian (Монгол)
+ months: [
+ "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
+ ],
+ dayOfWeekShort: [
+ "Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
+ ],
+ dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
+ },
+ 'pt-BR': { //Português(Brasil)
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ sk: { //Slovenčina
+ months: [
+ "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Ut", "St", "Št", "Pi", "So"
+ ],
+ dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
+ },
+ sq: { //Albanian (Shqip)
+ months: [
+ "Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
+ ],
+ dayOfWeekShort: [
+ "Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
+ ],
+ dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
+ },
+ 'sr-YU': { //Serbian (Srpski)
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
+ },
+ sr: { //Serbian Cyrillic (Српски)
+ months: [
+ "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "уто", "сре", "чет", "пет", "суб"
+ ],
+ dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
+ },
+ sv: { //Svenska
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ],
+ dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
+ },
+ 'zh-TW': { //Traditional Chinese (繁體中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ zh: { //Simplified Chinese (简体中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ ug:{ // Uyghur(ئۇيغۇرچە)
+ months: [
+ "1-ئاي","2-ئاي","3-ئاي","4-ئاي","5-ئاي","6-ئاي","7-ئاي","8-ئاي","9-ئاي","10-ئاي","11-ئاي","12-ئاي"
+ ],
+ dayOfWeek: [
+ "يەكشەنبە", "دۈشەنبە","سەيشەنبە","چارشەنبە","پەيشەنبە","جۈمە","شەنبە"
+ ]
+ },
+ he: { //Hebrew (עברית)
+ months: [
+ 'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
+ ],
+ dayOfWeekShort: [
+ 'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
+ ],
+ dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
+ },
+ hy: { // Armenian
+ months: [
+ "Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
+ ],
+ dayOfWeekShort: [
+ "Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
+ ],
+ dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
+ },
+ kg: { // Kyrgyz
+ months: [
+ 'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
+ ],
+ dayOfWeekShort: [
+ "Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
+ ],
+ dayOfWeek: [
+ "Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
+ ]
+ },
+ rm: { // Romansh
+ months: [
+ "Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
+ ],
+ dayOfWeek: [
+ "Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
+ ]
+ },
+ ka: { // Georgian
+ months: [
+ 'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
+ ],
+ dayOfWeekShort: [
+ "კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
+ ],
+ dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
+ },
+ kk: { // Kazakh
+ months: [
+ 'Қаңтар', 'Ақпан', 'Наурыз', 'Сәуір', 'Мамыр', 'Маусым', 'Шілде', 'Тамыз', 'Қыркүйек', 'Қазан', 'Қараша', 'Желтоқсан'
+ ],
+ dayOfWeekShort: [
+ "Жк", "Дс", "Сс", "Ср", "Бс", "Жм", "Сб"
+ ],
+ dayOfWeek: ["Жексенбі", "Дүйсенбі", "Сейсенбі", "Сәрсенбі", "Бейсенбі", "Жұма", "Сенбі"]
+ }
+ },
+
+ ownerDocument: document,
+ contentWindow: window,
+
+ value: '',
+ rtl: false,
+
+ format: 'Y/m/d H:i',
+ formatTime: 'H:i',
+ formatDate: 'Y/m/d',
+
+ startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
+ step: 60,
+ monthChangeSpinner: true,
+
+ closeOnDateSelect: false,
+ closeOnTimeSelect: true,
+ closeOnWithoutClick: true,
+ closeOnInputClick: true,
+ openOnFocus: true,
+
+ timepicker: true,
+ datepicker: true,
+ weeks: false,
+
+ defaultTime: false, // use formatTime format (ex. '10:00' for formatTime: 'H:i')
+ defaultDate: false, // use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')
+
+ minDate: false,
+ maxDate: false,
+ minTime: false,
+ maxTime: false,
+ minDateTime: false,
+ maxDateTime: false,
+
+ allowTimes: [],
+ opened: false,
+ initTime: true,
+ inline: false,
+ theme: '',
+ touchMovedThreshold: 5,
+
+ onSelectDate: function () {},
+ onSelectTime: function () {},
+ onChangeMonth: function () {},
+ onGetWeekOfYear: function () {},
+ onChangeYear: function () {},
+ onChangeDateTime: function () {},
+ onShow: function () {},
+ onClose: function () {},
+ onGenerate: function () {},
+
+ withoutCopyright: true,
+ inverseButton: false,
+ hours12: false,
+ next: 'xdsoft_next',
+ prev : 'xdsoft_prev',
+ dayOfWeekStart: 0,
+ parentID: 'body',
+ timeHeightInTimePicker: 25,
+ timepickerScrollbar: true,
+ todayButton: true,
+ prevButton: true,
+ nextButton: true,
+ defaultSelect: true,
+
+ scrollMonth: true,
+ scrollTime: true,
+ scrollInput: true,
+
+ lazyInit: false,
+ mask: false,
+ validateOnBlur: true,
+ allowBlank: true,
+ yearStart: 1950,
+ yearEnd: 2050,
+ monthStart: 0,
+ monthEnd: 11,
+ style: '',
+ id: '',
+ fixed: false,
+ roundTime: 'round', // ceil, floor
+ className: '',
+ weekends: [],
+ highlightedDates: [],
+ highlightedPeriods: [],
+ allowDates : [],
+ allowDateRe : null,
+ disabledDates : [],
+ disabledWeekDays: [],
+ yearOffset: 0,
+ beforeShowDay: null,
+
+ enterLikeTab: true,
+ showApplyButton: false,
+ insideParent: false,
+ };
+
+ var dateHelper = null,
+ defaultDateHelper = null,
+ globalLocaleDefault = 'en',
+ globalLocale = 'en';
+
+ var dateFormatterOptionsDefault = {
+ meridiem: ['AM', 'PM']
+ };
+
+ var initDateFormatter = function(){
+ var locale = default_options.i18n[globalLocale],
+ opts = {
+ days: locale.dayOfWeek,
+ daysShort: locale.dayOfWeekShort,
+ months: locale.months,
+ monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) })
+ };
+
+ if (typeof DateFormatter === 'function') {
+ dateHelper = defaultDateHelper = new DateFormatter({
+ dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
+ });
+ }
+ };
+
+ var dateFormatters = {
+ moment: {
+ default_options:{
+ format: 'YYYY/MM/DD HH:mm',
+ formatDate: 'YYYY/MM/DD',
+ formatTime: 'HH:mm',
+ },
+ formatter: {
+ parseDate: function (date, format) {
+ if(isFormatStandard(format)){
+ return defaultDateHelper.parseDate(date, format);
+ }
+ var d = moment(date, format);
+ return d.isValid() ? d.toDate() : false;
+ },
+
+ formatDate: function (date, format) {
+ if(isFormatStandard(format)){
+ return defaultDateHelper.formatDate(date, format);
+ }
+ return moment(date).format(format);
+ },
+
+ formatMask: function(format){
+ return format
+ .replace(/Y{4}/g, '9999')
+ .replace(/Y{2}/g, '99')
+ .replace(/M{2}/g, '19')
+ .replace(/D{2}/g, '39')
+ .replace(/H{2}/g, '29')
+ .replace(/m{2}/g, '59')
+ .replace(/s{2}/g, '59');
+ },
+ }
+ }
+ }
+
+ // for locale settings
+ $.datetimepicker = {
+ setLocale: function(locale){
+ var newLocale = default_options.i18n[locale] ? locale : globalLocaleDefault;
+ if (globalLocale !== newLocale) {
+ globalLocale = newLocale;
+ // reinit date formatter
+ initDateFormatter();
+ }
+ },
+
+ setDateFormatter: function(dateFormatter) {
+ if(typeof dateFormatter === 'string' && dateFormatters.hasOwnProperty(dateFormatter)){
+ var df = dateFormatters[dateFormatter];
+ $.extend(default_options, df.default_options);
+ dateHelper = df.formatter;
+ }
+ else {
+ dateHelper = dateFormatter;
+ }
+ },
+ };
+
+ var standardFormats = {
+ RFC_2822: 'D, d M Y H:i:s O',
+ ATOM: 'Y-m-d\TH:i:sP',
+ ISO_8601: 'Y-m-d\TH:i:sO',
+ RFC_822: 'D, d M y H:i:s O',
+ RFC_850: 'l, d-M-y H:i:s T',
+ RFC_1036: 'D, d M y H:i:s O',
+ RFC_1123: 'D, d M Y H:i:s O',
+ RSS: 'D, d M Y H:i:s O',
+ W3C: 'Y-m-d\TH:i:sP'
+ }
+
+ var isFormatStandard = function(format){
+ return Object.values(standardFormats).indexOf(format) === -1 ? false : true;
+ }
+
+ $.extend($.datetimepicker, standardFormats);
+
+ // first init date formatter
+ initDateFormatter();
+
+ // fix for ie8
+ if (!window.getComputedStyle) {
+ window.getComputedStyle = function (el) {
+ this.el = el;
+ this.getPropertyValue = function (prop) {
+ var re = /(-([a-z]))/g;
+ if (prop === 'float') {
+ prop = 'styleFloat';
+ }
+ if (re.test(prop)) {
+ prop = prop.replace(re, function (a, b, c) {
+ return c.toUpperCase();
+ });
+ }
+ return el.currentStyle[prop] || null;
+ };
+ return this;
+ };
+ }
+ if (!Array.prototype.indexOf) {
+ Array.prototype.indexOf = function (obj, start) {
+ var i, j;
+ for (i = (start || 0), j = this.length; i < j; i += 1) {
+ if (this[i] === obj) { return i; }
+ }
+ return -1;
+ };
+ }
+
+ Date.prototype.countDaysInMonth = function () {
+ return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
+ };
+
+ $.fn.xdsoftScroller = function (options, percent) {
+ return this.each(function () {
+ var timeboxparent = $(this),
+ pointerEventToXY = function (e) {
+ var out = {x: 0, y: 0},
+ touch;
+ if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
+ touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
+ out.x = touch.clientX;
+ out.y = touch.clientY;
+ } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
+ out.x = e.clientX;
+ out.y = e.clientY;
+ }
+ return out;
+ },
+ getWheelDelta = function (e) {
+ var deltaY = 0;
+
+ if ('detail' in e) { deltaY = e.detail; }
+ if ('wheelDelta' in e) { deltaY = -e.wheelDelta / 120; }
+ if ('wheelDeltaY' in e) { deltaY = -e.wheelDeltaY / 120; }
+ if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) { deltaY = 0; }
+
+ deltaY *= 10;
+
+ if ('deltaY' in e) { deltaY = e.deltaY; }
+
+ if (deltaY && e.deltaMode) {
+ if (e.deltaMode === 1) {
+ deltaY *= 40;
+ } else {
+ deltaY *= 800;
+ }
+ }
+
+ return deltaY;
+ },
+ timebox,
+ timeboxTop = 0,
+ parentHeight,
+ height,
+ scrollbar,
+ scroller,
+ maximumOffset = 100,
+ start = false,
+ startY = 0,
+ startTop = 0,
+ h1 = 0,
+ touchStart = false,
+ startTopScroll = 0,
+ calcOffset = function () {};
+
+ if (percent === 'hide') {
+ timeboxparent.find('.xdsoft_scrollbar').hide();
+ return;
+ }
+
+ if (!$(this).hasClass('xdsoft_scroller_box')) {
+ timebox = timeboxparent.children().eq(0);
+ timeboxTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ scrollbar = $('<div class="xdsoft_scrollbar"></div>');
+ scroller = $('<div class="xdsoft_scroller"></div>');
+ scrollbar.append(scroller);
+
+ timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
+ calcOffset = function calcOffset(event) {
+ var offset = pointerEventToXY(event).y - startY + startTopScroll;
+ if (offset < 0) {
+ offset = 0;
+ }
+ if (offset + scroller[0].offsetHeight > h1) {
+ offset = h1 - scroller[0].offsetHeight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
+ };
+
+ scroller
+ .on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ }
+
+ startY = pointerEventToXY(event).y;
+ startTopScroll = parseInt(scroller.css('marginTop'), 10);
+ h1 = scrollbar[0].offsetHeight;
+
+ if (event.type === 'mousedown' || event.type === 'touchstart') {
+ if (options.ownerDocument) {
+ $(options.ownerDocument.body).addClass('xdsoft_noselect');
+ }
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
+ $([options.ownerDocument.body, options.contentWindow]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
+ .off('mousemove.xdsoft_scroller', calcOffset)
+ .removeClass('xdsoft_noselect');
+ });
+ $(options.ownerDocument.body).on('mousemove.xdsoft_scroller', calcOffset);
+ } else {
+ touchStart = true;
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ })
+ .on('touchmove', function (event) {
+ if (touchStart) {
+ event.preventDefault();
+ calcOffset(event);
+ }
+ })
+ .on('touchend touchcancel', function () {
+ touchStart = false;
+ startTopScroll = 0;
+ });
+
+ timeboxparent
+ .on('scroll_element.xdsoft_scroller', function (event, percentage) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
+ }
+ percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;
+ timeboxTop = parseFloat(Math.abs((timebox[0].offsetHeight - parentHeight) * percentage).toFixed(4));
+
+ scroller.css('marginTop', maximumOffset * percentage);
+ timebox.css('marginTop', -timeboxTop);
+ })
+ .on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
+ var percent, sh;
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ percent = parentHeight / height;
+ sh = percent * scrollbar[0].offsetHeight;
+ if (percent > 1) {
+ scroller.hide();
+ } else {
+ scroller.show();
+ scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
+ maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
+ if (noTriggerScroll !== true) {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || timeboxTop / (height - parentHeight)]);
+ }
+ }
+ });
+
+ timeboxparent.on('mousewheel', function (event) {
+ var deltaY = getWheelDelta(event.originalEvent);
+ var top = Math.max(0, timeboxTop - deltaY);
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
+ event.stopPropagation();
+ return false;
+ });
+
+ timeboxparent.on('touchstart', function (event) {
+ start = pointerEventToXY(event);
+ startTop = timeboxTop;
+ });
+
+ timeboxparent.on('touchmove', function (event) {
+ if (start) {
+ event.preventDefault();
+ var coord = pointerEventToXY(event);
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
+ }
+ });
+
+ timeboxparent.on('touchend touchcancel', function () {
+ start = false;
+ startTop = 0;
+ });
+ }
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ });
+ };
+
+ $.fn.datetimepicker = function (opt, opt2) {
+ var result = this,
+ KEY0 = 48,
+ KEY9 = 57,
+ _KEY0 = 96,
+ _KEY9 = 105,
+ CTRLKEY = 17,
+ CMDKEY = 91,
+ DEL = 46,
+ ENTER = 13,
+ ESC = 27,
+ BACKSPACE = 8,
+ ARROWLEFT = 37,
+ ARROWUP = 38,
+ ARROWRIGHT = 39,
+ ARROWDOWN = 40,
+ TAB = 9,
+ F5 = 116,
+ AKEY = 65,
+ CKEY = 67,
+ VKEY = 86,
+ ZKEY = 90,
+ YKEY = 89,
+ ctrlDown = false,
+ cmdDown = false,
+ options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),
+
+ lazyInitTimer = 0,
+ createDateTimePicker,
+ destroyDateTimePicker,
+
+ lazyInit = function (input) {
+ input
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
+ if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
+ return;
+ }
+ clearTimeout(lazyInitTimer);
+ lazyInitTimer = setTimeout(function () {
+
+ if (!input.data('xdsoft_datetimepicker')) {
+ createDateTimePicker(input);
+ }
+ input
+ .off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
+ .trigger('open.xdsoft');
+ }, 100);
+ });
+ };
+
+ createDateTimePicker = function (input) {
+ var datetimepicker = $('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'),
+ xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
+ datepicker = $('<div class="xdsoft_datepicker active"></div>'),
+ month_picker = $('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button>' +
+ '<div class="xdsoft_label xdsoft_month"><span></span><i></i></div>' +
+ '<div class="xdsoft_label xdsoft_year"><span></span><i></i></div>' +
+ '<button type="button" class="xdsoft_next"></button></div>'),
+ calendar = $('<div class="xdsoft_calendar"></div>'),
+ timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
+ timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
+ timebox = $('<div class="xdsoft_time_variant"></div>'),
+ applyButton = $('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'),
+
+ monthselect = $('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
+ yearselect = $('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'),
+ triggerAfterOpen = false,
+ XDSoft_datetime,
+
+ xchangeTimer,
+ timerclick,
+ current_time_index,
+ setPos,
+ timer = 0,
+ _xdsoft_datetime,
+ forEachAncestorOf;
+
+ if (options.id) {
+ datetimepicker.attr('id', options.id);
+ }
+ if (options.style) {
+ datetimepicker.attr('style', options.style);
+ }
+ if (options.weeks) {
+ datetimepicker.addClass('xdsoft_showweeks');
+ }
+ if (options.rtl) {
+ datetimepicker.addClass('xdsoft_rtl');
+ }
+
+ datetimepicker.addClass('xdsoft_' + options.theme);
+ datetimepicker.addClass(options.className);
+
+ month_picker
+ .find('.xdsoft_month span')
+ .after(monthselect);
+ month_picker
+ .find('.xdsoft_year span')
+ .after(yearselect);
+
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .on('touchstart mousedown.xdsoft', function (event) {
+ var select = $(this).find('.xdsoft_select').eq(0),
+ val = 0,
+ top = 0,
+ visible = select.is(':visible'),
+ items,
+ i;
+
+ month_picker
+ .find('.xdsoft_select')
+ .hide();
+ if (_xdsoft_datetime.currentTime) {
+ val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
+ }
+
+ select[visible ? 'hide' : 'show']();
+ for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
+ if (items.eq(i).data('value') === val) {
+ break;
+ } else {
+ top += items[0].offsetHeight;
+ }
+ }
+
+ select.xdsoftScroller(options, top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
+ event.stopPropagation();
+ return false;
+ });
+
+ var handleTouchMoved = function (event) {
+ var evt = event.originalEvent;
+ var touchPosition = evt.touches ? evt.touches[0] : evt;
+ this.touchStartPosition = this.touchStartPosition || touchPosition;
+ var xMovement = Math.abs(this.touchStartPosition.clientX - touchPosition.clientX);
+ var yMovement = Math.abs(this.touchStartPosition.clientY - touchPosition.clientY);
+ var distance = Math.sqrt(xMovement * xMovement + yMovement * yMovement);
+ if(distance > options.touchMovedThreshold) {
+ this.touchMoved = true;
+ }
+ }
+
+ month_picker
+ .find('.xdsoft_select')
+ .xdsoftScroller(options)
+ .on('touchstart mousedown.xdsoft', function (event) {
+ var evt = event.originalEvent;
+ this.touchMoved = false;
+ this.touchStartPosition = evt.touches ? evt.touches[0] : evt;
+ event.stopPropagation();
+ event.preventDefault();
+ })
+ .on('touchmove', '.xdsoft_option', handleTouchMoved)
+ .on('touchend mousedown.xdsoft', '.xdsoft_option', function () {
+ if (!this.touchMoved) {
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var year = _xdsoft_datetime.currentTime.getFullYear();
+ if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
+ _xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
+ }
+
+ $(this).parent().parent().hide();
+
+ datetimepicker.trigger('xchange.xdsoft');
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ }
+ });
+
+ datetimepicker.getValue = function () {
+ return _xdsoft_datetime.getCurrentTime();
+ };
+
+ datetimepicker.setOptions = function (_options) {
+ var highlightedDates = {};
+
+ options = $.extend(true, {}, options, _options);
+
+ if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
+ options.allowTimes = $.extend(true, [], _options.allowTimes);
+ }
+
+ if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
+ options.weekends = $.extend(true, [], _options.weekends);
+ }
+
+ if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
+ options.allowDates = $.extend(true, [], _options.allowDates);
+ }
+
+ if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
+ options.allowDateRe = new RegExp(_options.allowDateRe);
+ }
+
+ if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
+ $.each(_options.highlightedDates, function (index, value) {
+ var splitData = $.map(value.split(','), $.trim),
+ exDesc,
+ hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
+ keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
+ highlightedDates = $.extend(true, [], options.highlightedDates);
+ $.each(_options.highlightedPeriods, function (index, value) {
+ var dateTest, // start date
+ dateEnd,
+ desc,
+ hDate,
+ keyDate,
+ exDesc,
+ style;
+ if ($.isArray(value)) {
+ dateTest = value[0];
+ dateEnd = value[1];
+ desc = value[2];
+ style = value[3];
+ }
+ else {
+ var splitData = $.map(value.split(','), $.trim);
+ dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
+ dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
+ desc = splitData[2];
+ style = splitData[3];
+ }
+
+ while (dateTest <= dateEnd) {
+ hDate = new HighlightedDate(dateTest, desc, style);
+ keyDate = dateHelper.formatDate(dateTest, options.formatDate);
+ dateTest.setDate(dateTest.getDate() + 1);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
+ options.disabledDates = $.extend(true, [], _options.disabledDates);
+ }
+
+ if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
+ options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
+ }
+
+ if ((options.open || options.opened) && (!options.inline)) {
+ input.trigger('open.xdsoft');
+ }
+
+ if (options.inline) {
+ triggerAfterOpen = true;
+ datetimepicker.addClass('xdsoft_inline');
+ input.after(datetimepicker).hide();
+ }
+
+ if (options.inverseButton) {
+ options.next = 'xdsoft_prev';
+ options.prev = 'xdsoft_next';
+ }
+
+ if (options.datepicker) {
+ datepicker.addClass('active');
+ } else {
+ datepicker.removeClass('active');
+ }
+
+ if (options.timepicker) {
+ timepicker.addClass('active');
+ } else {
+ timepicker.removeClass('active');
+ }
+
+ if (options.value) {
+ _xdsoft_datetime.setCurrentTime(options.value);
+ if (input && input.val) {
+ input.val(_xdsoft_datetime.str);
+ }
+ }
+
+ if (isNaN(options.dayOfWeekStart)) {
+ options.dayOfWeekStart = 0;
+ } else {
+ options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
+ }
+
+ if (!options.timepickerScrollbar) {
+ timeboxparent.xdsoftScroller(options, 'hide');
+ }
+
+ if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
+ options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
+ }
+
+ if (options.maxDate && /^[\+\-](.*)$/.test(options.maxDate)) {
+ options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
+ }
+
+ if (options.minDateTime && /^\+(.*)$/.test(options.minDateTime)) {
+ options.minDateTime = _xdsoft_datetime.strToDateTime(options.minDateTime).dateFormat(options.formatDate);
+ }
+
+ if (options.maxDateTime && /^\+(.*)$/.test(options.maxDateTime)) {
+ options.maxDateTime = _xdsoft_datetime.strToDateTime(options.maxDateTime).dateFormat(options.formatDate);
+ }
+
+ applyButton.toggle(options.showApplyButton);
+
+ month_picker
+ .find('.xdsoft_today_button')
+ .css('visibility', !options.todayButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.prev)
+ .css('visibility', !options.prevButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.next)
+ .css('visibility', !options.nextButton ? 'hidden' : 'visible');
+
+ setMask(options);
+
+ if (options.validateOnBlur) {
+ input
+ .off('blur.xdsoft')
+ .on('blur.xdsoft', function () {
+ if (options.allowBlank && (!$.trim($(this).val()).length ||
+ (typeof options.mask === "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
+ $(this).val(null);
+ datetimepicker.data('xdsoft_datetime').empty();
+ } else {
+ var d = dateHelper.parseDate($(this).val(), options.format);
+ if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
+ $(this).val(dateHelper.formatDate(d, options.format));
+ } else {
+ var splittedHours = +([$(this).val()[0], $(this).val()[1]].join('')),
+ splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
+
+ // parse the numbers as 0312 => 03:12
+ if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
+ $(this).val([splittedHours, splittedMinutes].map(function (item) {
+ return item > 9 ? item : '0' + item;
+ }).join(':'));
+ } else {
+ $(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
+ }
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
+ }
+
+ datetimepicker.trigger('changedatetime.xdsoft');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ }
+ options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;
+
+ datetimepicker
+ .trigger('xchange.xdsoft')
+ .trigger('afterOpen.xdsoft');
+ };
+
+ datetimepicker
+ .data('options', options)
+ .on('touchstart mousedown.xdsoft', function (event) {
+ event.stopPropagation();
+ event.preventDefault();
+ yearselect.hide();
+ monthselect.hide();
+ return false;
+ });
+
+ //scroll_element = timepicker.find('.xdsoft_time_box');
+ timeboxparent.append(timebox);
+ timeboxparent.xdsoftScroller(options);
+
+ datetimepicker.on('afterOpen.xdsoft', function () {
+ timeboxparent.xdsoftScroller(options);
+ });
+
+ datetimepicker
+ .append(datepicker)
+ .append(timepicker);
+
+ if (options.withoutCopyright !== true) {
+ datetimepicker
+ .append(xdsoft_copyright);
+ }
+
+ datepicker
+ .append(month_picker)
+ .append(calendar)
+ .append(applyButton);
+
+ if (options.insideParent) {
+ $(input).parent().append(datetimepicker);
+ } else {
+ $(options.parentID).append(datetimepicker);
+ }
+
+ XDSoft_datetime = function () {
+ var _this = this;
+ _this.now = function (norecursion) {
+ var d = new Date(),
+ date,
+ time;
+
+ if (!norecursion && options.defaultDate) {
+ date = _this.strToDateTime(options.defaultDate);
+ d.setFullYear(date.getFullYear());
+ d.setMonth(date.getMonth());
+ d.setDate(date.getDate());
+ }
+
+ d.setFullYear(d.getFullYear());
+
+ if (!norecursion && options.defaultTime) {
+ time = _this.strtotime(options.defaultTime);
+ d.setHours(time.getHours());
+ d.setMinutes(time.getMinutes());
+ d.setSeconds(time.getSeconds());
+ d.setMilliseconds(time.getMilliseconds());
+ }
+ return d;
+ };
+
+ _this.isValidDate = function (d) {
+ if (Object.prototype.toString.call(d) !== "[object Date]") {
+ return false;
+ }
+ return !isNaN(d.getTime());
+ };
+
+ _this.setCurrentTime = function (dTime, requireValidDate) {
+ if (typeof dTime === 'string') {
+ _this.currentTime = _this.strToDateTime(dTime);
+ }
+ else if (_this.isValidDate(dTime)) {
+ _this.currentTime = dTime;
+ }
+ else if (!dTime && !requireValidDate && options.allowBlank && !options.inline) {
+ _this.currentTime = null;
+ }
+ else {
+ _this.currentTime = _this.now();
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ };
+
+ _this.empty = function () {
+ _this.currentTime = null;
+ };
+
+ _this.getCurrentTime = function () {
+ return _this.currentTime;
+ };
+
+ _this.nextMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() + 1,
+ year;
+ if (month === 12) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
+ month = 0;
+ }
+
+ year = _this.currentTime.getFullYear();
+
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.prevMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() - 1;
+ if (month === -1) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
+ month = 11;
+ }
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.getWeekOfYear = function (datetime) {
+ if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
+ var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
+ if (typeof week !== 'undefined') {
+ return week;
+ }
+ }
+ var onejan = new Date(datetime.getFullYear(), 0, 1);
+
+ //First week of the year is th one with the first Thursday according to ISO8601
+ if (onejan.getDay() !== 4) {
+ onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
+ }
+
+ return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
+ };
+
+ _this.strToDateTime = function (sDateTime) {
+ var tmpDate = [], timeOffset, currentTime;
+
+ if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
+ return sDateTime;
+ }
+
+ tmpDate = /^([+-]{1})(.*)$/.exec(sDateTime);
+
+ if (tmpDate) {
+ tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
+ }
+
+ if (tmpDate && tmpDate[2]) {
+ timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
+ currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
+ } else {
+ currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
+ }
+
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now();
+ }
+
+ return currentTime;
+ };
+
+ _this.strToDate = function (sDate) {
+ if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
+ return sDate;
+ }
+
+ var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.strtotime = function (sTime) {
+ if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
+ return sTime;
+ }
+ var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.str = function () {
+ var format = options.format;
+ if (options.yearOffset) {
+ format = format.replace('Y', _this.currentTime.getFullYear() + options.yearOffset);
+ format = format.replace('y', String(_this.currentTime.getFullYear() + options.yearOffset).substring(2, 4));
+ }
+ return dateHelper.formatDate(_this.currentTime, format);
+ };
+ _this.currentTime = this.now();
+ };
+
+ _xdsoft_datetime = new XDSoft_datetime();
+
+ applyButton.on('touchend click', function (e) {//pathbrite
+ e.preventDefault();
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+ input.val(_xdsoft_datetime.str());
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_today_button')
+ .on('touchend mousedown.xdsoft', function () {
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(0, true);
+ datetimepicker.trigger('afterOpen.xdsoft');
+ }).on('dblclick.xdsoft', function () {
+ var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
+ currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ if (currentDate < minDate) {
+ return;
+ }
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
+ if (currentDate > maxDate) {
+ return;
+ }
+ input.val(_xdsoft_datetime.str());
+ input.trigger('change');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false;
+
+ (function arguments_callee1(v) {
+ if ($this.hasClass(options.next)) {
+ _xdsoft_datetime.nextMonth();
+ } else if ($this.hasClass(options.prev)) {
+ _xdsoft_datetime.prevMonth();
+ }
+ if (options.monthChangeSpinner) {
+ if (!stop) {
+ timer = setTimeout(arguments_callee1, v || 100);
+ }
+ }
+ }(500));
+
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft', function arguments_callee2() {
+ clearTimeout(timer);
+ stop = true;
+ $([options.ownerDocument.body, options.contentWindow]).off('touchend mouseup.xdsoft', arguments_callee2);
+ });
+ });
+
+ timepicker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false,
+ period = 110;
+ (function arguments_callee4(v) {
+ var pheight = timeboxparent[0].clientHeight,
+ height = timebox[0].offsetHeight,
+ top = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ /**
+ * Fixes a bug which happens if:
+ * top is < the timeHeightInTimePicker, it will cause the up arrow to stop working
+ * same for the down arrow if it's not exactly on the pixel
+ */
+ if (top < options.timeHeightInTimePicker) {
+ top = options.timeHeightInTimePicker;
+ } else if ($this.hasClass(options.next) && (height - pheight) < top) {
+ timebox.css('marginTop', '-' + height + 'px');
+ }
+
+ if ($this.hasClass(options.next) && (height - pheight) > top) {
+ timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
+ } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
+ timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
+ }
+ /**
+ * Fixed bug:
+ * When using css3 transition, it will cause a bug that you cannot scroll the timepicker list.
+ * The reason is that the transition-duration time, if you set it to 0, all things fine, otherwise, this
+ * would cause a bug when you use jquery.css method.
+ * Let's say: * { transition: all .5s ease; }
+ * jquery timebox.css('marginTop') will return the original value which is before you clicking the next/prev button,
+ * meanwhile the timebox[0].style.marginTop will return the right value which is after you clicking the
+ * next/prev button.
+ *
+ * What we should do:
+ * Replace timebox.css('marginTop') with timebox[0].style.marginTop.
+ */
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]);
+ period = (period > 10) ? 10 : period - 10;
+ if (!stop) {
+ timer = setTimeout(arguments_callee4, v || period);
+ }
+ }(500));
+ $([options.ownerDocument.body, options.contentWindow]).on('touchend mouseup.xdsoft', function arguments_callee5() {
+ clearTimeout(timer);
+ stop = true;
+ $([options.ownerDocument.body, options.contentWindow])
+ .off('touchend mouseup.xdsoft', arguments_callee5);
+ });
+ });
+
+ xchangeTimer = 0;
+ // base handler - generating a calendar and timepicker
+ datetimepicker
+ .on('xchange.xdsoft', function (event) {
+ clearTimeout(xchangeTimer);
+ xchangeTimer = setTimeout(function () {
+
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null || isNaN(_xdsoft_datetime.currentTime.getTime())) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var table = '',
+ start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
+ i = 0,
+ j,
+ today = _xdsoft_datetime.now(),
+ maxDate = false,
+ minDate = false,
+ minDateTime = false,
+ maxDateTime = false,
+ hDate,
+ day,
+ d,
+ y,
+ m,
+ w,
+ classes = [],
+ customDateSettings,
+ newRow = true,
+ time = '',
+ h,
+ line_time,
+ description;
+
+ while (start.getDay() !== options.dayOfWeekStart) {
+ start.setDate(start.getDate() - 1);
+ }
+
+ table += '<table><thead><tr>';
+
+ if (options.weeks) {
+ table += '<th></th>';
+ }
+
+ for (j = 0; j < 7; j += 1) {
+ table += '<th>' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + '</th>';
+ }
+
+ table += '</tr></thead>';
+ table += '<tbody>';
+
+ if (options.maxDate !== false) {
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
+ }
+
+ if (options.minDate !== false) {
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ }
+
+ if (options.minDateTime !== false) {
+ minDateTime = _xdsoft_datetime.strToDate(options.minDateTime);
+ minDateTime = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), minDateTime.getHours(), minDateTime.getMinutes(), minDateTime.getSeconds());
+ }
+
+ if (options.maxDateTime !== false) {
+ maxDateTime = _xdsoft_datetime.strToDate(options.maxDateTime);
+ maxDateTime = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), maxDateTime.getHours(), maxDateTime.getMinutes(), maxDateTime.getSeconds());
+ }
+
+ var maxDateTimeDay;
+ if (maxDateTime !== false) {
+ maxDateTimeDay = ((maxDateTime.getFullYear() * 12) + maxDateTime.getMonth()) * 31 + maxDateTime.getDate();
+ }
+
+ while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
+ classes = [];
+ i += 1;
+
+ day = start.getDay();
+ d = start.getDate();
+ y = start.getFullYear();
+ m = start.getMonth();
+ w = _xdsoft_datetime.getWeekOfYear(start);
+ description = '';
+
+ classes.push('xdsoft_date');
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
+ customDateSettings = options.beforeShowDay.call(datetimepicker, start);
+ } else {
+ customDateSettings = null;
+ }
+
+ if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
+ if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
+ classes.push('xdsoft_disabled');
+ }
+ }
+
+ if(options.allowDates && options.allowDates.length>0){
+ if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
+ classes.push('xdsoft_disabled');
+ }
+ }
+
+ var currentDay = ((start.getFullYear() * 12) + start.getMonth()) * 31 + start.getDate();
+ if ((maxDate !== false && start > maxDate) || (minDateTime !== false && start < minDateTime) || (minDate !== false && start < minDate) || (maxDateTime !== false && currentDay > maxDateTimeDay) || (customDateSettings && customDateSettings[0] === false)) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (options.disabledWeekDays.indexOf(day) !== -1) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (input.is('[disabled]')) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (customDateSettings && customDateSettings[1] !== "") {
+ classes.push(customDateSettings[1]);
+ }
+
+ if (_xdsoft_datetime.currentTime.getMonth() !== m) {
+ classes.push('xdsoft_other_month');
+ }
+
+ if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_current');
+ }
+
+ if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_today');
+ }
+
+ if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_weekend');
+ }
+
+ if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
+ hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
+ classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
+ description = hDate.desc === undefined ? '' : hDate.desc;
+ }
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
+ classes.push(options.beforeShowDay(start));
+ }
+
+ if (newRow) {
+ table += '<tr>';
+ newRow = false;
+ if (options.weeks) {
+ table += '<th>' + w + '</th>';
+ }
+ }
+
+ table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="xdsoft_date xdsoft_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '" title="' + description + '">' +
+ '<div>' + d + '</div>' +
+ '</td>';
+
+ if (start.getDay() === options.dayOfWeekStartPrev) {
+ table += '</tr>';
+ newRow = true;
+ }
+
+ start.setDate(d + 1);
+ }
+ table += '</tbody></table>';
+
+ calendar.html(table);
+
+ month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
+ month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear() + options.yearOffset);
+
+ // generate timebox
+ time = '';
+ h = '';
+ m = '';
+
+ var minTimeMinutesOfDay = 0;
+ if (options.minTime !== false) {
+ var t = _xdsoft_datetime.strtotime(options.minTime);
+ minTimeMinutesOfDay = 60 * t.getHours() + t.getMinutes();
+ }
+ var maxTimeMinutesOfDay = 24 * 60;
+ if (options.maxTime !== false) {
+ var t = _xdsoft_datetime.strtotime(options.maxTime);
+ maxTimeMinutesOfDay = 60 * t.getHours() + t.getMinutes();
+ }
+
+ if (options.minDateTime !== false) {
+ var t = _xdsoft_datetime.strToDateTime(options.minDateTime);
+ var currentDayIsMinDateTimeDay = dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(t, options.formatDate);
+ if (currentDayIsMinDateTimeDay) {
+ var m = 60 * t.getHours() + t.getMinutes();
+ if (m > minTimeMinutesOfDay) minTimeMinutesOfDay = m;
+ }
+ }
+
+ if (options.maxDateTime !== false) {
+ var t = _xdsoft_datetime.strToDateTime(options.maxDateTime);
+ var currentDayIsMaxDateTimeDay = dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(t, options.formatDate);
+ if (currentDayIsMaxDateTimeDay) {
+ var m = 60 * t.getHours() + t.getMinutes();
+ if (m < maxTimeMinutesOfDay) maxTimeMinutesOfDay = m;
+ }
+ }
+
+ line_time = function line_time(h, m) {
+ var now = _xdsoft_datetime.now(), current_time,
+ isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
+ now.setHours(h);
+ h = parseInt(now.getHours(), 10);
+ now.setMinutes(m);
+ m = parseInt(now.getMinutes(), 10);
+ classes = [];
+ var currentMinutesOfDay = 60 * h + m;
+ if (input.is('[disabled]') || (currentMinutesOfDay >= maxTimeMinutesOfDay) || (currentMinutesOfDay < minTimeMinutesOfDay)) {
+ classes.push('xdsoft_disabled');
+ }
+
+ current_time = new Date(_xdsoft_datetime.currentTime);
+ current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));
+
+ if (!isALlowTimesInit) {
+ current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
+ }
+
+ if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
+ if (options.defaultSelect || datetimepicker.data('changed')) {
+ classes.push('xdsoft_current');
+ } else if (options.initTime) {
+ classes.push('xdsoft_init_time');
+ }
+ }
+ if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
+ classes.push('xdsoft_today');
+ }
+ time += '<div class="xdsoft_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + dateHelper.formatDate(now, options.formatTime) + '</div>';
+ };
+
+ if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
+ for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
+ for (j = 0; j < 60; j += options.step) {
+ var currentMinutesOfDay = i * 60 + j;
+ if (currentMinutesOfDay < minTimeMinutesOfDay) continue;
+ if (currentMinutesOfDay >= maxTimeMinutesOfDay) continue;
+ h = (i < 10 ? '0' : '') + i;
+ m = (j < 10 ? '0' : '') + j;
+ line_time(h, m);
+ }
+ }
+ } else {
+ for (i = 0; i < options.allowTimes.length; i += 1) {
+ h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
+ m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
+ line_time(h, m);
+ }
+ }
+
+ timebox.html(time);
+
+ opt = '';
+
+ for (i = parseInt(options.yearStart, 10); i <= parseInt(options.yearEnd, 10); i += 1) {
+ opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getFullYear() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + (i + options.yearOffset) + '</div>';
+ }
+ yearselect.children().eq(0)
+ .html(opt);
+
+ for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
+ opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getMonth() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + options.i18n[globalLocale].months[i] + '</div>';
+ }
+ monthselect.children().eq(0).html(opt);
+ $(datetimepicker)
+ .trigger('generate.xdsoft');
+ }, 10);
+ event.stopPropagation();
+ })
+ .on('afterOpen.xdsoft', function () {
+ if (options.timepicker) {
+ var classType, pheight, height, top;
+ if (timebox.find('.xdsoft_current').length) {
+ classType = '.xdsoft_current';
+ } else if (timebox.find('.xdsoft_init_time').length) {
+ classType = '.xdsoft_init_time';
+ }
+ if (classType) {
+ pheight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
+ if ((height - pheight) < top) {
+ top = height - pheight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
+ } else {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
+ }
+ }
+ });
+
+ timerclick = 0;
+ calendar
+ .on('touchend click.xdsoft', 'td', function (xdevent) {
+ xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
+ timerclick += 1;
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+
+ currentTime.setDate(1);
+ currentTime.setFullYear($this.data('year'));
+ currentTime.setMonth($this.data('month'));
+ currentTime.setDate($this.data('date'));
+
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ input.val(_xdsoft_datetime.str());
+
+ if (options.onSelectDate && $.isFunction(options.onSelectDate)) {
+ options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ setTimeout(function () {
+ timerclick = 0;
+ }, 200);
+ });
+
+ timebox
+ .on('touchstart', 'div', function (xdevent) {
+ this.touchMoved = false;
+ })
+ .on('touchmove', 'div', handleTouchMoved)
+ .on('touchend click.xdsoft', 'div', function (xdevent) {
+ if (!this.touchMoved) {
+ xdevent.stopPropagation();
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+ currentTime.setHours($this.data('hour'));
+ currentTime.setMinutes($this.data('minute'));
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ datetimepicker.data('input').val(_xdsoft_datetime.str());
+
+ if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
+ options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if (options.inline !== true && options.closeOnTimeSelect === true) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ }
+ });
+
+ datepicker
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollMonth) {
+ return true;
+ }
+ if (event.deltaY < 0) {
+ _xdsoft_datetime.nextMonth();
+ } else {
+ _xdsoft_datetime.prevMonth();
+ }
+ return false;
+ });
+
+ input
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollInput) {
+ return true;
+ }
+ if (!options.datepicker && options.timepicker) {
+ current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
+ if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
+ current_time_index += event.deltaY;
+ }
+ if (timebox.children().eq(current_time_index).length) {
+ timebox.children().eq(current_time_index).trigger('mousedown');
+ }
+ return false;
+ }
+ if (options.datepicker && !options.timepicker) {
+ datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
+ if (input.val) {
+ input.val(_xdsoft_datetime.str());
+ }
+ datetimepicker.trigger('changedatetime.xdsoft');
+ return false;
+ }
+ });
+
+ datetimepicker
+ .on('changedatetime.xdsoft', function (event) {
+ if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
+ var $input = datetimepicker.data('input');
+ options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
+ delete options.value;
+ $input.trigger('change');
+ }
+ })
+ .on('generate.xdsoft', function () {
+ if (options.onGenerate && $.isFunction(options.onGenerate)) {
+ options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ if (triggerAfterOpen) {
+ datetimepicker.trigger('afterOpen.xdsoft');
+ triggerAfterOpen = false;
+ }
+ })
+ .on('click.xdsoft', function (xdevent) {
+ xdevent.stopPropagation();
+ });
+
+ current_time_index = 0;
+
+ /**
+ * Runs the callback for each of the specified node's ancestors.
+ *
+ * Return FALSE from the callback to stop ascending.
+ *
+ * @param {DOMNode} node
+ * @param {Function} callback
+ * @returns {undefined}
+ */
+ forEachAncestorOf = function (node, callback) {
+ do {
+ node = node.parentNode;
+
+ if (!node || callback(node) === false) {
+ break;
+ }
+ } while (node.nodeName !== 'HTML');
+ };
+
+ /**
+ * Sets the position of the picker.
+ *
+ * @returns {undefined}
+ */
+ setPos = function () {
+ var dateInputOffset,
+ dateInputElem,
+ verticalPosition,
+ left,
+ position,
+ datetimepickerElem,
+ dateInputHasFixedAncestor,
+ $dateInput,
+ windowWidth,
+ verticalAnchorEdge,
+ datetimepickerCss,
+ windowHeight,
+ windowScrollTop;
+
+ $dateInput = datetimepicker.data('input');
+ dateInputOffset = $dateInput.offset();
+ dateInputElem = $dateInput[0];
+
+ verticalAnchorEdge = 'top';
+ verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
+ left = dateInputOffset.left;
+ position = "absolute";
+
+ windowWidth = $(options.contentWindow).width();
+ windowHeight = $(options.contentWindow).height();
+ windowScrollTop = $(options.contentWindow).scrollTop();
+
+ if ((options.ownerDocument.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
+ var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
+ left = left - diff;
+ }
+
+ if ($dateInput.parent().css('direction') === 'rtl') {
+ left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
+ }
+
+ if (options.fixed) {
+ verticalPosition -= windowScrollTop;
+ left -= $(options.contentWindow).scrollLeft();
+ position = "fixed";
+ } else {
+ dateInputHasFixedAncestor = false;
+
+ forEachAncestorOf(dateInputElem, function (ancestorNode) {
+ if (ancestorNode === null) {
+ return false;
+ }
+
+ if (options.contentWindow.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
+ dateInputHasFixedAncestor = true;
+ return false;
+ }
+ });
+
+ if (dateInputHasFixedAncestor && !options.insideParent) {
+ position = 'fixed';
+
+ //If the picker won't fit entirely within the viewport then display it above the date input.
+ if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
+ verticalAnchorEdge = 'bottom';
+ verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
+ } else {
+ verticalPosition -= windowScrollTop;
+ }
+ } else {
+ if (verticalPosition + datetimepicker[0].offsetHeight > windowHeight + windowScrollTop) {
+ verticalPosition = dateInputOffset.top - datetimepicker[0].offsetHeight + 1;
+ }
+ }
+
+ if (verticalPosition < 0) {
+ verticalPosition = 0;
+ }
+
+ if (left + dateInputElem.offsetWidth > windowWidth) {
+ left = windowWidth - dateInputElem.offsetWidth;
+ }
+ }
+
+ datetimepickerElem = datetimepicker[0];
+
+ forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
+ var ancestorNodePosition;
+
+ ancestorNodePosition = options.contentWindow.getComputedStyle(ancestorNode).getPropertyValue('position');
+
+ if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
+ left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
+ return false;
+ }
+ });
+
+ datetimepickerCss = {
+ position: position,
+ left: options.insideParent ? dateInputElem.offsetLeft : left,
+ top: '', //Initialize to prevent previous values interfering with new ones.
+ bottom: '' //Initialize to prevent previous values interfering with new ones.
+ };
+
+ if (options.insideParent) {
+ datetimepickerCss[verticalAnchorEdge] = dateInputElem.offsetTop + dateInputElem.offsetHeight;
+ } else {
+ datetimepickerCss[verticalAnchorEdge] = verticalPosition;
+ }
+
+ datetimepicker.css(datetimepickerCss);
+ };
+
+ datetimepicker
+ .on('open.xdsoft', function (event) {
+ var onShow = true;
+ if (options.onShow && $.isFunction(options.onShow)) {
+ onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onShow !== false) {
+ datetimepicker.show();
+ setPos();
+ $(options.contentWindow)
+ .off('resize.xdsoft', setPos)
+ .on('resize.xdsoft', setPos);
+
+ if (options.closeOnWithoutClick) {
+ $([options.ownerDocument.body, options.contentWindow]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
+ datetimepicker.trigger('close.xdsoft');
+ $([options.ownerDocument.body, options.contentWindow]).off('touchstart mousedown.xdsoft', arguments_callee6);
+ });
+ }
+ }
+ })
+ .on('close.xdsoft', function (event) {
+ var onClose = true;
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .find('.xdsoft_select')
+ .hide();
+ if (options.onClose && $.isFunction(options.onClose)) {
+ onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onClose !== false && !options.opened && !options.inline) {
+ datetimepicker.hide();
+ }
+ event.stopPropagation();
+ })
+ .on('toggle.xdsoft', function () {
+ if (datetimepicker.is(':visible')) {
+ datetimepicker.trigger('close.xdsoft');
+ } else {
+ datetimepicker.trigger('open.xdsoft');
+ }
+ })
+ .data('input', input);
+
+ timer = 0;
+
+ datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
+ datetimepicker.setOptions(options);
+
+ function getCurrentValue() {
+ var ct = false, time;
+
+ if (options.startDate) {
+ ct = _xdsoft_datetime.strToDate(options.startDate);
+ } else {
+ ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
+ if (ct) {
+ ct = _xdsoft_datetime.strToDateTime(ct);
+ if (options.yearOffset) {
+ ct = new Date(ct.getFullYear() - options.yearOffset, ct.getMonth(), ct.getDate(), ct.getHours(), ct.getMinutes(), ct.getSeconds(), ct.getMilliseconds());
+ }
+ } else if (options.defaultDate) {
+ ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
+ if (options.defaultTime) {
+ time = _xdsoft_datetime.strtotime(options.defaultTime);
+ ct.setHours(time.getHours());
+ ct.setMinutes(time.getMinutes());
+ }
+ }
+ }
+
+ if (ct && _xdsoft_datetime.isValidDate(ct)) {
+ datetimepicker.data('changed', true);
+ } else {
+ ct = '';
+ }
+
+ return ct || 0;
+ }
+
+ function setMask(options) {
+
+ var isValidValue = function (mask, value) {
+ var reg = mask
+ .replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
+ .replace(/_/g, '{digit+}')
+ .replace(/([0-9]{1})/g, '{digit$1}')
+ .replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
+ .replace(/\{digit[\+]\}/g, '[0-9_]{1}');
+ return (new RegExp(reg)).test(value);
+ },
+ getCaretPos = function (input) {
+ try {
+ if (options.ownerDocument.selection && options.ownerDocument.selection.createRange) {
+ var range = options.ownerDocument.selection.createRange();
+ return range.getBookmark().charCodeAt(2) - 2;
+ }
+ if (input.setSelectionRange) {
+ return input.selectionStart;
+ }
+ } catch (e) {
+ return 0;
+ }
+ },
+ setCaretPos = function (node, pos) {
+ node = (typeof node === "string" || node instanceof String) ? options.ownerDocument.getElementById(node) : node;
+ if (!node) {
+ return false;
+ }
+ if (node.createTextRange) {
+ var textRange = node.createTextRange();
+ textRange.collapse(true);
+ textRange.moveEnd('character', pos);
+ textRange.moveStart('character', pos);
+ textRange.select();
+ return true;
+ }
+ if (node.setSelectionRange) {
+ node.setSelectionRange(pos, pos);
+ return true;
+ }
+ return false;
+ };
+
+ if(options.mask) {
+ input.off('keydown.xdsoft');
+ }
+
+ if (options.mask === true) {
+ if (dateHelper.formatMask) {
+ options.mask = dateHelper.formatMask(options.format)
+ } else {
+ options.mask = options.format
+ .replace(/Y/g, '9999')
+ .replace(/F/g, '9999')
+ .replace(/m/g, '19')
+ .replace(/d/g, '39')
+ .replace(/H/g, '29')
+ .replace(/i/g, '59')
+ .replace(/s/g, '59');
+ }
+ }
+
+ if ($.type(options.mask) === 'string') {
+ if (!isValidValue(options.mask, input.val())) {
+ input.val(options.mask.replace(/[0-9]/g, '_'));
+ setCaretPos(input[0], 0);
+ }
+
+ input.on('paste.xdsoft', function (event) {
+ // couple options here
+ // 1. return false - tell them they can't paste
+ // 2. insert over current characters - minimal validation
+ // 3. full fledged parsing and validation
+ // let's go option 2 for now
+
+ // fires multiple times for some reason
+
+ // https://stackoverflow.com/a/30496488/1366033
+ var clipboardData = event.clipboardData || event.originalEvent.clipboardData || window.clipboardData,
+ pastedData = clipboardData.getData('text'),
+ val = this.value,
+ pos = this.selectionStart
+
+ var valueBeforeCursor = val.substr(0, pos);
+ var valueAfterPaste = val.substr(pos + pastedData.length);
+
+ val = valueBeforeCursor + pastedData + valueAfterPaste;
+ pos += pastedData.length;
+
+ if (isValidValue(options.mask, val)) {
+ this.value = val;
+ setCaretPos(this, pos);
+ } else if ($.trim(val) === '') {
+ this.value = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ input.trigger('error_input.xdsoft');
+ }
+
+ event.preventDefault();
+ return false;
+ });
+
+ input.on('keydown.xdsoft', function (event) {
+ var val = this.value,
+ key = event.which,
+ pos = this.selectionStart,
+ selEnd = this.selectionEnd,
+ hasSel = pos !== selEnd,
+ digit;
+
+ // only alow these characters
+ if (((key >= KEY0 && key <= KEY9) ||
+ (key >= _KEY0 && key <= _KEY9)) ||
+ (key === BACKSPACE || key === DEL)) {
+
+ // get char to insert which is new character or placeholder ('_')
+ digit = (key === BACKSPACE || key === DEL) ? '_' :
+ String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key);
+
+ // we're deleting something, we're not at the start, and have normal cursor, move back one
+ // if we have a selection length, cursor actually sits behind deletable char, not in front
+ if (key === BACKSPACE && pos && !hasSel) {
+ pos -= 1;
+ }
+
+ // don't stop on a separator, continue whatever direction you were going
+ // value char - keep incrementing position while on separator char and we still have room
+ // del char - keep decrementing position while on separator char and we still have room
+ while (true) {
+ var maskValueAtCurPos = options.mask.substr(pos, 1);
+ var posShorterThanMaskLength = pos < options.mask.length;
+ var posGreaterThanZero = pos > 0;
+ var notNumberOrPlaceholder = /[^0-9_]/;
+ var curPosOnSep = notNumberOrPlaceholder.test(maskValueAtCurPos);
+ var continueMovingPosition = curPosOnSep && posShorterThanMaskLength && posGreaterThanZero
+
+ // if we hit a real char, stay where we are
+ if (!continueMovingPosition) break;
+
+ // hitting backspace in a selection, you can possibly go back any further - go forward
+ pos += (key === BACKSPACE && !hasSel) ? -1 : 1;
+
+ }
+
+ if (event.metaKey) { // cmd has been pressed
+ pos = 0;
+ hasSel = true;
+ }
+
+ if (hasSel) {
+ // pos might have moved so re-calc length
+ var selLength = selEnd - pos
+
+ // if we have a selection length we will wipe out entire selection and replace with default template for that range
+ var defaultBlank = options.mask.replace(/[0-9]/g, '_');
+ var defaultBlankSelectionReplacement = defaultBlank.substr(pos, selLength);
+ var selReplacementRemainder = defaultBlankSelectionReplacement.substr(1) // might be empty
+
+ var valueBeforeSel = val.substr(0, pos);
+ var insertChars = digit + selReplacementRemainder;
+ var charsAfterSelection = val.substr(pos + selLength);
+
+ val = valueBeforeSel + insertChars + charsAfterSelection
+
+ } else {
+ var valueBeforeCursor = val.substr(0, pos);
+ var insertChar = digit;
+ var valueAfterNextChar = val.substr(pos + 1);
+
+ val = valueBeforeCursor + insertChar + valueAfterNextChar
+ }
+
+ if ($.trim(val) === '') {
+ // if empty, set to default
+ val = defaultBlank
+ } else {
+ // if at the last character don't need to do anything
+ if (pos === options.mask.length) {
+ event.preventDefault();
+ return false;
+ }
+ }
+
+ // resume cursor location
+ pos += (key === BACKSPACE) ? 0 : 1;
+ // don't stop on a separator, continue whatever direction you were going
+ while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
+ pos += (key === BACKSPACE) ? 0 : 1;
+ }
+
+ if (isValidValue(options.mask, val)) {
+ this.value = val;
+ setCaretPos(this, pos);
+ } else if ($.trim(val) === '') {
+ this.value = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ input.trigger('error_input.xdsoft');
+ }
+ } else {
+ if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
+ return true;
+ }
+ }
+
+ event.preventDefault();
+ return false;
+ });
+ }
+ }
+
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+
+ input
+ .data('xdsoft_datetimepicker', datetimepicker)
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
+ if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
+ return;
+ }
+ if (!options.openOnFocus) {
+ return;
+ }
+ clearTimeout(timer);
+ timer = setTimeout(function () {
+ if (input.is(':disabled')) {
+ return;
+ }
+
+ triggerAfterOpen = true;
+ _xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
+ if(options.mask) {
+ setMask(options);
+ }
+ datetimepicker.trigger('open.xdsoft');
+ }, 100);
+ })
+ .on('keydown.xdsoft', function (event) {
+ var elementSelector,
+ key = event.which;
+ if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
+ elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
+ datetimepicker.trigger('close.xdsoft');
+ elementSelector.eq(elementSelector.index(this) + 1).focus();
+ return false;
+ }
+ if ([TAB].indexOf(key) !== -1) {
+ datetimepicker.trigger('close.xdsoft');
+ return true;
+ }
+ })
+ .on('blur.xdsoft', function () {
+ datetimepicker.trigger('close.xdsoft');
+ });
+ };
+ destroyDateTimePicker = function (input) {
+ var datetimepicker = input.data('xdsoft_datetimepicker');
+ if (datetimepicker) {
+ datetimepicker.data('xdsoft_datetime', null);
+ datetimepicker.remove();
+ input
+ .data('xdsoft_datetimepicker', null)
+ .off('.xdsoft');
+ $(options.contentWindow).off('resize.xdsoft');
+ $([options.contentWindow, options.ownerDocument.body]).off('mousedown.xdsoft touchstart');
+ if (input.unmousewheel) {
+ input.unmousewheel();
+ }
+ }
+ };
+ $(options.ownerDocument)
+ .off('keydown.xdsoftctrl keyup.xdsoftctrl')
+ .off('keydown.xdsoftcmd keyup.xdsoftcmd')
+ .on('keydown.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = true;
+ }
+ })
+ .on('keyup.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = false;
+ }
+ })
+ .on('keydown.xdsoftcmd', function (e) {
+ if (e.keyCode === CMDKEY) {
+ cmdDown = true;
+ }
+ })
+ .on('keyup.xdsoftcmd', function (e) {
+ if (e.keyCode === CMDKEY) {
+ cmdDown = false;
+ }
+ });
+
+ this.each(function () {
+ var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
+ if (datetimepicker) {
+ if ($.type(opt) === 'string') {
+ switch (opt) {
+ case 'show':
+ $(this).select().focus();
+ datetimepicker.trigger('open.xdsoft');
+ break;
+ case 'hide':
+ datetimepicker.trigger('close.xdsoft');
+ break;
+ case 'toggle':
+ datetimepicker.trigger('toggle.xdsoft');
+ break;
+ case 'destroy':
+ destroyDateTimePicker($(this));
+ break;
+ case 'reset':
+ this.value = this.defaultValue;
+ if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
+ datetimepicker.data('changed', false);
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
+ break;
+ case 'validate':
+ $input = datetimepicker.data('input');
+ $input.trigger('blur.xdsoft');
+ break;
+ default:
+ if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
+ result = datetimepicker[opt](opt2);
+ }
+ }
+ } else {
+ datetimepicker
+ .setOptions(opt);
+ }
+ return 0;
+ }
+ if ($.type(opt) !== 'string') {
+ if (!options.lazyInit || options.open || options.inline) {
+ createDateTimePicker($(this));
+ } else {
+ lazyInit($(this));
+ }
+ }
+ });
+
+ return result;
+ };
+
+ $.fn.datetimepicker.defaults = default_options;
+
+ function HighlightedDate(date, desc, style) {
+ "use strict";
+ this.date = date;
+ this.desc = desc;
+ this.style = style;
+ }
+};
+;(function (factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery', 'jquery-mousewheel'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory(require('jquery'));;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(datetimepickerFactory));
+
+
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/favicon.ico b/op25/gr-op25_repeater/apps/oplog/op25/static/favicon.ico
new file mode 100644
index 0000000..b47738f
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/favicon.ico
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-1.11.3.min.js b/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-1.11.3.min.js
new file mode 100644
index 0000000..0f60b7b
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-1.11.3.min.js
@@ -0,0 +1,5 @@
+/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
+
+return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
+return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-2.2.4.min.js b/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-2.2.4.min.js
new file mode 100644
index 0000000..4024b66
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/jquery/jquery-2.2.4.min.js
@@ -0,0 +1,4 @@
+/*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
+}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ca(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Fa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ba.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Oa(a,b,c||(g?"border":"content"),d,f)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),
+void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b)}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.bundle.min.js b/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.bundle.min.js
new file mode 100644
index 0000000..9b6cec7
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.bundle.min.js
@@ -0,0 +1,7 @@
+/*!
+ * Bootstrap v5.0.1 (https://getbootstrap.com/)
+ * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter(t=>t.matches(e)),parents(t,e){const i=[];let n=t.parentNode;for(;n&&n.nodeType===Node.ELEMENT_NODE&&3!==n.nodeType;)n.matches(e)&&i.push(n),n=n.parentNode;return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]}},e=t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t},i=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i="#"+i.split("#")[1]),e=i&&"#"!==i?i.trim():null}return e},n=t=>{const e=i(t);return e&&document.querySelector(e)?e:null},s=t=>{const e=i(t);return e?document.querySelector(e):null},o=t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0},r=t=>{t.dispatchEvent(new Event("transitionend"))},a=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),l=e=>a(e)?e.jquery?e[0]:e:"string"==typeof e&&e.length>0?t.findOne(e):null,c=(t,e)=>{let i=!1;const n=e+5;t.addEventListener("transitionend",(function e(){i=!0,t.removeEventListener("transitionend",e)})),setTimeout(()=>{i||r(t)},n)},d=(t,e,i)=>{Object.keys(i).forEach(n=>{const s=i[n],o=e[n],r=o&&a(o)?"element":null==(l=o)?""+l:{}.toString.call(l).match(/\s([a-z]+)/i)[1].toLowerCase();var l;if(!new RegExp(s).test(r))throw new TypeError(`${t.toUpperCase()}: Option "${n}" provided type "${r}" but expected type "${s}".`)})},h=t=>{if(!t)return!1;if(t.style&&t.parentNode&&t.parentNode.style){const e=getComputedStyle(t),i=getComputedStyle(t.parentNode);return"none"!==e.display&&"none"!==i.display&&"hidden"!==e.visibility}return!1},u=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),f=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?f(t.parentNode):null},p=()=>{},m=t=>t.offsetHeight,g=()=>{const{jQuery:t}=window;return t&&!document.body.hasAttribute("data-bs-no-jquery")?t:null},_=()=>"rtl"===document.documentElement.dir,b=t=>{var e;e=()=>{const e=g();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()},v=t=>{"function"==typeof t&&t()},y=new Map;var w={set(t,e,i){y.has(t)||y.set(t,new Map);const n=y.get(t);n.has(e)||0===n.size?n.set(e,i):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(n.keys())[0]}.`)},get:(t,e)=>y.has(t)&&y.get(t).get(e)||null,remove(t,e){if(!y.has(t))return;const i=y.get(t);i.delete(e),0===i.size&&y.delete(t)}};const E=/[^.]*(?=\..*)\.|.*/,T=/\..*/,A=/::\d+$/,L={};let O=1;const k={mouseenter:"mouseover",mouseleave:"mouseout"},C=/^(mouseenter|mouseleave)/i,x=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function D(t,e){return e&&`${e}::${O++}`||t.uidEvent||O++}function N(t){const e=D(t);return t.uidEvent=e,L[e]=L[e]||{},L[e]}function S(t,e,i=null){const n=Object.keys(t);for(let s=0,o=n.length;s<o;s++){const o=t[n[s]];if(o.originalHandler===e&&o.delegationSelector===i)return o}return null}function I(t,e,i){const n="string"==typeof e,s=n?i:e;let o=M(t);return x.has(o)||(o=t),[n,s,o]}function j(t,e,i,n,s){if("string"!=typeof e||!t)return;if(i||(i=n,n=null),C.test(e)){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};n?n=t(n):i=t(i)}const[o,r,a]=I(e,i,n),l=N(t),c=l[a]||(l[a]={}),d=S(c,r,o?i:null);if(d)return void(d.oneOff=d.oneOff&&s);const h=D(r,e.replace(E,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(let a=o.length;a--;)if(o[a]===r)return s.delegateTarget=r,n.oneOff&&H.off(t,s.type,e,i),i.apply(r,[s]);return null}}(t,i,n):function(t,e){return function i(n){return n.delegateTarget=t,i.oneOff&&H.off(t,n.type,e),e.apply(t,[n])}}(t,i);u.delegationSelector=o?i:null,u.originalHandler=r,u.oneOff=s,u.uidEvent=h,c[h]=u,t.addEventListener(a,u,o)}function P(t,e,i,n,s){const o=S(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function M(t){return t=t.replace(T,""),k[t]||t}const H={on(t,e,i,n){j(t,e,i,n,!1)},one(t,e,i,n){j(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=I(e,i,n),a=r!==e,l=N(t),c=e.startsWith(".");if(void 0!==o){if(!l||!l[r])return;return void P(t,l,r,o,s?i:null)}c&&Object.keys(l).forEach(i=>{!function(t,e,i,n){const s=e[i]||{};Object.keys(s).forEach(o=>{if(o.includes(n)){const n=s[o];P(t,e,i,n.originalHandler,n.delegationSelector)}})}(t,l,i,e.slice(1))});const d=l[r]||{};Object.keys(d).forEach(i=>{const n=i.replace(A,"");if(!a||e.includes(n)){const e=d[i];P(t,l,r,e.originalHandler,e.delegationSelector)}})},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=g(),s=M(e),o=e!==s,r=x.has(s);let a,l=!0,c=!0,d=!1,h=null;return o&&n&&(a=n.Event(e,i),n(t).trigger(a),l=!a.isPropagationStopped(),c=!a.isImmediatePropagationStopped(),d=a.isDefaultPrevented()),r?(h=document.createEvent("HTMLEvents"),h.initEvent(s,l,!0)):h=new CustomEvent(e,{bubbles:l,cancelable:!0}),void 0!==i&&Object.keys(i).forEach(t=>{Object.defineProperty(h,t,{get:()=>i[t]})}),d&&h.preventDefault(),c&&t.dispatchEvent(h),h.defaultPrevented&&void 0!==a&&a.preventDefault(),h}};class R{constructor(t){(t=l(t))&&(this._element=t,w.set(this._element,this.constructor.DATA_KEY,this))}dispose(){w.remove(this._element,this.constructor.DATA_KEY),H.off(this._element,this.constructor.EVENT_KEY),Object.getOwnPropertyNames(this).forEach(t=>{this[t]=null})}_queueCallback(t,e,i=!0){if(!i)return void v(t);const n=o(e);H.one(e,"transitionend",()=>v(t)),c(e,n)}static getInstance(t){return w.get(t,this.DATA_KEY)}static get VERSION(){return"5.0.1"}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}static get DATA_KEY(){return"bs."+this.NAME}static get EVENT_KEY(){return"."+this.DATA_KEY}}class B extends R{static get NAME(){return"alert"}close(t){const e=t?this._getRootElement(t):this._element,i=this._triggerCloseEvent(e);null===i||i.defaultPrevented||this._removeElement(e)}_getRootElement(t){return s(t)||t.closest(".alert")}_triggerCloseEvent(t){return H.trigger(t,"close.bs.alert")}_removeElement(t){t.classList.remove("show");const e=t.classList.contains("fade");this._queueCallback(()=>this._destroyElement(t),t,e)}_destroyElement(t){t.parentNode&&t.parentNode.removeChild(t),H.trigger(t,"closed.bs.alert")}static jQueryInterface(t){return this.each((function(){let e=w.get(this,"bs.alert");e||(e=new B(this)),"close"===t&&e[t](this)}))}static handleDismiss(t){return function(e){e&&e.preventDefault(),t.close(this)}}}H.on(document,"click.bs.alert.data-api",'[data-bs-dismiss="alert"]',B.handleDismiss(new B)),b(B);class W extends R{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){let e=w.get(this,"bs.button");e||(e=new W(this)),"toggle"===t&&e[t]()}))}}function q(t){return"true"===t||"false"!==t&&(t===Number(t).toString()?Number(t):""===t||"null"===t?null:t)}function z(t){return t.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}H.on(document,"click.bs.button.data-api",'[data-bs-toggle="button"]',t=>{t.preventDefault();const e=t.target.closest('[data-bs-toggle="button"]');let i=w.get(e,"bs.button");i||(i=new W(e)),i.toggle()}),b(W);const U={setDataAttribute(t,e,i){t.setAttribute("data-bs-"+z(e),i)},removeDataAttribute(t,e){t.removeAttribute("data-bs-"+z(e))},getDataAttributes(t){if(!t)return{};const e={};return Object.keys(t.dataset).filter(t=>t.startsWith("bs")).forEach(i=>{let n=i.replace(/^bs/,"");n=n.charAt(0).toLowerCase()+n.slice(1,n.length),e[n]=q(t.dataset[i])}),e},getDataAttribute:(t,e)=>q(t.getAttribute("data-bs-"+z(e))),offset(t){const e=t.getBoundingClientRect();return{top:e.top+document.body.scrollTop,left:e.left+document.body.scrollLeft}},position:t=>({top:t.offsetTop,left:t.offsetLeft})},$={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0,touch:!0},F={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean",touch:"boolean"},V="next",K="prev",X="left",Y="right";class Q extends R{constructor(e,i){super(e),this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this.touchStartX=0,this.touchDeltaX=0,this._config=this._getConfig(i),this._indicatorsElement=t.findOne(".carousel-indicators",this._element),this._touchSupported="ontouchstart"in document.documentElement||navigator.maxTouchPoints>0,this._pointerEvent=Boolean(window.PointerEvent),this._addEventListeners()}static get Default(){return $}static get NAME(){return"carousel"}next(){this._isSliding||this._slide(V)}nextWhenVisible(){!document.hidden&&h(this._element)&&this.next()}prev(){this._isSliding||this._slide(K)}pause(e){e||(this._isPaused=!0),t.findOne(".carousel-item-next, .carousel-item-prev",this._element)&&(r(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null}cycle(t){t||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config&&this._config.interval&&!this._isPaused&&(this._updateInterval(),this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))}to(e){this._activeElement=t.findOne(".active.carousel-item",this._element);const i=this._getItemIndex(this._activeElement);if(e>this._items.length-1||e<0)return;if(this._isSliding)return void H.one(this._element,"slid.bs.carousel",()=>this.to(e));if(i===e)return this.pause(),void this.cycle();const n=e>i?V:K;this._slide(n,this._items[e])}_getConfig(t){return t={...$,...t},d("carousel",t,F),t}_handleSwipe(){const t=Math.abs(this.touchDeltaX);if(t<=40)return;const e=t/this.touchDeltaX;this.touchDeltaX=0,e&&this._slide(e>0?Y:X)}_addEventListeners(){this._config.keyboard&&H.on(this._element,"keydown.bs.carousel",t=>this._keydown(t)),"hover"===this._config.pause&&(H.on(this._element,"mouseenter.bs.carousel",t=>this.pause(t)),H.on(this._element,"mouseleave.bs.carousel",t=>this.cycle(t))),this._config.touch&&this._touchSupported&&this._addTouchEventListeners()}_addTouchEventListeners(){const e=t=>{!this._pointerEvent||"pen"!==t.pointerType&&"touch"!==t.pointerType?this._pointerEvent||(this.touchStartX=t.touches[0].clientX):this.touchStartX=t.clientX},i=t=>{this.touchDeltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this.touchStartX},n=t=>{!this._pointerEvent||"pen"!==t.pointerType&&"touch"!==t.pointerType||(this.touchDeltaX=t.clientX-this.touchStartX),this._handleSwipe(),"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout(t=>this.cycle(t),500+this._config.interval))};t.find(".carousel-item img",this._element).forEach(t=>{H.on(t,"dragstart.bs.carousel",t=>t.preventDefault())}),this._pointerEvent?(H.on(this._element,"pointerdown.bs.carousel",t=>e(t)),H.on(this._element,"pointerup.bs.carousel",t=>n(t)),this._element.classList.add("pointer-event")):(H.on(this._element,"touchstart.bs.carousel",t=>e(t)),H.on(this._element,"touchmove.bs.carousel",t=>i(t)),H.on(this._element,"touchend.bs.carousel",t=>n(t)))}_keydown(t){/input|textarea/i.test(t.target.tagName)||("ArrowLeft"===t.key?(t.preventDefault(),this._slide(Y)):"ArrowRight"===t.key&&(t.preventDefault(),this._slide(X)))}_getItemIndex(e){return this._items=e&&e.parentNode?t.find(".carousel-item",e.parentNode):[],this._items.indexOf(e)}_getItemByOrder(t,e){const i=t===V,n=t===K,s=this._getItemIndex(e),o=this._items.length-1;if((n&&0===s||i&&s===o)&&!this._config.wrap)return e;const r=(s+(n?-1:1))%this._items.length;return-1===r?this._items[this._items.length-1]:this._items[r]}_triggerSlideEvent(e,i){const n=this._getItemIndex(e),s=this._getItemIndex(t.findOne(".active.carousel-item",this._element));return H.trigger(this._element,"slide.bs.carousel",{relatedTarget:e,direction:i,from:s,to:n})}_setActiveIndicatorElement(e){if(this._indicatorsElement){const i=t.findOne(".active",this._indicatorsElement);i.classList.remove("active"),i.removeAttribute("aria-current");const n=t.find("[data-bs-target]",this._indicatorsElement);for(let t=0;t<n.length;t++)if(Number.parseInt(n[t].getAttribute("data-bs-slide-to"),10)===this._getItemIndex(e)){n[t].classList.add("active"),n[t].setAttribute("aria-current","true");break}}}_updateInterval(){const e=this._activeElement||t.findOne(".active.carousel-item",this._element);if(!e)return;const i=Number.parseInt(e.getAttribute("data-bs-interval"),10);i?(this._config.defaultInterval=this._config.defaultInterval||this._config.interval,this._config.interval=i):this._config.interval=this._config.defaultInterval||this._config.interval}_slide(e,i){const n=this._directionToOrder(e),s=t.findOne(".active.carousel-item",this._element),o=this._getItemIndex(s),r=i||this._getItemByOrder(n,s),a=this._getItemIndex(r),l=Boolean(this._interval),c=n===V,d=c?"carousel-item-start":"carousel-item-end",h=c?"carousel-item-next":"carousel-item-prev",u=this._orderToDirection(n);if(r&&r.classList.contains("active"))return void(this._isSliding=!1);if(this._triggerSlideEvent(r,u).defaultPrevented)return;if(!s||!r)return;this._isSliding=!0,l&&this.pause(),this._setActiveIndicatorElement(r),this._activeElement=r;const f=()=>{H.trigger(this._element,"slid.bs.carousel",{relatedTarget:r,direction:u,from:o,to:a})};if(this._element.classList.contains("slide")){r.classList.add(h),m(r),s.classList.add(d),r.classList.add(d);const t=()=>{r.classList.remove(d,h),r.classList.add("active"),s.classList.remove("active",h,d),this._isSliding=!1,setTimeout(f,0)};this._queueCallback(t,s,!0)}else s.classList.remove("active"),r.classList.add("active"),this._isSliding=!1,f();l&&this.cycle()}_directionToOrder(t){return[Y,X].includes(t)?_()?t===X?K:V:t===X?V:K:t}_orderToDirection(t){return[V,K].includes(t)?_()?t===K?X:Y:t===K?Y:X:t}static carouselInterface(t,e){let i=w.get(t,"bs.carousel"),n={...$,...U.getDataAttributes(t)};"object"==typeof e&&(n={...n,...e});const s="string"==typeof e?e:n.slide;if(i||(i=new Q(t,n)),"number"==typeof e)i.to(e);else if("string"==typeof s){if(void 0===i[s])throw new TypeError(`No method named "${s}"`);i[s]()}else n.interval&&n.ride&&(i.pause(),i.cycle())}static jQueryInterface(t){return this.each((function(){Q.carouselInterface(this,t)}))}static dataApiClickHandler(t){const e=s(this);if(!e||!e.classList.contains("carousel"))return;const i={...U.getDataAttributes(e),...U.getDataAttributes(this)},n=this.getAttribute("data-bs-slide-to");n&&(i.interval=!1),Q.carouselInterface(e,i),n&&w.get(e,"bs.carousel").to(n),t.preventDefault()}}H.on(document,"click.bs.carousel.data-api","[data-bs-slide], [data-bs-slide-to]",Q.dataApiClickHandler),H.on(window,"load.bs.carousel.data-api",()=>{const e=t.find('[data-bs-ride="carousel"]');for(let t=0,i=e.length;t<i;t++)Q.carouselInterface(e[t],w.get(e[t],"bs.carousel"))}),b(Q);const G={toggle:!0,parent:""},Z={toggle:"boolean",parent:"(string|element)"};class J extends R{constructor(e,i){super(e),this._isTransitioning=!1,this._config=this._getConfig(i),this._triggerArray=t.find(`[data-bs-toggle="collapse"][href="#${this._element.id}"],[data-bs-toggle="collapse"][data-bs-target="#${this._element.id}"]`);const s=t.find('[data-bs-toggle="collapse"]');for(let e=0,i=s.length;e<i;e++){const i=s[e],o=n(i),r=t.find(o).filter(t=>t===this._element);null!==o&&r.length&&(this._selector=o,this._triggerArray.push(i))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}static get Default(){return G}static get NAME(){return"collapse"}toggle(){this._element.classList.contains("show")?this.hide():this.show()}show(){if(this._isTransitioning||this._element.classList.contains("show"))return;let e,i;this._parent&&(e=t.find(".show, .collapsing",this._parent).filter(t=>"string"==typeof this._config.parent?t.getAttribute("data-bs-parent")===this._config.parent:t.classList.contains("collapse")),0===e.length&&(e=null));const n=t.findOne(this._selector);if(e){const t=e.find(t=>n!==t);if(i=t?w.get(t,"bs.collapse"):null,i&&i._isTransitioning)return}if(H.trigger(this._element,"show.bs.collapse").defaultPrevented)return;e&&e.forEach(t=>{n!==t&&J.collapseInterface(t,"hide"),i||w.set(t,"bs.collapse",null)});const s=this._getDimension();this._element.classList.remove("collapse"),this._element.classList.add("collapsing"),this._element.style[s]=0,this._triggerArray.length&&this._triggerArray.forEach(t=>{t.classList.remove("collapsed"),t.setAttribute("aria-expanded",!0)}),this.setTransitioning(!0);const o="scroll"+(s[0].toUpperCase()+s.slice(1));this._queueCallback(()=>{this._element.classList.remove("collapsing"),this._element.classList.add("collapse","show"),this._element.style[s]="",this.setTransitioning(!1),H.trigger(this._element,"shown.bs.collapse")},this._element,!0),this._element.style[s]=this._element[o]+"px"}hide(){if(this._isTransitioning||!this._element.classList.contains("show"))return;if(H.trigger(this._element,"hide.bs.collapse").defaultPrevented)return;const t=this._getDimension();this._element.style[t]=this._element.getBoundingClientRect()[t]+"px",m(this._element),this._element.classList.add("collapsing"),this._element.classList.remove("collapse","show");const e=this._triggerArray.length;if(e>0)for(let t=0;t<e;t++){const e=this._triggerArray[t],i=s(e);i&&!i.classList.contains("show")&&(e.classList.add("collapsed"),e.setAttribute("aria-expanded",!1))}this.setTransitioning(!0),this._element.style[t]="",this._queueCallback(()=>{this.setTransitioning(!1),this._element.classList.remove("collapsing"),this._element.classList.add("collapse"),H.trigger(this._element,"hidden.bs.collapse")},this._element,!0)}setTransitioning(t){this._isTransitioning=t}_getConfig(t){return(t={...G,...t}).toggle=Boolean(t.toggle),d("collapse",t,Z),t}_getDimension(){return this._element.classList.contains("width")?"width":"height"}_getParent(){let{parent:e}=this._config;e=l(e);const i=`[data-bs-toggle="collapse"][data-bs-parent="${e}"]`;return t.find(i,e).forEach(t=>{const e=s(t);this._addAriaAndCollapsedClass(e,[t])}),e}_addAriaAndCollapsedClass(t,e){if(!t||!e.length)return;const i=t.classList.contains("show");e.forEach(t=>{i?t.classList.remove("collapsed"):t.classList.add("collapsed"),t.setAttribute("aria-expanded",i)})}static collapseInterface(t,e){let i=w.get(t,"bs.collapse");const n={...G,...U.getDataAttributes(t),..."object"==typeof e&&e?e:{}};if(!i&&n.toggle&&"string"==typeof e&&/show|hide/.test(e)&&(n.toggle=!1),i||(i=new J(t,n)),"string"==typeof e){if(void 0===i[e])throw new TypeError(`No method named "${e}"`);i[e]()}}static jQueryInterface(t){return this.each((function(){J.collapseInterface(this,t)}))}}H.on(document,"click.bs.collapse.data-api",'[data-bs-toggle="collapse"]',(function(e){("A"===e.target.tagName||e.delegateTarget&&"A"===e.delegateTarget.tagName)&&e.preventDefault();const i=U.getDataAttributes(this),s=n(this);t.find(s).forEach(t=>{const e=w.get(t,"bs.collapse");let n;e?(null===e._parent&&"string"==typeof i.parent&&(e._config.parent=i.parent,e._parent=e._getParent()),n="toggle"):n=i,J.collapseInterface(t,n)})})),b(J);var tt="top",et="bottom",it="right",nt="left",st=[tt,et,it,nt],ot=st.reduce((function(t,e){return t.concat([e+"-start",e+"-end"])}),[]),rt=[].concat(st,["auto"]).reduce((function(t,e){return t.concat([e,e+"-start",e+"-end"])}),[]),at=["beforeRead","read","afterRead","beforeMain","main","afterMain","beforeWrite","write","afterWrite"];function lt(t){return t?(t.nodeName||"").toLowerCase():null}function ct(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function dt(t){return t instanceof ct(t).Element||t instanceof Element}function ht(t){return t instanceof ct(t).HTMLElement||t instanceof HTMLElement}function ut(t){return"undefined"!=typeof ShadowRoot&&(t instanceof ct(t).ShadowRoot||t instanceof ShadowRoot)}var ft={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];ht(s)&&lt(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});ht(n)&&lt(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function pt(t){return t.split("-")[0]}function mt(t){var e=t.getBoundingClientRect();return{width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,x:e.left,y:e.top}}function gt(t){var e=mt(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function _t(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&ut(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function bt(t){return ct(t).getComputedStyle(t)}function vt(t){return["table","td","th"].indexOf(lt(t))>=0}function yt(t){return((dt(t)?t.ownerDocument:t.document)||window.document).documentElement}function wt(t){return"html"===lt(t)?t:t.assignedSlot||t.parentNode||(ut(t)?t.host:null)||yt(t)}function Et(t){return ht(t)&&"fixed"!==bt(t).position?t.offsetParent:null}function Tt(t){for(var e=ct(t),i=Et(t);i&&vt(i)&&"static"===bt(i).position;)i=Et(i);return i&&("html"===lt(i)||"body"===lt(i)&&"static"===bt(i).position)?e:i||function(t){var e=-1!==navigator.userAgent.toLowerCase().indexOf("firefox");if(-1!==navigator.userAgent.indexOf("Trident")&&ht(t)&&"fixed"===bt(t).position)return null;for(var i=wt(t);ht(i)&&["html","body"].indexOf(lt(i))<0;){var n=bt(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function At(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}var Lt=Math.max,Ot=Math.min,kt=Math.round;function Ct(t,e,i){return Lt(t,Ot(e,i))}function xt(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function Dt(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}var Nt={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,n=t.name,s=t.options,o=i.elements.arrow,r=i.modifiersData.popperOffsets,a=pt(i.placement),l=At(a),c=[nt,it].indexOf(a)>=0?"height":"width";if(o&&r){var d=function(t,e){return xt("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:Dt(t,st))}(s.padding,i),h=gt(o),u="y"===l?tt:nt,f="y"===l?et:it,p=i.rects.reference[c]+i.rects.reference[l]-r[l]-i.rects.popper[c],m=r[l]-i.rects.reference[l],g=Tt(o),_=g?"y"===l?g.clientHeight||0:g.clientWidth||0:0,b=p/2-m/2,v=d[u],y=_-h[c]-d[f],w=_/2-h[c]/2+b,E=Ct(v,w,y),T=l;i.modifiersData[n]=((e={})[T]=E,e.centerOffset=E-w,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&_t(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},St={top:"auto",right:"auto",bottom:"auto",left:"auto"};function It(t){var e,i=t.popper,n=t.popperRect,s=t.placement,o=t.offsets,r=t.position,a=t.gpuAcceleration,l=t.adaptive,c=t.roundOffsets,d=!0===c?function(t){var e=t.x,i=t.y,n=window.devicePixelRatio||1;return{x:kt(kt(e*n)/n)||0,y:kt(kt(i*n)/n)||0}}(o):"function"==typeof c?c(o):o,h=d.x,u=void 0===h?0:h,f=d.y,p=void 0===f?0:f,m=o.hasOwnProperty("x"),g=o.hasOwnProperty("y"),_=nt,b=tt,v=window;if(l){var y=Tt(i),w="clientHeight",E="clientWidth";y===ct(i)&&"static"!==bt(y=yt(i)).position&&(w="scrollHeight",E="scrollWidth"),y=y,s===tt&&(b=et,p-=y[w]-n.height,p*=a?1:-1),s===nt&&(_=it,u-=y[E]-n.width,u*=a?1:-1)}var T,A=Object.assign({position:r},l&&St);return a?Object.assign({},A,((T={})[b]=g?"0":"",T[_]=m?"0":"",T.transform=(v.devicePixelRatio||1)<2?"translate("+u+"px, "+p+"px)":"translate3d("+u+"px, "+p+"px, 0)",T)):Object.assign({},A,((e={})[b]=g?p+"px":"",e[_]=m?u+"px":"",e.transform="",e))}var jt={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:pt(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,It(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,It(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}},Pt={passive:!0},Mt={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=ct(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,Pt)})),a&&l.addEventListener("resize",i.update,Pt),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,Pt)})),a&&l.removeEventListener("resize",i.update,Pt)}},data:{}},Ht={left:"right",right:"left",bottom:"top",top:"bottom"};function Rt(t){return t.replace(/left|right|bottom|top/g,(function(t){return Ht[t]}))}var Bt={start:"end",end:"start"};function Wt(t){return t.replace(/start|end/g,(function(t){return Bt[t]}))}function qt(t){var e=ct(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function zt(t){return mt(yt(t)).left+qt(t).scrollLeft}function Ut(t){var e=bt(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function $t(t,e){var i;void 0===e&&(e=[]);var n=function t(e){return["html","body","#document"].indexOf(lt(e))>=0?e.ownerDocument.body:ht(e)&&Ut(e)?e:t(wt(e))}(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=ct(n),r=s?[o].concat(o.visualViewport||[],Ut(n)?n:[]):n,a=e.concat(r);return s?a:a.concat($t(wt(r)))}function Ft(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function Vt(t,e){return"viewport"===e?Ft(function(t){var e=ct(t),i=yt(t),n=e.visualViewport,s=i.clientWidth,o=i.clientHeight,r=0,a=0;return n&&(s=n.width,o=n.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(r=n.offsetLeft,a=n.offsetTop)),{width:s,height:o,x:r+zt(t),y:a}}(t)):ht(e)?function(t){var e=mt(t);return e.top=e.top+t.clientTop,e.left=e.left+t.clientLeft,e.bottom=e.top+t.clientHeight,e.right=e.left+t.clientWidth,e.width=t.clientWidth,e.height=t.clientHeight,e.x=e.left,e.y=e.top,e}(e):Ft(function(t){var e,i=yt(t),n=qt(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=Lt(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=Lt(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+zt(t),l=-n.scrollTop;return"rtl"===bt(s||i).direction&&(a+=Lt(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(yt(t)))}function Kt(t){return t.split("-")[1]}function Xt(t){var e,i=t.reference,n=t.element,s=t.placement,o=s?pt(s):null,r=s?Kt(s):null,a=i.x+i.width/2-n.width/2,l=i.y+i.height/2-n.height/2;switch(o){case tt:e={x:a,y:i.y-n.height};break;case et:e={x:a,y:i.y+i.height};break;case it:e={x:i.x+i.width,y:l};break;case nt:e={x:i.x-n.width,y:l};break;default:e={x:i.x,y:i.y}}var c=o?At(o):null;if(null!=c){var d="y"===c?"height":"width";switch(r){case"start":e[c]=e[c]-(i[d]/2-n[d]/2);break;case"end":e[c]=e[c]+(i[d]/2-n[d]/2)}}return e}function Yt(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=void 0===n?t.placement:n,o=i.boundary,r=void 0===o?"clippingParents":o,a=i.rootBoundary,l=void 0===a?"viewport":a,c=i.elementContext,d=void 0===c?"popper":c,h=i.altBoundary,u=void 0!==h&&h,f=i.padding,p=void 0===f?0:f,m=xt("number"!=typeof p?p:Dt(p,st)),g="popper"===d?"reference":"popper",_=t.elements.reference,b=t.rects.popper,v=t.elements[u?g:d],y=function(t,e,i){var n="clippingParents"===e?function(t){var e=$t(wt(t)),i=["absolute","fixed"].indexOf(bt(t).position)>=0&&ht(t)?Tt(t):t;return dt(i)?e.filter((function(t){return dt(t)&&_t(t,i)&&"body"!==lt(t)})):[]}(t):[].concat(e),s=[].concat(n,[i]),o=s[0],r=s.reduce((function(e,i){var n=Vt(t,i);return e.top=Lt(n.top,e.top),e.right=Ot(n.right,e.right),e.bottom=Ot(n.bottom,e.bottom),e.left=Lt(n.left,e.left),e}),Vt(t,o));return r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}(dt(v)?v:v.contextElement||yt(t.elements.popper),r,l),w=mt(_),E=Xt({reference:w,element:b,strategy:"absolute",placement:s}),T=Ft(Object.assign({},b,E)),A="popper"===d?T:w,L={top:y.top-A.top+m.top,bottom:A.bottom-y.bottom+m.bottom,left:y.left-A.left+m.left,right:A.right-y.right+m.right},O=t.modifiersData.offset;if("popper"===d&&O){var k=O[s];Object.keys(L).forEach((function(t){var e=[it,et].indexOf(t)>=0?1:-1,i=[tt,et].indexOf(t)>=0?"y":"x";L[t]+=k[i]*e}))}return L}function Qt(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,l=i.allowedAutoPlacements,c=void 0===l?rt:l,d=Kt(n),h=d?a?ot:ot.filter((function(t){return Kt(t)===d})):st,u=h.filter((function(t){return c.indexOf(t)>=0}));0===u.length&&(u=h);var f=u.reduce((function(e,i){return e[i]=Yt(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[pt(i)],e}),{});return Object.keys(f).sort((function(t,e){return f[t]-f[e]}))}var Gt={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name;if(!e.modifiersData[n]._skip){for(var s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0===r||r,l=i.fallbackPlacements,c=i.padding,d=i.boundary,h=i.rootBoundary,u=i.altBoundary,f=i.flipVariations,p=void 0===f||f,m=i.allowedAutoPlacements,g=e.options.placement,_=pt(g),b=l||(_!==g&&p?function(t){if("auto"===pt(t))return[];var e=Rt(t);return[Wt(t),e,Wt(e)]}(g):[Rt(g)]),v=[g].concat(b).reduce((function(t,i){return t.concat("auto"===pt(i)?Qt(e,{placement:i,boundary:d,rootBoundary:h,padding:c,flipVariations:p,allowedAutoPlacements:m}):i)}),[]),y=e.rects.reference,w=e.rects.popper,E=new Map,T=!0,A=v[0],L=0;L<v.length;L++){var O=v[L],k=pt(O),C="start"===Kt(O),x=[tt,et].indexOf(k)>=0,D=x?"width":"height",N=Yt(e,{placement:O,boundary:d,rootBoundary:h,altBoundary:u,padding:c}),S=x?C?it:nt:C?et:tt;y[D]>w[D]&&(S=Rt(S));var I=Rt(S),j=[];if(o&&j.push(N[k]<=0),a&&j.push(N[S]<=0,N[I]<=0),j.every((function(t){return t}))){A=O,T=!1;break}E.set(O,j)}if(T)for(var P=function(t){var e=v.find((function(e){var i=E.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return A=e,"break"},M=p?3:1;M>0&&"break"!==P(M);M--);e.placement!==A&&(e.modifiersData[n]._skip=!0,e.placement=A,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function Zt(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function Jt(t){return[tt,it,et,nt].some((function(e){return t[e]>=0}))}var te={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=Yt(e,{elementContext:"reference"}),a=Yt(e,{altBoundary:!0}),l=Zt(r,n),c=Zt(a,s,o),d=Jt(l),h=Jt(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:d,hasPopperEscaped:h},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":d,"data-popper-escaped":h})}},ee={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.offset,o=void 0===s?[0,0]:s,r=rt.reduce((function(t,i){return t[i]=function(t,e,i){var n=pt(t),s=[nt,tt].indexOf(n)>=0?-1:1,o="function"==typeof i?i(Object.assign({},e,{placement:t})):i,r=o[0],a=o[1];return r=r||0,a=(a||0)*s,[nt,it].indexOf(n)>=0?{x:a,y:r}:{x:r,y:a}}(i,e.rects,o),t}),{}),a=r[e.placement],l=a.x,c=a.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=r}},ie={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=Xt({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},ne={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0!==r&&r,l=i.boundary,c=i.rootBoundary,d=i.altBoundary,h=i.padding,u=i.tether,f=void 0===u||u,p=i.tetherOffset,m=void 0===p?0:p,g=Yt(e,{boundary:l,rootBoundary:c,padding:h,altBoundary:d}),_=pt(e.placement),b=Kt(e.placement),v=!b,y=At(_),w="x"===y?"y":"x",E=e.modifiersData.popperOffsets,T=e.rects.reference,A=e.rects.popper,L="function"==typeof m?m(Object.assign({},e.rects,{placement:e.placement})):m,O={x:0,y:0};if(E){if(o||a){var k="y"===y?tt:nt,C="y"===y?et:it,x="y"===y?"height":"width",D=E[y],N=E[y]+g[k],S=E[y]-g[C],I=f?-A[x]/2:0,j="start"===b?T[x]:A[x],P="start"===b?-A[x]:-T[x],M=e.elements.arrow,H=f&&M?gt(M):{width:0,height:0},R=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},B=R[k],W=R[C],q=Ct(0,T[x],H[x]),z=v?T[x]/2-I-q-B-L:j-q-B-L,U=v?-T[x]/2+I+q+W+L:P+q+W+L,$=e.elements.arrow&&Tt(e.elements.arrow),F=$?"y"===y?$.clientTop||0:$.clientLeft||0:0,V=e.modifiersData.offset?e.modifiersData.offset[e.placement][y]:0,K=E[y]+z-V-F,X=E[y]+U-V;if(o){var Y=Ct(f?Ot(N,K):N,D,f?Lt(S,X):S);E[y]=Y,O[y]=Y-D}if(a){var Q="x"===y?tt:nt,G="x"===y?et:it,Z=E[w],J=Z+g[Q],st=Z-g[G],ot=Ct(f?Ot(J,K):J,Z,f?Lt(st,X):st);E[w]=ot,O[w]=ot-Z}}e.modifiersData[n]=O}},requiresIfExists:["offset"]};function se(t,e,i){void 0===i&&(i=!1);var n,s,o=yt(e),r=mt(t),a=ht(e),l={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(a||!a&&!i)&&(("body"!==lt(e)||Ut(o))&&(l=(n=e)!==ct(n)&&ht(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:qt(n)),ht(e)?((c=mt(e)).x+=e.clientLeft,c.y+=e.clientTop):o&&(c.x=zt(o))),{x:r.left+l.scrollLeft-c.x,y:r.top+l.scrollTop-c.y,width:r.width,height:r.height}}var oe={placement:"bottom",modifiers:[],strategy:"absolute"};function re(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return!e.some((function(t){return!(t&&"function"==typeof t.getBoundingClientRect)}))}function ae(t){void 0===t&&(t={});var e=t,i=e.defaultModifiers,n=void 0===i?[]:i,s=e.defaultOptions,o=void 0===s?oe:s;return function(t,e,i){void 0===i&&(i=o);var s,r,a={placement:"bottom",orderedModifiers:[],options:Object.assign({},oe,o),modifiersData:{},elements:{reference:t,popper:e},attributes:{},styles:{}},l=[],c=!1,d={state:a,setOptions:function(i){h(),a.options=Object.assign({},o,a.options,i),a.scrollParents={reference:dt(t)?$t(t):t.contextElement?$t(t.contextElement):[],popper:$t(e)};var s,r,c=function(t){var e=function(t){var e=new Map,i=new Set,n=[];return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||function t(s){i.add(s.name),[].concat(s.requires||[],s.requiresIfExists||[]).forEach((function(n){if(!i.has(n)){var s=e.get(n);s&&t(s)}})),n.push(s)}(t)})),n}(t);return at.reduce((function(t,i){return t.concat(e.filter((function(t){return t.phase===i})))}),[])}((s=[].concat(n,a.options.modifiers),r=s.reduce((function(t,e){var i=t[e.name];return t[e.name]=i?Object.assign({},i,e,{options:Object.assign({},i.options,e.options),data:Object.assign({},i.data,e.data)}):e,t}),{}),Object.keys(r).map((function(t){return r[t]}))));return a.orderedModifiers=c.filter((function(t){return t.enabled})),a.orderedModifiers.forEach((function(t){var e=t.name,i=t.options,n=void 0===i?{}:i,s=t.effect;if("function"==typeof s){var o=s({state:a,name:e,instance:d,options:n});l.push(o||function(){})}})),d.update()},forceUpdate:function(){if(!c){var t=a.elements,e=t.reference,i=t.popper;if(re(e,i)){a.rects={reference:se(e,Tt(i),"fixed"===a.options.strategy),popper:gt(i)},a.reset=!1,a.placement=a.options.placement,a.orderedModifiers.forEach((function(t){return a.modifiersData[t.name]=Object.assign({},t.data)}));for(var n=0;n<a.orderedModifiers.length;n++)if(!0!==a.reset){var s=a.orderedModifiers[n],o=s.fn,r=s.options,l=void 0===r?{}:r,h=s.name;"function"==typeof o&&(a=o({state:a,options:l,name:h,instance:d})||a)}else a.reset=!1,n=-1}}},update:(s=function(){return new Promise((function(t){d.forceUpdate(),t(a)}))},function(){return r||(r=new Promise((function(t){Promise.resolve().then((function(){r=void 0,t(s())}))}))),r}),destroy:function(){h(),c=!0}};if(!re(t,e))return d;function h(){l.forEach((function(t){return t()})),l=[]}return d.setOptions(i).then((function(t){!c&&i.onFirstUpdate&&i.onFirstUpdate(t)})),d}}var le=ae(),ce=ae({defaultModifiers:[Mt,ie,jt,ft]}),de=ae({defaultModifiers:[Mt,ie,jt,ft,ee,Gt,ne,Nt,te]}),he=Object.freeze({__proto__:null,popperGenerator:ae,detectOverflow:Yt,createPopperBase:le,createPopper:de,createPopperLite:ce,top:tt,bottom:et,right:it,left:nt,auto:"auto",basePlacements:st,start:"start",end:"end",clippingParents:"clippingParents",viewport:"viewport",popper:"popper",reference:"reference",variationPlacements:ot,placements:rt,beforeRead:"beforeRead",read:"read",afterRead:"afterRead",beforeMain:"beforeMain",main:"main",afterMain:"afterMain",beforeWrite:"beforeWrite",write:"write",afterWrite:"afterWrite",modifierPhases:at,applyStyles:ft,arrow:Nt,computeStyles:jt,eventListeners:Mt,flip:Gt,hide:te,offset:ee,popperOffsets:ie,preventOverflow:ne});const ue=new RegExp("ArrowUp|ArrowDown|Escape"),fe=_()?"top-end":"top-start",pe=_()?"top-start":"top-end",me=_()?"bottom-end":"bottom-start",ge=_()?"bottom-start":"bottom-end",_e=_()?"left-start":"right-start",be=_()?"right-start":"left-start",ve={offset:[0,2],boundary:"clippingParents",reference:"toggle",display:"dynamic",popperConfig:null,autoClose:!0},ye={offset:"(array|string|function)",boundary:"(string|element)",reference:"(string|element|object)",display:"string",popperConfig:"(null|object|function)",autoClose:"(boolean|string)"};class we extends R{constructor(t,e){super(t),this._popper=null,this._config=this._getConfig(e),this._menu=this._getMenuElement(),this._inNavbar=this._detectNavbar(),this._addEventListeners()}static get Default(){return ve}static get DefaultType(){return ye}static get NAME(){return"dropdown"}toggle(){u(this._element)||(this._element.classList.contains("show")?this.hide():this.show())}show(){if(u(this._element)||this._menu.classList.contains("show"))return;const t=we.getParentFromElement(this._element),e={relatedTarget:this._element};if(!H.trigger(this._element,"show.bs.dropdown",e).defaultPrevented){if(this._inNavbar)U.setDataAttribute(this._menu,"popper","none");else{if(void 0===he)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let e=this._element;"parent"===this._config.reference?e=t:a(this._config.reference)?e=l(this._config.reference):"object"==typeof this._config.reference&&(e=this._config.reference);const i=this._getPopperConfig(),n=i.modifiers.find(t=>"applyStyles"===t.name&&!1===t.enabled);this._popper=de(e,this._menu,i),n&&U.setDataAttribute(this._menu,"popper","static")}"ontouchstart"in document.documentElement&&!t.closest(".navbar-nav")&&[].concat(...document.body.children).forEach(t=>H.on(t,"mouseover",p)),this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.toggle("show"),this._element.classList.toggle("show"),H.trigger(this._element,"shown.bs.dropdown",e)}}hide(){if(u(this._element)||!this._menu.classList.contains("show"))return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_addEventListeners(){H.on(this._element,"click.bs.dropdown",t=>{t.preventDefault(),this.toggle()})}_completeHide(t){H.trigger(this._element,"hide.bs.dropdown",t).defaultPrevented||("ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>H.off(t,"mouseover",p)),this._popper&&this._popper.destroy(),this._menu.classList.remove("show"),this._element.classList.remove("show"),this._element.setAttribute("aria-expanded","false"),U.removeDataAttribute(this._menu,"popper"),H.trigger(this._element,"hidden.bs.dropdown",t))}_getConfig(t){if(t={...this.constructor.Default,...U.getDataAttributes(this._element),...t},d("dropdown",t,this.constructor.DefaultType),"object"==typeof t.reference&&!a(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError("dropdown".toUpperCase()+': Option "reference" provided type "object" without a required "getBoundingClientRect" method.');return t}_getMenuElement(){return t.next(this._element,".dropdown-menu")[0]}_getPlacement(){const t=this._element.parentNode;if(t.classList.contains("dropend"))return _e;if(t.classList.contains("dropstart"))return be;const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?pe:fe:e?ge:me}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map(t=>Number.parseInt(t,10)):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return"static"===this._config.display&&(t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,..."function"==typeof this._config.popperConfig?this._config.popperConfig(t):this._config.popperConfig}}_selectMenuItem(e){const i=t.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter(h);if(!i.length)return;let n=i.indexOf(e.target);"ArrowUp"===e.key&&n>0&&n--,"ArrowDown"===e.key&&n<i.length-1&&n++,n=-1===n?0:n,i[n].focus()}static dropdownInterface(t,e){let i=w.get(t,"bs.dropdown");if(i||(i=new we(t,"object"==typeof e?e:null)),"string"==typeof e){if(void 0===i[e])throw new TypeError(`No method named "${e}"`);i[e]()}}static jQueryInterface(t){return this.each((function(){we.dropdownInterface(this,t)}))}static clearMenus(e){if(e&&(2===e.button||"keyup"===e.type&&"Tab"!==e.key))return;const i=t.find('[data-bs-toggle="dropdown"]');for(let t=0,n=i.length;t<n;t++){const n=w.get(i[t],"bs.dropdown");if(!n||!1===n._config.autoClose)continue;if(!n._element.classList.contains("show"))continue;const s={relatedTarget:n._element};if(e){const t=e.composedPath(),i=t.includes(n._menu);if(t.includes(n._element)||"inside"===n._config.autoClose&&!i||"outside"===n._config.autoClose&&i)continue;if(n._menu.contains(e.target)&&("keyup"===e.type&&"Tab"===e.key||/input|select|option|textarea|form/i.test(e.target.tagName)))continue;"click"===e.type&&(s.clickEvent=e)}n._completeHide(s)}}static getParentFromElement(t){return s(t)||t.parentNode}static dataApiKeydownHandler(e){if(/input|textarea/i.test(e.target.tagName)?"Space"===e.key||"Escape"!==e.key&&("ArrowDown"!==e.key&&"ArrowUp"!==e.key||e.target.closest(".dropdown-menu")):!ue.test(e.key))return;const i=this.classList.contains("show");if(!i&&"Escape"===e.key)return;if(e.preventDefault(),e.stopPropagation(),u(this))return;const n=()=>this.matches('[data-bs-toggle="dropdown"]')?this:t.prev(this,'[data-bs-toggle="dropdown"]')[0];if("Escape"===e.key)return n().focus(),void we.clearMenus();i||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?i&&"Space"!==e.key?we.getInstance(n())._selectMenuItem(e):we.clearMenus():n().click()}}H.on(document,"keydown.bs.dropdown.data-api",'[data-bs-toggle="dropdown"]',we.dataApiKeydownHandler),H.on(document,"keydown.bs.dropdown.data-api",".dropdown-menu",we.dataApiKeydownHandler),H.on(document,"click.bs.dropdown.data-api",we.clearMenus),H.on(document,"keyup.bs.dropdown.data-api",we.clearMenus),H.on(document,"click.bs.dropdown.data-api",'[data-bs-toggle="dropdown"]',(function(t){t.preventDefault(),we.dropdownInterface(this)})),b(we);const Ee=()=>{const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)},Te=(t=Ee())=>{Ae(),Le("body","paddingRight",e=>e+t),Le(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top","paddingRight",e=>e+t),Le(".sticky-top","marginRight",e=>e-t)},Ae=()=>{const t=document.body.style.overflow;t&&U.setDataAttribute(document.body,"overflow",t),document.body.style.overflow="hidden"},Le=(e,i,n)=>{const s=Ee();t.find(e).forEach(t=>{if(t!==document.body&&window.innerWidth>t.clientWidth+s)return;const e=t.style[i],o=window.getComputedStyle(t)[i];U.setDataAttribute(t,i,e),t.style[i]=n(Number.parseFloat(o))+"px"})},Oe=()=>{ke("body","overflow"),ke("body","paddingRight"),ke(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top","paddingRight"),ke(".sticky-top","marginRight")},ke=(e,i)=>{t.find(e).forEach(t=>{const e=U.getDataAttribute(t,i);void 0===e?t.style.removeProperty(i):(U.removeDataAttribute(t,i),t.style[i]=e)})},Ce={isVisible:!0,isAnimated:!1,rootElement:document.body,clickCallback:null},xe={isVisible:"boolean",isAnimated:"boolean",rootElement:"element",clickCallback:"(function|null)"};class De{constructor(t){this._config=this._getConfig(t),this._isAppended=!1,this._element=null}show(t){this._config.isVisible?(this._append(),this._config.isAnimated&&m(this._getElement()),this._getElement().classList.add("show"),this._emulateAnimation(()=>{v(t)})):v(t)}hide(t){this._config.isVisible?(this._getElement().classList.remove("show"),this._emulateAnimation(()=>{this.dispose(),v(t)})):v(t)}_getElement(){if(!this._element){const t=document.createElement("div");t.className="modal-backdrop",this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_getConfig(t){return(t={...Ce,..."object"==typeof t?t:{}}).rootElement=t.rootElement||document.body,d("backdrop",t,xe),t}_append(){this._isAppended||(this._config.rootElement.appendChild(this._getElement()),H.on(this._getElement(),"mousedown.bs.backdrop",()=>{v(this._config.clickCallback)}),this._isAppended=!0)}dispose(){this._isAppended&&(H.off(this._element,"mousedown.bs.backdrop"),this._getElement().parentNode.removeChild(this._element),this._isAppended=!1)}_emulateAnimation(t){if(!this._config.isAnimated)return void v(t);const e=o(this._getElement());H.one(this._getElement(),"transitionend",()=>v(t)),c(this._getElement(),e)}}const Ne={backdrop:!0,keyboard:!0,focus:!0},Se={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean"};class Ie extends R{constructor(e,i){super(e),this._config=this._getConfig(i),this._dialog=t.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._isShown=!1,this._ignoreBackdropClick=!1,this._isTransitioning=!1}static get Default(){return Ne}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){if(this._isShown||this._isTransitioning)return;this._isAnimated()&&(this._isTransitioning=!0);const e=H.trigger(this._element,"show.bs.modal",{relatedTarget:t});this._isShown||e.defaultPrevented||(this._isShown=!0,Te(),document.body.classList.add("modal-open"),this._adjustDialog(),this._setEscapeEvent(),this._setResizeEvent(),H.on(this._element,"click.dismiss.bs.modal",'[data-bs-dismiss="modal"]',t=>this.hide(t)),H.on(this._dialog,"mousedown.dismiss.bs.modal",()=>{H.one(this._element,"mouseup.dismiss.bs.modal",t=>{t.target===this._element&&(this._ignoreBackdropClick=!0)})}),this._showBackdrop(()=>this._showElement(t)))}hide(t){if(t&&t.preventDefault(),!this._isShown||this._isTransitioning)return;if(H.trigger(this._element,"hide.bs.modal").defaultPrevented)return;this._isShown=!1;const e=this._isAnimated();e&&(this._isTransitioning=!0),this._setEscapeEvent(),this._setResizeEvent(),H.off(document,"focusin.bs.modal"),this._element.classList.remove("show"),H.off(this._element,"click.dismiss.bs.modal"),H.off(this._dialog,"mousedown.dismiss.bs.modal"),this._queueCallback(()=>this._hideModal(),this._element,e)}dispose(){[window,this._dialog].forEach(t=>H.off(t,".bs.modal")),this._backdrop.dispose(),super.dispose(),H.off(document,"focusin.bs.modal")}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new De({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_getConfig(t){return t={...Ne,...U.getDataAttributes(this._element),...t},d("modal",t,Se),t}_showElement(e){const i=this._isAnimated(),n=t.findOne(".modal-body",this._dialog);this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0,n&&(n.scrollTop=0),i&&m(this._element),this._element.classList.add("show"),this._config.focus&&this._enforceFocus(),this._queueCallback(()=>{this._config.focus&&this._element.focus(),this._isTransitioning=!1,H.trigger(this._element,"shown.bs.modal",{relatedTarget:e})},this._dialog,i)}_enforceFocus(){H.off(document,"focusin.bs.modal"),H.on(document,"focusin.bs.modal",t=>{document===t.target||this._element===t.target||this._element.contains(t.target)||this._element.focus()})}_setEscapeEvent(){this._isShown?H.on(this._element,"keydown.dismiss.bs.modal",t=>{this._config.keyboard&&"Escape"===t.key?(t.preventDefault(),this.hide()):this._config.keyboard||"Escape"!==t.key||this._triggerBackdropTransition()}):H.off(this._element,"keydown.dismiss.bs.modal")}_setResizeEvent(){this._isShown?H.on(window,"resize.bs.modal",()=>this._adjustDialog()):H.off(window,"resize.bs.modal")}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide(()=>{document.body.classList.remove("modal-open"),this._resetAdjustments(),Oe(),H.trigger(this._element,"hidden.bs.modal")})}_showBackdrop(t){H.on(this._element,"click.dismiss.bs.modal",t=>{this._ignoreBackdropClick?this._ignoreBackdropClick=!1:t.target===t.currentTarget&&(!0===this._config.backdrop?this.hide():"static"===this._config.backdrop&&this._triggerBackdropTransition())}),this._backdrop.show(t)}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(H.trigger(this._element,"hidePrevented.bs.modal").defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight;t||(this._element.style.overflowY="hidden"),this._element.classList.add("modal-static");const e=o(this._dialog);H.off(this._element,"transitionend"),H.one(this._element,"transitionend",()=>{this._element.classList.remove("modal-static"),t||(H.one(this._element,"transitionend",()=>{this._element.style.overflowY=""}),c(this._element,e))}),c(this._element,e),this._element.focus()}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=Ee(),i=e>0;(!i&&t&&!_()||i&&!t&&_())&&(this._element.style.paddingLeft=e+"px"),(i&&!t&&!_()||!i&&t&&_())&&(this._element.style.paddingRight=e+"px")}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=Ie.getInstance(this)||new Ie(this,"object"==typeof t?t:{});if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}H.on(document,"click.bs.modal.data-api",'[data-bs-toggle="modal"]',(function(t){const e=s(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),H.one(e,"show.bs.modal",t=>{t.defaultPrevented||H.one(e,"hidden.bs.modal",()=>{h(this)&&this.focus()})}),(Ie.getInstance(e)||new Ie(e)).toggle(this)})),b(Ie);const je={backdrop:!0,keyboard:!0,scroll:!1},Pe={backdrop:"boolean",keyboard:"boolean",scroll:"boolean"};class Me extends R{constructor(t,e){super(t),this._config=this._getConfig(e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._addEventListeners()}static get NAME(){return"offcanvas"}static get Default(){return je}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||H.trigger(this._element,"show.bs.offcanvas",{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._element.style.visibility="visible",this._backdrop.show(),this._config.scroll||(Te(),this._enforceFocusOnElement(this._element)),this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add("show"),this._queueCallback(()=>{H.trigger(this._element,"shown.bs.offcanvas",{relatedTarget:t})},this._element,!0))}hide(){this._isShown&&(H.trigger(this._element,"hide.bs.offcanvas").defaultPrevented||(H.off(document,"focusin.bs.offcanvas"),this._element.blur(),this._isShown=!1,this._element.classList.remove("show"),this._backdrop.hide(),this._queueCallback(()=>{this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._element.style.visibility="hidden",this._config.scroll||Oe(),H.trigger(this._element,"hidden.bs.offcanvas")},this._element,!0)))}dispose(){this._backdrop.dispose(),super.dispose(),H.off(document,"focusin.bs.offcanvas")}_getConfig(t){return t={...je,...U.getDataAttributes(this._element),..."object"==typeof t?t:{}},d("offcanvas",t,Pe),t}_initializeBackDrop(){return new De({isVisible:this._config.backdrop,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:()=>this.hide()})}_enforceFocusOnElement(t){H.off(document,"focusin.bs.offcanvas"),H.on(document,"focusin.bs.offcanvas",e=>{document===e.target||t===e.target||t.contains(e.target)||t.focus()}),t.focus()}_addEventListeners(){H.on(this._element,"click.dismiss.bs.offcanvas",'[data-bs-dismiss="offcanvas"]',()=>this.hide()),H.on(this._element,"keydown.dismiss.bs.offcanvas",t=>{this._config.keyboard&&"Escape"===t.key&&this.hide()})}static jQueryInterface(t){return this.each((function(){const e=w.get(this,"bs.offcanvas")||new Me(this,"object"==typeof t?t:{});if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}H.on(document,"click.bs.offcanvas.data-api",'[data-bs-toggle="offcanvas"]',(function(e){const i=s(this);if(["A","AREA"].includes(this.tagName)&&e.preventDefault(),u(this))return;H.one(i,"hidden.bs.offcanvas",()=>{h(this)&&this.focus()});const n=t.findOne(".offcanvas.show");n&&n!==i&&Me.getInstance(n).hide(),(w.get(i,"bs.offcanvas")||new Me(i)).toggle(this)})),H.on(window,"load.bs.offcanvas.data-api",()=>{t.find(".offcanvas.show").forEach(t=>(w.get(t,"bs.offcanvas")||new Me(t)).show())}),b(Me);const He=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Re=/^(?:(?:https?|mailto|ftp|tel|file):|[^#&/:?]*(?:[#/?]|$))/i,Be=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i,We=(t,e)=>{const i=t.nodeName.toLowerCase();if(e.includes(i))return!He.has(i)||Boolean(Re.test(t.nodeValue)||Be.test(t.nodeValue));const n=e.filter(t=>t instanceof RegExp);for(let t=0,e=n.length;t<e;t++)if(n[t].test(i))return!0;return!1};function qe(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=Object.keys(e),o=[].concat(...n.body.querySelectorAll("*"));for(let t=0,i=o.length;t<i;t++){const i=o[t],n=i.nodeName.toLowerCase();if(!s.includes(n)){i.parentNode.removeChild(i);continue}const r=[].concat(...i.attributes),a=[].concat(e["*"]||[],e[n]||[]);r.forEach(t=>{We(t,a)||i.removeAttribute(t.nodeName)})}return n.body.innerHTML}const ze=new RegExp("(^|\\s)bs-tooltip\\S+","g"),Ue=new Set(["sanitize","allowList","sanitizeFn"]),$e={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(array|string|function)",container:"(string|element|boolean)",fallbackPlacements:"array",boundary:"(string|element)",customClass:"(string|function)",sanitize:"boolean",sanitizeFn:"(null|function)",allowList:"object",popperConfig:"(null|object|function)"},Fe={AUTO:"auto",TOP:"top",RIGHT:_()?"left":"right",BOTTOM:"bottom",LEFT:_()?"right":"left"},Ve={animation:!0,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:[0,0],container:!1,fallbackPlacements:["top","right","bottom","left"],boundary:"clippingParents",customClass:"",sanitize:!0,sanitizeFn:null,allowList:{"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},popperConfig:null},Ke={HIDE:"hide.bs.tooltip",HIDDEN:"hidden.bs.tooltip",SHOW:"show.bs.tooltip",SHOWN:"shown.bs.tooltip",INSERTED:"inserted.bs.tooltip",CLICK:"click.bs.tooltip",FOCUSIN:"focusin.bs.tooltip",FOCUSOUT:"focusout.bs.tooltip",MOUSEENTER:"mouseenter.bs.tooltip",MOUSELEAVE:"mouseleave.bs.tooltip"};class Xe extends R{constructor(t,e){if(void 0===he)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t),this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this._config=this._getConfig(e),this.tip=null,this._setListeners()}static get Default(){return Ve}static get NAME(){return"tooltip"}static get Event(){return Ke}static get DefaultType(){return $e}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(t){if(this._isEnabled)if(t){const e=this._initializeOnDelegatedTarget(t);e._activeTrigger.click=!e._activeTrigger.click,e._isWithActiveTrigger()?e._enter(null,e):e._leave(null,e)}else{if(this.getTipElement().classList.contains("show"))return void this._leave(null,this);this._enter(null,this)}}dispose(){clearTimeout(this._timeout),H.off(this._element.closest(".modal"),"hide.bs.modal",this._hideModalHandler),this.tip&&this.tip.parentNode&&this.tip.parentNode.removeChild(this.tip),this._popper&&this._popper.destroy(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this.isWithContent()||!this._isEnabled)return;const t=H.trigger(this._element,this.constructor.Event.SHOW),i=f(this._element),n=null===i?this._element.ownerDocument.documentElement.contains(this._element):i.contains(this._element);if(t.defaultPrevented||!n)return;const s=this.getTipElement(),o=e(this.constructor.NAME);s.setAttribute("id",o),this._element.setAttribute("aria-describedby",o),this.setContent(),this._config.animation&&s.classList.add("fade");const r="function"==typeof this._config.placement?this._config.placement.call(this,s,this._element):this._config.placement,a=this._getAttachment(r);this._addAttachmentClass(a);const{container:l}=this._config;w.set(s,this.constructor.DATA_KEY,this),this._element.ownerDocument.documentElement.contains(this.tip)||(l.appendChild(s),H.trigger(this._element,this.constructor.Event.INSERTED)),this._popper?this._popper.update():this._popper=de(this._element,s,this._getPopperConfig(a)),s.classList.add("show");const c="function"==typeof this._config.customClass?this._config.customClass():this._config.customClass;c&&s.classList.add(...c.split(" ")),"ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>{H.on(t,"mouseover",p)});const d=this.tip.classList.contains("fade");this._queueCallback(()=>{const t=this._hoverState;this._hoverState=null,H.trigger(this._element,this.constructor.Event.SHOWN),"out"===t&&this._leave(null,this)},this.tip,d)}hide(){if(!this._popper)return;const t=this.getTipElement();if(H.trigger(this._element,this.constructor.Event.HIDE).defaultPrevented)return;t.classList.remove("show"),"ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>H.off(t,"mouseover",p)),this._activeTrigger.click=!1,this._activeTrigger.focus=!1,this._activeTrigger.hover=!1;const e=this.tip.classList.contains("fade");this._queueCallback(()=>{this._isWithActiveTrigger()||("show"!==this._hoverState&&t.parentNode&&t.parentNode.removeChild(t),this._cleanTipClass(),this._element.removeAttribute("aria-describedby"),H.trigger(this._element,this.constructor.Event.HIDDEN),this._popper&&(this._popper.destroy(),this._popper=null))},this.tip,e),this._hoverState=""}update(){null!==this._popper&&this._popper.update()}isWithContent(){return Boolean(this.getTitle())}getTipElement(){if(this.tip)return this.tip;const t=document.createElement("div");return t.innerHTML=this._config.template,this.tip=t.children[0],this.tip}setContent(){const e=this.getTipElement();this.setElementContent(t.findOne(".tooltip-inner",e),this.getTitle()),e.classList.remove("fade","show")}setElementContent(t,e){if(null!==t)return a(e)?(e=l(e),void(this._config.html?e.parentNode!==t&&(t.innerHTML="",t.appendChild(e)):t.textContent=e.textContent)):void(this._config.html?(this._config.sanitize&&(e=qe(e,this._config.allowList,this._config.sanitizeFn)),t.innerHTML=e):t.textContent=e)}getTitle(){let t=this._element.getAttribute("data-bs-original-title");return t||(t="function"==typeof this._config.title?this._config.title.call(this._element):this._config.title),t}updateAttachment(t){return"right"===t?"end":"left"===t?"start":t}_initializeOnDelegatedTarget(t,e){const i=this.constructor.DATA_KEY;return(e=e||w.get(t.delegateTarget,i))||(e=new this.constructor(t.delegateTarget,this._getDelegateConfig()),w.set(t.delegateTarget,i,e)),e}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map(t=>Number.parseInt(t,10)):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"onChange",enabled:!0,phase:"afterWrite",fn:t=>this._handlePopperPlacementChange(t)}],onFirstUpdate:t=>{t.options.placement!==t.placement&&this._handlePopperPlacementChange(t)}};return{...e,..."function"==typeof this._config.popperConfig?this._config.popperConfig(e):this._config.popperConfig}}_addAttachmentClass(t){this.getTipElement().classList.add("bs-tooltip-"+this.updateAttachment(t))}_getAttachment(t){return Fe[t.toUpperCase()]}_setListeners(){this._config.trigger.split(" ").forEach(t=>{if("click"===t)H.on(this._element,this.constructor.Event.CLICK,this._config.selector,t=>this.toggle(t));else if("manual"!==t){const e="hover"===t?this.constructor.Event.MOUSEENTER:this.constructor.Event.FOCUSIN,i="hover"===t?this.constructor.Event.MOUSELEAVE:this.constructor.Event.FOCUSOUT;H.on(this._element,e,this._config.selector,t=>this._enter(t)),H.on(this._element,i,this._config.selector,t=>this._leave(t))}}),this._hideModalHandler=()=>{this._element&&this.hide()},H.on(this._element.closest(".modal"),"hide.bs.modal",this._hideModalHandler),this._config.selector?this._config={...this._config,trigger:"manual",selector:""}:this._fixTitle()}_fixTitle(){const t=this._element.getAttribute("title"),e=typeof this._element.getAttribute("data-bs-original-title");(t||"string"!==e)&&(this._element.setAttribute("data-bs-original-title",t||""),!t||this._element.getAttribute("aria-label")||this._element.textContent||this._element.setAttribute("aria-label",t),this._element.setAttribute("title",""))}_enter(t,e){e=this._initializeOnDelegatedTarget(t,e),t&&(e._activeTrigger["focusin"===t.type?"focus":"hover"]=!0),e.getTipElement().classList.contains("show")||"show"===e._hoverState?e._hoverState="show":(clearTimeout(e._timeout),e._hoverState="show",e._config.delay&&e._config.delay.show?e._timeout=setTimeout(()=>{"show"===e._hoverState&&e.show()},e._config.delay.show):e.show())}_leave(t,e){e=this._initializeOnDelegatedTarget(t,e),t&&(e._activeTrigger["focusout"===t.type?"focus":"hover"]=e._element.contains(t.relatedTarget)),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState="out",e._config.delay&&e._config.delay.hide?e._timeout=setTimeout(()=>{"out"===e._hoverState&&e.hide()},e._config.delay.hide):e.hide())}_isWithActiveTrigger(){for(const t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1}_getConfig(t){const e=U.getDataAttributes(this._element);return Object.keys(e).forEach(t=>{Ue.has(t)&&delete e[t]}),(t={...this.constructor.Default,...e,..."object"==typeof t&&t?t:{}}).container=!1===t.container?document.body:l(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),d("tooltip",t,this.constructor.DefaultType),t.sanitize&&(t.template=qe(t.template,t.allowList,t.sanitizeFn)),t}_getDelegateConfig(){const t={};if(this._config)for(const e in this._config)this.constructor.Default[e]!==this._config[e]&&(t[e]=this._config[e]);return t}_cleanTipClass(){const t=this.getTipElement(),e=t.getAttribute("class").match(ze);null!==e&&e.length>0&&e.map(t=>t.trim()).forEach(e=>t.classList.remove(e))}_handlePopperPlacementChange(t){const{state:e}=t;e&&(this.tip=e.elements.popper,this._cleanTipClass(),this._addAttachmentClass(this._getAttachment(e.placement)))}static jQueryInterface(t){return this.each((function(){let e=w.get(this,"bs.tooltip");const i="object"==typeof t&&t;if((e||!/dispose|hide/.test(t))&&(e||(e=new Xe(this,i)),"string"==typeof t)){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}b(Xe);const Ye=new RegExp("(^|\\s)bs-popover\\S+","g"),Qe={...Xe.Default,placement:"right",offset:[0,8],trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'},Ge={...Xe.DefaultType,content:"(string|element|function)"},Ze={HIDE:"hide.bs.popover",HIDDEN:"hidden.bs.popover",SHOW:"show.bs.popover",SHOWN:"shown.bs.popover",INSERTED:"inserted.bs.popover",CLICK:"click.bs.popover",FOCUSIN:"focusin.bs.popover",FOCUSOUT:"focusout.bs.popover",MOUSEENTER:"mouseenter.bs.popover",MOUSELEAVE:"mouseleave.bs.popover"};class Je extends Xe{static get Default(){return Qe}static get NAME(){return"popover"}static get Event(){return Ze}static get DefaultType(){return Ge}isWithContent(){return this.getTitle()||this._getContent()}setContent(){const e=this.getTipElement();this.setElementContent(t.findOne(".popover-header",e),this.getTitle());let i=this._getContent();"function"==typeof i&&(i=i.call(this._element)),this.setElementContent(t.findOne(".popover-body",e),i),e.classList.remove("fade","show")}_addAttachmentClass(t){this.getTipElement().classList.add("bs-popover-"+this.updateAttachment(t))}_getContent(){return this._element.getAttribute("data-bs-content")||this._config.content}_cleanTipClass(){const t=this.getTipElement(),e=t.getAttribute("class").match(Ye);null!==e&&e.length>0&&e.map(t=>t.trim()).forEach(e=>t.classList.remove(e))}static jQueryInterface(t){return this.each((function(){let e=w.get(this,"bs.popover");const i="object"==typeof t?t:null;if((e||!/dispose|hide/.test(t))&&(e||(e=new Je(this,i),w.set(this,"bs.popover",e)),"string"==typeof t)){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}b(Je);const ti={offset:10,method:"auto",target:""},ei={offset:"number",method:"string",target:"(string|element)"};class ii extends R{constructor(t,e){super(t),this._scrollElement="BODY"===this._element.tagName?window:this._element,this._config=this._getConfig(e),this._selector=`${this._config.target} .nav-link, ${this._config.target} .list-group-item, ${this._config.target} .dropdown-item`,this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,H.on(this._scrollElement,"scroll.bs.scrollspy",()=>this._process()),this.refresh(),this._process()}static get Default(){return ti}static get NAME(){return"scrollspy"}refresh(){const e=this._scrollElement===this._scrollElement.window?"offset":"position",i="auto"===this._config.method?e:this._config.method,s="position"===i?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),t.find(this._selector).map(e=>{const o=n(e),r=o?t.findOne(o):null;if(r){const t=r.getBoundingClientRect();if(t.width||t.height)return[U[i](r).top+s,o]}return null}).filter(t=>t).sort((t,e)=>t[0]-e[0]).forEach(t=>{this._offsets.push(t[0]),this._targets.push(t[1])})}dispose(){H.off(this._scrollElement,".bs.scrollspy"),super.dispose()}_getConfig(t){if("string"!=typeof(t={...ti,...U.getDataAttributes(this._element),..."object"==typeof t&&t?t:{}}).target&&a(t.target)){let{id:i}=t.target;i||(i=e("scrollspy"),t.target.id=i),t.target="#"+i}return d("scrollspy",t,ei),t}_getScrollTop(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop}_getScrollHeight(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}_getOffsetHeight(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height}_process(){const t=this._getScrollTop()+this._config.offset,e=this._getScrollHeight(),i=this._config.offset+e-this._getOffsetHeight();if(this._scrollHeight!==e&&this.refresh(),t>=i){const t=this._targets[this._targets.length-1];this._activeTarget!==t&&this._activate(t)}else{if(this._activeTarget&&t<this._offsets[0]&&this._offsets[0]>0)return this._activeTarget=null,void this._clear();for(let e=this._offsets.length;e--;)this._activeTarget!==this._targets[e]&&t>=this._offsets[e]&&(void 0===this._offsets[e+1]||t<this._offsets[e+1])&&this._activate(this._targets[e])}}_activate(e){this._activeTarget=e,this._clear();const i=this._selector.split(",").map(t=>`${t}[data-bs-target="${e}"],${t}[href="${e}"]`),n=t.findOne(i.join(","));n.classList.contains("dropdown-item")?(t.findOne(".dropdown-toggle",n.closest(".dropdown")).classList.add("active"),n.classList.add("active")):(n.classList.add("active"),t.parents(n,".nav, .list-group").forEach(e=>{t.prev(e,".nav-link, .list-group-item").forEach(t=>t.classList.add("active")),t.prev(e,".nav-item").forEach(e=>{t.children(e,".nav-link").forEach(t=>t.classList.add("active"))})})),H.trigger(this._scrollElement,"activate.bs.scrollspy",{relatedTarget:e})}_clear(){t.find(this._selector).filter(t=>t.classList.contains("active")).forEach(t=>t.classList.remove("active"))}static jQueryInterface(t){return this.each((function(){const e=ii.getInstance(this)||new ii(this,"object"==typeof t?t:{});if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}H.on(window,"load.bs.scrollspy.data-api",()=>{t.find('[data-bs-spy="scroll"]').forEach(t=>new ii(t))}),b(ii);class ni extends R{static get NAME(){return"tab"}show(){if(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&this._element.classList.contains("active"))return;let e;const i=s(this._element),n=this._element.closest(".nav, .list-group");if(n){const i="UL"===n.nodeName||"OL"===n.nodeName?":scope > li > .active":".active";e=t.find(i,n),e=e[e.length-1]}const o=e?H.trigger(e,"hide.bs.tab",{relatedTarget:this._element}):null;if(H.trigger(this._element,"show.bs.tab",{relatedTarget:e}).defaultPrevented||null!==o&&o.defaultPrevented)return;this._activate(this._element,n);const r=()=>{H.trigger(e,"hidden.bs.tab",{relatedTarget:this._element}),H.trigger(this._element,"shown.bs.tab",{relatedTarget:e})};i?this._activate(i,i.parentNode,r):r()}_activate(e,i,n){const s=(!i||"UL"!==i.nodeName&&"OL"!==i.nodeName?t.children(i,".active"):t.find(":scope > li > .active",i))[0],o=n&&s&&s.classList.contains("fade"),r=()=>this._transitionComplete(e,s,n);s&&o?(s.classList.remove("show"),this._queueCallback(r,e,!0)):r()}_transitionComplete(e,i,n){if(i){i.classList.remove("active");const e=t.findOne(":scope > .dropdown-menu .active",i.parentNode);e&&e.classList.remove("active"),"tab"===i.getAttribute("role")&&i.setAttribute("aria-selected",!1)}e.classList.add("active"),"tab"===e.getAttribute("role")&&e.setAttribute("aria-selected",!0),m(e),e.classList.contains("fade")&&e.classList.add("show");let s=e.parentNode;if(s&&"LI"===s.nodeName&&(s=s.parentNode),s&&s.classList.contains("dropdown-menu")){const i=e.closest(".dropdown");i&&t.find(".dropdown-toggle",i).forEach(t=>t.classList.add("active")),e.setAttribute("aria-expanded",!0)}n&&n()}static jQueryInterface(t){return this.each((function(){const e=w.get(this,"bs.tab")||new ni(this);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}H.on(document,"click.bs.tab.data-api",'[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),u(this)||(w.get(this,"bs.tab")||new ni(this)).show()})),b(ni);const si={animation:"boolean",autohide:"boolean",delay:"number"},oi={animation:!0,autohide:!0,delay:5e3};class ri extends R{constructor(t,e){super(t),this._config=this._getConfig(e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get DefaultType(){return si}static get Default(){return oi}static get NAME(){return"toast"}show(){H.trigger(this._element,"show.bs.toast").defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove("hide"),m(this._element),this._element.classList.add("showing"),this._queueCallback(()=>{this._element.classList.remove("showing"),this._element.classList.add("show"),H.trigger(this._element,"shown.bs.toast"),this._maybeScheduleHide()},this._element,this._config.animation))}hide(){this._element.classList.contains("show")&&(H.trigger(this._element,"hide.bs.toast").defaultPrevented||(this._element.classList.remove("show"),this._queueCallback(()=>{this._element.classList.add("hide"),H.trigger(this._element,"hidden.bs.toast")},this._element,this._config.animation)))}dispose(){this._clearTimeout(),this._element.classList.contains("show")&&this._element.classList.remove("show"),super.dispose()}_getConfig(t){return t={...oi,...U.getDataAttributes(this._element),..."object"==typeof t&&t?t:{}},d("toast",t,this.constructor.DefaultType),t}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout(()=>{this.hide()},this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){H.on(this._element,"click.dismiss.bs.toast",'[data-bs-dismiss="toast"]',()=>this.hide()),H.on(this._element,"mouseover.bs.toast",t=>this._onInteraction(t,!0)),H.on(this._element,"mouseout.bs.toast",t=>this._onInteraction(t,!1)),H.on(this._element,"focusin.bs.toast",t=>this._onInteraction(t,!0)),H.on(this._element,"focusout.bs.toast",t=>this._onInteraction(t,!1))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){let e=w.get(this,"bs.toast");if(e||(e=new ri(this,"object"==typeof t&&t)),"string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return b(ri),{Alert:B,Button:W,Carousel:Q,Collapse:J,Dropdown:we,Modal:Ie,Offcanvas:Me,Popover:Je,ScrollSpy:ii,Tab:ni,Toast:ri,Tooltip:Xe}}));
+//# sourceMappingURL=bootstrap.bundle.min.js.map \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.min.js b/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.min.js
new file mode 100644
index 0000000..e364a13
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/js/bootstrap/bootstrap.min.js
@@ -0,0 +1,7 @@
+/*!
+ * Bootstrap v3.3.6 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under the MIT license
+ */
+if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.6",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");
+d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.6",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/js/datatables/jquery.dataTables.js b/op25/gr-op25_repeater/apps/oplog/op25/static/js/datatables/jquery.dataTables.js
new file mode 100644
index 0000000..c061fd7
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/js/datatables/jquery.dataTables.js
@@ -0,0 +1,15212 @@
+/*! DataTables 1.10.10
+ * ©2008-2015 SpryMedia Ltd - datatables.net/license
+ */
+
+/**
+ * @summary DataTables
+ * @description Paginate, search and order HTML tables
+ * @version 1.10.10
+ * @file jquery.dataTables.js
+ * @author SpryMedia Ltd (www.sprymedia.co.uk)
+ * @contact www.sprymedia.co.uk/contact
+ * @copyright Copyright 2008-2015 SpryMedia Ltd.
+ *
+ * This source file is free software, available under the following license:
+ * MIT license - http://datatables.net/license
+ *
+ * This source file is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
+ *
+ * For details please refer to: http://www.datatables.net
+ */
+
+/*jslint evil: true, undef: true, browser: true */
+/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
+
+(function( factory ) {
+ "use strict";
+
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD
+ define( ['jquery'], function ( $ ) {
+ return factory( $, window, document );
+ } );
+ }
+ else if ( typeof exports === 'object' ) {
+ // CommonJS
+ module.exports = function (root, $) {
+ if ( ! root ) {
+ // CommonJS environments without a window global must pass a
+ // root. This will give an error otherwise
+ root = window;
+ }
+
+ if ( ! $ ) {
+ $ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
+ require('jquery') :
+ require('jquery')( root );
+ }
+
+ return factory( $, root, root.document );
+ };
+ }
+ else {
+ // Browser
+ factory( jQuery, window, document );
+ }
+}
+(function( $, window, document, undefined ) {
+ "use strict";
+
+ /**
+ * DataTables is a plug-in for the jQuery Javascript library. It is a highly
+ * flexible tool, based upon the foundations of progressive enhancement,
+ * which will add advanced interaction controls to any HTML table. For a
+ * full list of features please refer to
+ * [DataTables.net](href="http://datatables.net).
+ *
+ * Note that the `DataTable` object is not a global variable but is aliased
+ * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
+ * be accessed.
+ *
+ * @class
+ * @param {object} [init={}] Configuration object for DataTables. Options
+ * are defined by {@link DataTable.defaults}
+ * @requires jQuery 1.7+
+ *
+ * @example
+ * // Basic initialisation
+ * $(document).ready( function {
+ * $('#example').dataTable();
+ * } );
+ *
+ * @example
+ * // Initialisation with configuration options - in this case, disable
+ * // pagination and sorting.
+ * $(document).ready( function {
+ * $('#example').dataTable( {
+ * "paginate": false,
+ * "sort": false
+ * } );
+ * } );
+ */
+ var DataTable;
+
+
+ /*
+ * It is useful to have variables which are scoped locally so only the
+ * DataTables functions can access them and they don't leak into global space.
+ * At the same time these functions are often useful over multiple files in the
+ * core and API, so we list, or at least document, all variables which are used
+ * by DataTables as private variables here. This also ensures that there is no
+ * clashing of variable names and that they can easily referenced for reuse.
+ */
+
+
+ // Defined else where
+ // _selector_run
+ // _selector_opts
+ // _selector_first
+ // _selector_row_indexes
+
+ var _ext; // DataTable.ext
+ var _Api; // DataTable.Api
+ var _api_register; // DataTable.Api.register
+ var _api_registerPlural; // DataTable.Api.registerPlural
+
+ var _re_dic = {};
+ var _re_new_lines = /[\r\n]/g;
+ var _re_html = /<.*?>/g;
+ var _re_date_start = /^[\w\+\-]/;
+ var _re_date_end = /[\w\+\-]$/;
+
+ // Escape regular expression special characters
+ var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' );
+
+ // http://en.wikipedia.org/wiki/Foreign_exchange_market
+ // - \u20BD - Russian ruble.
+ // - \u20a9 - South Korean Won
+ // - \u20BA - Turkish Lira
+ // - \u20B9 - Indian Rupee
+ // - R - Brazil (R$) and South Africa
+ // - fr - Swiss Franc
+ // - kr - Swedish krona, Norwegian krone and Danish krone
+ // - \u2009 is thin space and \u202F is narrow no-break space, both used in many
+ // standards as thousands separators.
+ var _re_formatted_numeric = /[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi;
+
+
+ var _empty = function ( d ) {
+ return !d || d === true || d === '-' ? true : false;
+ };
+
+
+ var _intVal = function ( s ) {
+ var integer = parseInt( s, 10 );
+ return !isNaN(integer) && isFinite(s) ? integer : null;
+ };
+
+ // Convert from a formatted number with characters other than `.` as the
+ // decimal place, to a Javascript number
+ var _numToDecimal = function ( num, decimalPoint ) {
+ // Cache created regular expressions for speed as this function is called often
+ if ( ! _re_dic[ decimalPoint ] ) {
+ _re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' );
+ }
+ return typeof num === 'string' && decimalPoint !== '.' ?
+ num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) :
+ num;
+ };
+
+
+ var _isNumber = function ( d, decimalPoint, formatted ) {
+ var strType = typeof d === 'string';
+
+ // If empty return immediately so there must be a number if it is a
+ // formatted string (this stops the string "k", or "kr", etc being detected
+ // as a formatted number for currency
+ if ( _empty( d ) ) {
+ return true;
+ }
+
+ if ( decimalPoint && strType ) {
+ d = _numToDecimal( d, decimalPoint );
+ }
+
+ if ( formatted && strType ) {
+ d = d.replace( _re_formatted_numeric, '' );
+ }
+
+ return !isNaN( parseFloat(d) ) && isFinite( d );
+ };
+
+
+ // A string without HTML in it can be considered to be HTML still
+ var _isHtml = function ( d ) {
+ return _empty( d ) || typeof d === 'string';
+ };
+
+
+ var _htmlNumeric = function ( d, decimalPoint, formatted ) {
+ if ( _empty( d ) ) {
+ return true;
+ }
+
+ var html = _isHtml( d );
+ return ! html ?
+ null :
+ _isNumber( _stripHtml( d ), decimalPoint, formatted ) ?
+ true :
+ null;
+ };
+
+
+ var _pluck = function ( a, prop, prop2 ) {
+ var out = [];
+ var i=0, ien=a.length;
+
+ // Could have the test in the loop for slightly smaller code, but speed
+ // is essential here
+ if ( prop2 !== undefined ) {
+ for ( ; i<ien ; i++ ) {
+ if ( a[i] && a[i][ prop ] ) {
+ out.push( a[i][ prop ][ prop2 ] );
+ }
+ }
+ }
+ else {
+ for ( ; i<ien ; i++ ) {
+ if ( a[i] ) {
+ out.push( a[i][ prop ] );
+ }
+ }
+ }
+
+ return out;
+ };
+
+
+ // Basically the same as _pluck, but rather than looping over `a` we use `order`
+ // as the indexes to pick from `a`
+ var _pluck_order = function ( a, order, prop, prop2 )
+ {
+ var out = [];
+ var i=0, ien=order.length;
+
+ // Could have the test in the loop for slightly smaller code, but speed
+ // is essential here
+ if ( prop2 !== undefined ) {
+ for ( ; i<ien ; i++ ) {
+ if ( a[ order[i] ][ prop ] ) {
+ out.push( a[ order[i] ][ prop ][ prop2 ] );
+ }
+ }
+ }
+ else {
+ for ( ; i<ien ; i++ ) {
+ out.push( a[ order[i] ][ prop ] );
+ }
+ }
+
+ return out;
+ };
+
+
+ var _range = function ( len, start )
+ {
+ var out = [];
+ var end;
+
+ if ( start === undefined ) {
+ start = 0;
+ end = len;
+ }
+ else {
+ end = start;
+ start = len;
+ }
+
+ for ( var i=start ; i<end ; i++ ) {
+ out.push( i );
+ }
+
+ return out;
+ };
+
+
+ var _removeEmpty = function ( a )
+ {
+ var out = [];
+
+ for ( var i=0, ien=a.length ; i<ien ; i++ ) {
+ if ( a[i] ) { // careful - will remove all falsy values!
+ out.push( a[i] );
+ }
+ }
+
+ return out;
+ };
+
+
+ var _stripHtml = function ( d ) {
+ return d.replace( _re_html, '' );
+ };
+
+
+ /**
+ * Find the unique elements in a source array.
+ *
+ * @param {array} src Source array
+ * @return {array} Array of unique items
+ * @ignore
+ */
+ var _unique = function ( src )
+ {
+ // A faster unique method is to use object keys to identify used values,
+ // but this doesn't work with arrays or objects, which we must also
+ // consider. See jsperf.com/compare-array-unique-versions/4 for more
+ // information.
+ var
+ out = [],
+ val,
+ i, ien=src.length,
+ j, k=0;
+
+ again: for ( i=0 ; i<ien ; i++ ) {
+ val = src[i];
+
+ for ( j=0 ; j<k ; j++ ) {
+ if ( out[j] === val ) {
+ continue again;
+ }
+ }
+
+ out.push( val );
+ k++;
+ }
+
+ return out;
+ };
+
+
+
+ /**
+ * Create a mapping object that allows camel case parameters to be looked up
+ * for their Hungarian counterparts. The mapping is stored in a private
+ * parameter called `_hungarianMap` which can be accessed on the source object.
+ * @param {object} o
+ * @memberof DataTable#oApi
+ */
+ function _fnHungarianMap ( o )
+ {
+ var
+ hungarian = 'a aa ai ao as b fn i m o s ',
+ match,
+ newKey,
+ map = {};
+
+ $.each( o, function (key, val) {
+ match = key.match(/^([^A-Z]+?)([A-Z])/);
+
+ if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
+ {
+ newKey = key.replace( match[0], match[2].toLowerCase() );
+ map[ newKey ] = key;
+
+ if ( match[1] === 'o' )
+ {
+ _fnHungarianMap( o[key] );
+ }
+ }
+ } );
+
+ o._hungarianMap = map;
+ }
+
+
+ /**
+ * Convert from camel case parameters to Hungarian, based on a Hungarian map
+ * created by _fnHungarianMap.
+ * @param {object} src The model object which holds all parameters that can be
+ * mapped.
+ * @param {object} user The object to convert from camel case to Hungarian.
+ * @param {boolean} force When set to `true`, properties which already have a
+ * Hungarian value in the `user` object will be overwritten. Otherwise they
+ * won't be.
+ * @memberof DataTable#oApi
+ */
+ function _fnCamelToHungarian ( src, user, force )
+ {
+ if ( ! src._hungarianMap ) {
+ _fnHungarianMap( src );
+ }
+
+ var hungarianKey;
+
+ $.each( user, function (key, val) {
+ hungarianKey = src._hungarianMap[ key ];
+
+ if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
+ {
+ // For objects, we need to buzz down into the object to copy parameters
+ if ( hungarianKey.charAt(0) === 'o' )
+ {
+ // Copy the camelCase options over to the hungarian
+ if ( ! user[ hungarianKey ] ) {
+ user[ hungarianKey ] = {};
+ }
+ $.extend( true, user[hungarianKey], user[key] );
+
+ _fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force );
+ }
+ else {
+ user[hungarianKey] = user[ key ];
+ }
+ }
+ } );
+ }
+
+
+ /**
+ * Language compatibility - when certain options are given, and others aren't, we
+ * need to duplicate the values over, in order to provide backwards compatibility
+ * with older language files.
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnLanguageCompat( lang )
+ {
+ var defaults = DataTable.defaults.oLanguage;
+ var zeroRecords = lang.sZeroRecords;
+
+ /* Backwards compatibility - if there is no sEmptyTable given, then use the same as
+ * sZeroRecords - assuming that is given.
+ */
+ if ( ! lang.sEmptyTable && zeroRecords &&
+ defaults.sEmptyTable === "No data available in table" )
+ {
+ _fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' );
+ }
+
+ /* Likewise with loading records */
+ if ( ! lang.sLoadingRecords && zeroRecords &&
+ defaults.sLoadingRecords === "Loading..." )
+ {
+ _fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' );
+ }
+
+ // Old parameter name of the thousands separator mapped onto the new
+ if ( lang.sInfoThousands ) {
+ lang.sThousands = lang.sInfoThousands;
+ }
+
+ var decimal = lang.sDecimal;
+ if ( decimal ) {
+ _addNumericSort( decimal );
+ }
+ }
+
+
+ /**
+ * Map one parameter onto another
+ * @param {object} o Object to map
+ * @param {*} knew The new parameter name
+ * @param {*} old The old parameter name
+ */
+ var _fnCompatMap = function ( o, knew, old ) {
+ if ( o[ knew ] !== undefined ) {
+ o[ old ] = o[ knew ];
+ }
+ };
+
+
+ /**
+ * Provide backwards compatibility for the main DT options. Note that the new
+ * options are mapped onto the old parameters, so this is an external interface
+ * change only.
+ * @param {object} init Object to map
+ */
+ function _fnCompatOpts ( init )
+ {
+ _fnCompatMap( init, 'ordering', 'bSort' );
+ _fnCompatMap( init, 'orderMulti', 'bSortMulti' );
+ _fnCompatMap( init, 'orderClasses', 'bSortClasses' );
+ _fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
+ _fnCompatMap( init, 'order', 'aaSorting' );
+ _fnCompatMap( init, 'orderFixed', 'aaSortingFixed' );
+ _fnCompatMap( init, 'paging', 'bPaginate' );
+ _fnCompatMap( init, 'pagingType', 'sPaginationType' );
+ _fnCompatMap( init, 'pageLength', 'iDisplayLength' );
+ _fnCompatMap( init, 'searching', 'bFilter' );
+
+ // Boolean initialisation of x-scrolling
+ if ( typeof init.sScrollX === 'boolean' ) {
+ init.sScrollX = init.sScrollX ? '100%' : '';
+ }
+ if ( typeof init.scrollX === 'boolean' ) {
+ init.scrollX = init.scrollX ? '100%' : '';
+ }
+
+ // Column search objects are in an array, so it needs to be converted
+ // element by element
+ var searchCols = init.aoSearchCols;
+
+ if ( searchCols ) {
+ for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) {
+ if ( searchCols[i] ) {
+ _fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] );
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Provide backwards compatibility for column options. Note that the new options
+ * are mapped onto the old parameters, so this is an external interface change
+ * only.
+ * @param {object} init Object to map
+ */
+ function _fnCompatCols ( init )
+ {
+ _fnCompatMap( init, 'orderable', 'bSortable' );
+ _fnCompatMap( init, 'orderData', 'aDataSort' );
+ _fnCompatMap( init, 'orderSequence', 'asSorting' );
+ _fnCompatMap( init, 'orderDataType', 'sortDataType' );
+
+ // orderData can be given as an integer
+ var dataSort = init.aDataSort;
+ if ( dataSort && ! $.isArray( dataSort ) ) {
+ init.aDataSort = [ dataSort ];
+ }
+ }
+
+
+ /**
+ * Browser feature detection for capabilities, quirks
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnBrowserDetect( settings )
+ {
+ // We don't need to do this every time DataTables is constructed, the values
+ // calculated are specific to the browser and OS configuration which we
+ // don't expect to change between initialisations
+ if ( ! DataTable.__browser ) {
+ var browser = {};
+ DataTable.__browser = browser;
+
+ // Scrolling feature / quirks detection
+ var n = $('<div/>')
+ .css( {
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ height: 1,
+ width: 1,
+ overflow: 'hidden'
+ } )
+ .append(
+ $('<div/>')
+ .css( {
+ position: 'absolute',
+ top: 1,
+ left: 1,
+ width: 100,
+ overflow: 'scroll'
+ } )
+ .append(
+ $('<div/>')
+ .css( {
+ width: '100%',
+ height: 10
+ } )
+ )
+ )
+ .appendTo( 'body' );
+
+ var outer = n.children();
+ var inner = outer.children();
+
+ // Numbers below, in order, are:
+ // inner.offsetWidth, inner.clientWidth, outer.offsetWidth, outer.clientWidth
+ //
+ // IE6 XP: 100 100 100 83
+ // IE7 Vista: 100 100 100 83
+ // IE 8+ Windows: 83 83 100 83
+ // Evergreen Windows: 83 83 100 83
+ // Evergreen Mac with scrollbars: 85 85 100 85
+ // Evergreen Mac without scrollbars: 100 100 100 100
+
+ // Get scrollbar width
+ browser.barWidth = outer[0].offsetWidth - outer[0].clientWidth;
+
+ // IE6/7 will oversize a width 100% element inside a scrolling element, to
+ // include the width of the scrollbar, while other browsers ensure the inner
+ // element is contained without forcing scrolling
+ browser.bScrollOversize = inner[0].offsetWidth === 100 && outer[0].clientWidth !== 100;
+
+ // In rtl text layout, some browsers (most, but not all) will place the
+ // scrollbar on the left, rather than the right.
+ browser.bScrollbarLeft = Math.round( inner.offset().left ) !== 1;
+
+ // IE8- don't provide height and width for getBoundingClientRect
+ browser.bBounding = n[0].getBoundingClientRect().width ? true : false;
+
+ n.remove();
+ }
+
+ $.extend( settings.oBrowser, DataTable.__browser );
+ settings.oScroll.iBarWidth = DataTable.__browser.barWidth;
+ }
+
+
+ /**
+ * Array.prototype reduce[Right] method, used for browsers which don't support
+ * JS 1.6. Done this way to reduce code size, since we iterate either way
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnReduce ( that, fn, init, start, end, inc )
+ {
+ var
+ i = start,
+ value,
+ isSet = false;
+
+ if ( init !== undefined ) {
+ value = init;
+ isSet = true;
+ }
+
+ while ( i !== end ) {
+ if ( ! that.hasOwnProperty(i) ) {
+ continue;
+ }
+
+ value = isSet ?
+ fn( value, that[i], i, that ) :
+ that[i];
+
+ isSet = true;
+ i += inc;
+ }
+
+ return value;
+ }
+
+ /**
+ * Add a column to the list used for the table with default values
+ * @param {object} oSettings dataTables settings object
+ * @param {node} nTh The th element for this column
+ * @memberof DataTable#oApi
+ */
+ function _fnAddColumn( oSettings, nTh )
+ {
+ // Add column to aoColumns array
+ var oDefaults = DataTable.defaults.column;
+ var iCol = oSettings.aoColumns.length;
+ var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
+ "nTh": nTh ? nTh : document.createElement('th'),
+ "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
+ "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
+ "mData": oDefaults.mData ? oDefaults.mData : iCol,
+ idx: iCol
+ } );
+ oSettings.aoColumns.push( oCol );
+
+ // Add search object for column specific search. Note that the `searchCols[ iCol ]`
+ // passed into extend can be undefined. This allows the user to give a default
+ // with only some of the parameters defined, and also not give a default
+ var searchCols = oSettings.aoPreSearchCols;
+ searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] );
+
+ // Use the default column options function to initialise classes etc
+ _fnColumnOptions( oSettings, iCol, $(nTh).data() );
+ }
+
+
+ /**
+ * Apply options for a column
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iCol column index to consider
+ * @param {object} oOptions object with sType, bVisible and bSearchable etc
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnOptions( oSettings, iCol, oOptions )
+ {
+ var oCol = oSettings.aoColumns[ iCol ];
+ var oClasses = oSettings.oClasses;
+ var th = $(oCol.nTh);
+
+ // Try to get width information from the DOM. We can't get it from CSS
+ // as we'd need to parse the CSS stylesheet. `width` option can override
+ if ( ! oCol.sWidthOrig ) {
+ // Width attribute
+ oCol.sWidthOrig = th.attr('width') || null;
+
+ // Style attribute
+ var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/);
+ if ( t ) {
+ oCol.sWidthOrig = t[1];
+ }
+ }
+
+ /* User specified column options */
+ if ( oOptions !== undefined && oOptions !== null )
+ {
+ // Backwards compatibility
+ _fnCompatCols( oOptions );
+
+ // Map camel case parameters to their Hungarian counterparts
+ _fnCamelToHungarian( DataTable.defaults.column, oOptions );
+
+ /* Backwards compatibility for mDataProp */
+ if ( oOptions.mDataProp !== undefined && !oOptions.mData )
+ {
+ oOptions.mData = oOptions.mDataProp;
+ }
+
+ if ( oOptions.sType )
+ {
+ oCol._sManualType = oOptions.sType;
+ }
+
+ // `class` is a reserved word in Javascript, so we need to provide
+ // the ability to use a valid name for the camel case input
+ if ( oOptions.className && ! oOptions.sClass )
+ {
+ oOptions.sClass = oOptions.className;
+ }
+
+ $.extend( oCol, oOptions );
+ _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
+
+ /* iDataSort to be applied (backwards compatibility), but aDataSort will take
+ * priority if defined
+ */
+ if ( oOptions.iDataSort !== undefined )
+ {
+ oCol.aDataSort = [ oOptions.iDataSort ];
+ }
+ _fnMap( oCol, oOptions, "aDataSort" );
+ }
+
+ /* Cache the data get and set functions for speed */
+ var mDataSrc = oCol.mData;
+ var mData = _fnGetObjectDataFn( mDataSrc );
+ var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
+
+ var attrTest = function( src ) {
+ return typeof src === 'string' && src.indexOf('@') !== -1;
+ };
+ oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && (
+ attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
+ );
+
+ oCol.fnGetData = function (rowData, type, meta) {
+ var innerData = mData( rowData, type, undefined, meta );
+
+ return mRender && type ?
+ mRender( innerData, type, rowData, meta ) :
+ innerData;
+ };
+ oCol.fnSetData = function ( rowData, val, meta ) {
+ return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta );
+ };
+
+ // Indicate if DataTables should read DOM data as an object or array
+ // Used in _fnGetRowElements
+ if ( typeof mDataSrc !== 'number' ) {
+ oSettings._rowReadObject = true;
+ }
+
+ /* Feature sorting overrides column specific when off */
+ if ( !oSettings.oFeatures.bSort )
+ {
+ oCol.bSortable = false;
+ th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called
+ }
+
+ /* Check that the class assignment is correct for sorting */
+ var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
+ var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
+ if ( !oCol.bSortable || (!bAsc && !bDesc) )
+ {
+ oCol.sSortingClass = oClasses.sSortableNone;
+ oCol.sSortingClassJUI = "";
+ }
+ else if ( bAsc && !bDesc )
+ {
+ oCol.sSortingClass = oClasses.sSortableAsc;
+ oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
+ }
+ else if ( !bAsc && bDesc )
+ {
+ oCol.sSortingClass = oClasses.sSortableDesc;
+ oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
+ }
+ else
+ {
+ oCol.sSortingClass = oClasses.sSortable;
+ oCol.sSortingClassJUI = oClasses.sSortJUI;
+ }
+ }
+
+
+ /**
+ * Adjust the table column widths for new data. Note: you would probably want to
+ * do a redraw after calling this function!
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnAdjustColumnSizing ( settings )
+ {
+ /* Not interested in doing column width calculation if auto-width is disabled */
+ if ( settings.oFeatures.bAutoWidth !== false )
+ {
+ var columns = settings.aoColumns;
+
+ _fnCalculateColumnWidths( settings );
+ for ( var i=0 , iLen=columns.length ; i<iLen ; i++ )
+ {
+ columns[i].nTh.style.width = columns[i].sWidth;
+ }
+ }
+
+ var scroll = settings.oScroll;
+ if ( scroll.sY !== '' || scroll.sX !== '')
+ {
+ _fnScrollDraw( settings );
+ }
+
+ _fnCallbackFire( settings, null, 'column-sizing', [settings] );
+ }
+
+
+ /**
+ * Covert the index of a visible column to the index in the data array (take account
+ * of hidden columns)
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iMatch Visible column index to lookup
+ * @returns {int} i the data index
+ * @memberof DataTable#oApi
+ */
+ function _fnVisibleToColumnIndex( oSettings, iMatch )
+ {
+ var aiVis = _fnGetColumns( oSettings, 'bVisible' );
+
+ return typeof aiVis[iMatch] === 'number' ?
+ aiVis[iMatch] :
+ null;
+ }
+
+
+ /**
+ * Covert the index of an index in the data array and convert it to the visible
+ * column index (take account of hidden columns)
+ * @param {int} iMatch Column index to lookup
+ * @param {object} oSettings dataTables settings object
+ * @returns {int} i the data index
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnIndexToVisible( oSettings, iMatch )
+ {
+ var aiVis = _fnGetColumns( oSettings, 'bVisible' );
+ var iPos = $.inArray( iMatch, aiVis );
+
+ return iPos !== -1 ? iPos : null;
+ }
+
+
+ /**
+ * Get the number of visible columns
+ * @param {object} oSettings dataTables settings object
+ * @returns {int} i the number of visible columns
+ * @memberof DataTable#oApi
+ */
+ function _fnVisbleColumns( oSettings )
+ {
+ return _fnGetColumns( oSettings, 'bVisible' ).length;
+ }
+
+
+ /**
+ * Get an array of column indexes that match a given property
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sParam Parameter in aoColumns to look for - typically
+ * bVisible or bSearchable
+ * @returns {array} Array of indexes with matched properties
+ * @memberof DataTable#oApi
+ */
+ function _fnGetColumns( oSettings, sParam )
+ {
+ var a = [];
+
+ $.map( oSettings.aoColumns, function(val, i) {
+ if ( val[sParam] ) {
+ a.push( i );
+ }
+ } );
+
+ return a;
+ }
+
+
+ /**
+ * Calculate the 'type' of a column
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnTypes ( settings )
+ {
+ var columns = settings.aoColumns;
+ var data = settings.aoData;
+ var types = DataTable.ext.type.detect;
+ var i, ien, j, jen, k, ken;
+ var col, cell, detectedType, cache;
+
+ // For each column, spin over the
+ for ( i=0, ien=columns.length ; i<ien ; i++ ) {
+ col = columns[i];
+ cache = [];
+
+ if ( ! col.sType && col._sManualType ) {
+ col.sType = col._sManualType;
+ }
+ else if ( ! col.sType ) {
+ for ( j=0, jen=types.length ; j<jen ; j++ ) {
+ for ( k=0, ken=data.length ; k<ken ; k++ ) {
+ // Use a cache array so we only need to get the type data
+ // from the formatter once (when using multiple detectors)
+ if ( cache[k] === undefined ) {
+ cache[k] = _fnGetCellData( settings, k, i, 'type' );
+ }
+
+ detectedType = types[j]( cache[k], settings );
+
+ // If null, then this type can't apply to this column, so
+ // rather than testing all cells, break out. There is an
+ // exception for the last type which is `html`. We need to
+ // scan all rows since it is possible to mix string and HTML
+ // types
+ if ( ! detectedType && j !== types.length-1 ) {
+ break;
+ }
+
+ // Only a single match is needed for html type since it is
+ // bottom of the pile and very similar to string
+ if ( detectedType === 'html' ) {
+ break;
+ }
+ }
+
+ // Type is valid for all data points in the column - use this
+ // type
+ if ( detectedType ) {
+ col.sType = detectedType;
+ break;
+ }
+ }
+
+ // Fall back - if no type was detected, always use string
+ if ( ! col.sType ) {
+ col.sType = 'string';
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Take the column definitions and static columns arrays and calculate how
+ * they relate to column indexes. The callback function will then apply the
+ * definition found for a column to a suitable configuration object.
+ * @param {object} oSettings dataTables settings object
+ * @param {array} aoColDefs The aoColumnDefs array that is to be applied
+ * @param {array} aoCols The aoColumns array that defines columns individually
+ * @param {function} fn Callback function - takes two parameters, the calculated
+ * column index and the definition for that column.
+ * @memberof DataTable#oApi
+ */
+ function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
+ {
+ var i, iLen, j, jLen, k, kLen, def;
+ var columns = oSettings.aoColumns;
+
+ // Column definitions with aTargets
+ if ( aoColDefs )
+ {
+ /* Loop over the definitions array - loop in reverse so first instance has priority */
+ for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
+ {
+ def = aoColDefs[i];
+
+ /* Each definition can target multiple columns, as it is an array */
+ var aTargets = def.targets !== undefined ?
+ def.targets :
+ def.aTargets;
+
+ if ( ! $.isArray( aTargets ) )
+ {
+ aTargets = [ aTargets ];
+ }
+
+ for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
+ {
+ if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
+ {
+ /* Add columns that we don't yet know about */
+ while( columns.length <= aTargets[j] )
+ {
+ _fnAddColumn( oSettings );
+ }
+
+ /* Integer, basic index */
+ fn( aTargets[j], def );
+ }
+ else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
+ {
+ /* Negative integer, right to left column counting */
+ fn( columns.length+aTargets[j], def );
+ }
+ else if ( typeof aTargets[j] === 'string' )
+ {
+ /* Class name matching on TH element */
+ for ( k=0, kLen=columns.length ; k<kLen ; k++ )
+ {
+ if ( aTargets[j] == "_all" ||
+ $(columns[k].nTh).hasClass( aTargets[j] ) )
+ {
+ fn( k, def );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Statically defined columns array
+ if ( aoCols )
+ {
+ for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
+ {
+ fn( i, aoCols[i] );
+ }
+ }
+ }
+
+ /**
+ * Add a data array to the table, creating DOM node etc. This is the parallel to
+ * _fnGatherData, but for adding rows from a Javascript source, rather than a
+ * DOM source.
+ * @param {object} oSettings dataTables settings object
+ * @param {array} aData data array to be added
+ * @param {node} [nTr] TR element to add to the table - optional. If not given,
+ * DataTables will create a row automatically
+ * @param {array} [anTds] Array of TD|TH elements for the row - must be given
+ * if nTr is.
+ * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
+ * @memberof DataTable#oApi
+ */
+ function _fnAddData ( oSettings, aDataIn, nTr, anTds )
+ {
+ /* Create the object for storing information about this new row */
+ var iRow = oSettings.aoData.length;
+ var oData = $.extend( true, {}, DataTable.models.oRow, {
+ src: nTr ? 'dom' : 'data',
+ idx: iRow
+ } );
+
+ oData._aData = aDataIn;
+ oSettings.aoData.push( oData );
+
+ /* Create the cells */
+ var nTd, sThisType;
+ var columns = oSettings.aoColumns;
+
+ // Invalidate the column types as the new data needs to be revalidated
+ for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
+ {
+ columns[i].sType = null;
+ }
+
+ /* Add to the display array */
+ oSettings.aiDisplayMaster.push( iRow );
+
+ var id = oSettings.rowIdFn( aDataIn );
+ if ( id !== undefined ) {
+ oSettings.aIds[ id ] = oData;
+ }
+
+ /* Create the DOM information, or register it if already present */
+ if ( nTr || ! oSettings.oFeatures.bDeferRender )
+ {
+ _fnCreateTr( oSettings, iRow, nTr, anTds );
+ }
+
+ return iRow;
+ }
+
+
+ /**
+ * Add one or more TR elements to the table. Generally we'd expect to
+ * use this for reading data from a DOM sourced table, but it could be
+ * used for an TR element. Note that if a TR is given, it is used (i.e.
+ * it is not cloned).
+ * @param {object} settings dataTables settings object
+ * @param {array|node|jQuery} trs The TR element(s) to add to the table
+ * @returns {array} Array of indexes for the added rows
+ * @memberof DataTable#oApi
+ */
+ function _fnAddTr( settings, trs )
+ {
+ var row;
+
+ // Allow an individual node to be passed in
+ if ( ! (trs instanceof $) ) {
+ trs = $(trs);
+ }
+
+ return trs.map( function (i, el) {
+ row = _fnGetRowElements( settings, el );
+ return _fnAddData( settings, row.data, el, row.cells );
+ } );
+ }
+
+
+ /**
+ * Take a TR element and convert it to an index in aoData
+ * @param {object} oSettings dataTables settings object
+ * @param {node} n the TR element to find
+ * @returns {int} index if the node is found, null if not
+ * @memberof DataTable#oApi
+ */
+ function _fnNodeToDataIndex( oSettings, n )
+ {
+ return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
+ }
+
+
+ /**
+ * Take a TD element and convert it into a column data index (not the visible index)
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iRow The row number the TD/TH can be found in
+ * @param {node} n The TD/TH element to find
+ * @returns {int} index if the node is found, -1 if not
+ * @memberof DataTable#oApi
+ */
+ function _fnNodeToColumnIndex( oSettings, iRow, n )
+ {
+ return $.inArray( n, oSettings.aoData[ iRow ].anCells );
+ }
+
+
+ /**
+ * Get the data for a given cell from the internal cache, taking into account data mapping
+ * @param {object} settings dataTables settings object
+ * @param {int} rowIdx aoData row id
+ * @param {int} colIdx Column index
+ * @param {string} type data get type ('display', 'type' 'filter' 'sort')
+ * @returns {*} Cell data
+ * @memberof DataTable#oApi
+ */
+ function _fnGetCellData( settings, rowIdx, colIdx, type )
+ {
+ var draw = settings.iDraw;
+ var col = settings.aoColumns[colIdx];
+ var rowData = settings.aoData[rowIdx]._aData;
+ var defaultContent = col.sDefaultContent;
+ var cellData = col.fnGetData( rowData, type, {
+ settings: settings,
+ row: rowIdx,
+ col: colIdx
+ } );
+
+ if ( cellData === undefined ) {
+ if ( settings.iDrawError != draw && defaultContent === null ) {
+ _fnLog( settings, 0, "Requested unknown parameter "+
+ (typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+
+ " for row "+rowIdx+", column "+colIdx, 4 );
+ settings.iDrawError = draw;
+ }
+ return defaultContent;
+ }
+
+ /* When the data source is null, we can use default column data */
+ if ( (cellData === rowData || cellData === null) && defaultContent !== null ) {
+ cellData = defaultContent;
+ }
+ else if ( typeof cellData === 'function' ) {
+ // If the data source is a function, then we run it and use the return,
+ // executing in the scope of the data object (for instances)
+ return cellData.call( rowData );
+ }
+
+ if ( cellData === null && type == 'display' ) {
+ return '';
+ }
+ return cellData;
+ }
+
+
+ /**
+ * Set the value for a specific cell, into the internal data cache
+ * @param {object} settings dataTables settings object
+ * @param {int} rowIdx aoData row id
+ * @param {int} colIdx Column index
+ * @param {*} val Value to set
+ * @memberof DataTable#oApi
+ */
+ function _fnSetCellData( settings, rowIdx, colIdx, val )
+ {
+ var col = settings.aoColumns[colIdx];
+ var rowData = settings.aoData[rowIdx]._aData;
+
+ col.fnSetData( rowData, val, {
+ settings: settings,
+ row: rowIdx,
+ col: colIdx
+ } );
+ }
+
+
+ // Private variable that is used to match action syntax in the data property object
+ var __reArray = /\[.*?\]$/;
+ var __reFn = /\(\)$/;
+
+ /**
+ * Split string on periods, taking into account escaped periods
+ * @param {string} str String to split
+ * @return {array} Split string
+ */
+ function _fnSplitObjNotation( str )
+ {
+ return $.map( str.match(/(\\.|[^\.])+/g) || [''], function ( s ) {
+ return s.replace(/\\./g, '.');
+ } );
+ }
+
+
+ /**
+ * Return a function that can be used to get data from a source object, taking
+ * into account the ability to use nested objects as a source
+ * @param {string|int|function} mSource The data source for the object
+ * @returns {function} Data get function
+ * @memberof DataTable#oApi
+ */
+ function _fnGetObjectDataFn( mSource )
+ {
+ if ( $.isPlainObject( mSource ) )
+ {
+ /* Build an object of get functions, and wrap them in a single call */
+ var o = {};
+ $.each( mSource, function (key, val) {
+ if ( val ) {
+ o[key] = _fnGetObjectDataFn( val );
+ }
+ } );
+
+ return function (data, type, row, meta) {
+ var t = o[type] || o._;
+ return t !== undefined ?
+ t(data, type, row, meta) :
+ data;
+ };
+ }
+ else if ( mSource === null )
+ {
+ /* Give an empty string for rendering / sorting etc */
+ return function (data) { // type, row and meta also passed, but not used
+ return data;
+ };
+ }
+ else if ( typeof mSource === 'function' )
+ {
+ return function (data, type, row, meta) {
+ return mSource( data, type, row, meta );
+ };
+ }
+ else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
+ mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
+ {
+ /* If there is a . in the source string then the data source is in a
+ * nested object so we loop over the data for each level to get the next
+ * level down. On each loop we test for undefined, and if found immediately
+ * return. This allows entire objects to be missing and sDefaultContent to
+ * be used if defined, rather than throwing an error
+ */
+ var fetchData = function (data, type, src) {
+ var arrayNotation, funcNotation, out, innerSrc;
+
+ if ( src !== "" )
+ {
+ var a = _fnSplitObjNotation( src );
+
+ for ( var i=0, iLen=a.length ; i<iLen ; i++ )
+ {
+ // Check if we are dealing with special notation
+ arrayNotation = a[i].match(__reArray);
+ funcNotation = a[i].match(__reFn);
+
+ if ( arrayNotation )
+ {
+ // Array notation
+ a[i] = a[i].replace(__reArray, '');
+
+ // Condition allows simply [] to be passed in
+ if ( a[i] !== "" ) {
+ data = data[ a[i] ];
+ }
+ out = [];
+
+ // Get the remainder of the nested object to get
+ a.splice( 0, i+1 );
+ innerSrc = a.join('.');
+
+ // Traverse each entry in the array getting the properties requested
+ if ( $.isArray( data ) ) {
+ for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
+ out.push( fetchData( data[j], type, innerSrc ) );
+ }
+ }
+
+ // If a string is given in between the array notation indicators, that
+ // is used to join the strings together, otherwise an array is returned
+ var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
+ data = (join==="") ? out : out.join(join);
+
+ // The inner call to fetchData has already traversed through the remainder
+ // of the source requested, so we exit from the loop
+ break;
+ }
+ else if ( funcNotation )
+ {
+ // Function call
+ a[i] = a[i].replace(__reFn, '');
+ data = data[ a[i] ]();
+ continue;
+ }
+
+ if ( data === null || data[ a[i] ] === undefined )
+ {
+ return undefined;
+ }
+ data = data[ a[i] ];
+ }
+ }
+
+ return data;
+ };
+
+ return function (data, type) { // row and meta also passed, but not used
+ return fetchData( data, type, mSource );
+ };
+ }
+ else
+ {
+ /* Array or flat object mapping */
+ return function (data, type) { // row and meta also passed, but not used
+ return data[mSource];
+ };
+ }
+ }
+
+
+ /**
+ * Return a function that can be used to set data from a source object, taking
+ * into account the ability to use nested objects as a source
+ * @param {string|int|function} mSource The data source for the object
+ * @returns {function} Data set function
+ * @memberof DataTable#oApi
+ */
+ function _fnSetObjectDataFn( mSource )
+ {
+ if ( $.isPlainObject( mSource ) )
+ {
+ /* Unlike get, only the underscore (global) option is used for for
+ * setting data since we don't know the type here. This is why an object
+ * option is not documented for `mData` (which is read/write), but it is
+ * for `mRender` which is read only.
+ */
+ return _fnSetObjectDataFn( mSource._ );
+ }
+ else if ( mSource === null )
+ {
+ /* Nothing to do when the data source is null */
+ return function () {};
+ }
+ else if ( typeof mSource === 'function' )
+ {
+ return function (data, val, meta) {
+ mSource( data, 'set', val, meta );
+ };
+ }
+ else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
+ mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
+ {
+ /* Like the get, we need to get data from a nested object */
+ var setData = function (data, val, src) {
+ var a = _fnSplitObjNotation( src ), b;
+ var aLast = a[a.length-1];
+ var arrayNotation, funcNotation, o, innerSrc;
+
+ for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
+ {
+ // Check if we are dealing with an array notation request
+ arrayNotation = a[i].match(__reArray);
+ funcNotation = a[i].match(__reFn);
+
+ if ( arrayNotation )
+ {
+ a[i] = a[i].replace(__reArray, '');
+ data[ a[i] ] = [];
+
+ // Get the remainder of the nested object to set so we can recurse
+ b = a.slice();
+ b.splice( 0, i+1 );
+ innerSrc = b.join('.');
+
+ // Traverse each entry in the array setting the properties requested
+ if ( $.isArray( val ) )
+ {
+ for ( var j=0, jLen=val.length ; j<jLen ; j++ )
+ {
+ o = {};
+ setData( o, val[j], innerSrc );
+ data[ a[i] ].push( o );
+ }
+ }
+ else
+ {
+ // We've been asked to save data to an array, but it
+ // isn't array data to be saved. Best that can be done
+ // is to just save the value.
+ data[ a[i] ] = val;
+ }
+
+ // The inner call to setData has already traversed through the remainder
+ // of the source and has set the data, thus we can exit here
+ return;
+ }
+ else if ( funcNotation )
+ {
+ // Function call
+ a[i] = a[i].replace(__reFn, '');
+ data = data[ a[i] ]( val );
+ }
+
+ // If the nested object doesn't currently exist - since we are
+ // trying to set the value - create it
+ if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
+ {
+ data[ a[i] ] = {};
+ }
+ data = data[ a[i] ];
+ }
+
+ // Last item in the input - i.e, the actual set
+ if ( aLast.match(__reFn ) )
+ {
+ // Function call
+ data = data[ aLast.replace(__reFn, '') ]( val );
+ }
+ else
+ {
+ // If array notation is used, we just want to strip it and use the property name
+ // and assign the value. If it isn't used, then we get the result we want anyway
+ data[ aLast.replace(__reArray, '') ] = val;
+ }
+ };
+
+ return function (data, val) { // meta is also passed in, but not used
+ return setData( data, val, mSource );
+ };
+ }
+ else
+ {
+ /* Array or flat object mapping */
+ return function (data, val) { // meta is also passed in, but not used
+ data[mSource] = val;
+ };
+ }
+ }
+
+
+ /**
+ * Return an array with the full table data
+ * @param {object} oSettings dataTables settings object
+ * @returns array {array} aData Master data array
+ * @memberof DataTable#oApi
+ */
+ function _fnGetDataMaster ( settings )
+ {
+ return _pluck( settings.aoData, '_aData' );
+ }
+
+
+ /**
+ * Nuke the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnClearTable( settings )
+ {
+ settings.aoData.length = 0;
+ settings.aiDisplayMaster.length = 0;
+ settings.aiDisplay.length = 0;
+ settings.aIds = {};
+ }
+
+
+ /**
+ * Take an array of integers (index array) and remove a target integer (value - not
+ * the key!)
+ * @param {array} a Index array to target
+ * @param {int} iTarget value to find
+ * @memberof DataTable#oApi
+ */
+ function _fnDeleteIndex( a, iTarget, splice )
+ {
+ var iTargetIndex = -1;
+
+ for ( var i=0, iLen=a.length ; i<iLen ; i++ )
+ {
+ if ( a[i] == iTarget )
+ {
+ iTargetIndex = i;
+ }
+ else if ( a[i] > iTarget )
+ {
+ a[i]--;
+ }
+ }
+
+ if ( iTargetIndex != -1 && splice === undefined )
+ {
+ a.splice( iTargetIndex, 1 );
+ }
+ }
+
+
+ /**
+ * Mark cached data as invalid such that a re-read of the data will occur when
+ * the cached data is next requested. Also update from the data source object.
+ *
+ * @param {object} settings DataTables settings object
+ * @param {int} rowIdx Row index to invalidate
+ * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom'
+ * or 'data'
+ * @param {int} [colIdx] Column index to invalidate. If undefined the whole
+ * row will be invalidated
+ * @memberof DataTable#oApi
+ *
+ * @todo For the modularisation of v1.11 this will need to become a callback, so
+ * the sort and filter methods can subscribe to it. That will required
+ * initialisation options for sorting, which is why it is not already baked in
+ */
+ function _fnInvalidate( settings, rowIdx, src, colIdx )
+ {
+ var row = settings.aoData[ rowIdx ];
+ var i, ien;
+ var cellWrite = function ( cell, col ) {
+ // This is very frustrating, but in IE if you just write directly
+ // to innerHTML, and elements that are overwritten are GC'ed,
+ // even if there is a reference to them elsewhere
+ while ( cell.childNodes.length ) {
+ cell.removeChild( cell.firstChild );
+ }
+
+ cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );
+ };
+
+ // Are we reading last data from DOM or the data object?
+ if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
+ // Read the data from the DOM
+ row._aData = _fnGetRowElements(
+ settings, row, colIdx, colIdx === undefined ? undefined : row._aData
+ )
+ .data;
+ }
+ else {
+ // Reading from data object, update the DOM
+ var cells = row.anCells;
+
+ if ( cells ) {
+ if ( colIdx !== undefined ) {
+ cellWrite( cells[colIdx], colIdx );
+ }
+ else {
+ for ( i=0, ien=cells.length ; i<ien ; i++ ) {
+ cellWrite( cells[i], i );
+ }
+ }
+ }
+ }
+
+ // For both row and cell invalidation, the cached data for sorting and
+ // filtering is nulled out
+ row._aSortData = null;
+ row._aFilterData = null;
+
+ // Invalidate the type for a specific column (if given) or all columns since
+ // the data might have changed
+ var cols = settings.aoColumns;
+ if ( colIdx !== undefined ) {
+ cols[ colIdx ].sType = null;
+ }
+ else {
+ for ( i=0, ien=cols.length ; i<ien ; i++ ) {
+ cols[i].sType = null;
+ }
+
+ // Update DataTables special `DT_*` attributes for the row
+ _fnRowAttributes( settings, row );
+ }
+ }
+
+
+ /**
+ * Build a data source object from an HTML row, reading the contents of the
+ * cells that are in the row.
+ *
+ * @param {object} settings DataTables settings object
+ * @param {node|object} TR element from which to read data or existing row
+ * object from which to re-read the data from the cells
+ * @param {int} [colIdx] Optional column index
+ * @param {array|object} [d] Data source object. If `colIdx` is given then this
+ * parameter should also be given and will be used to write the data into.
+ * Only the column in question will be written
+ * @returns {object} Object with two parameters: `data` the data read, in
+ * document order, and `cells` and array of nodes (they can be useful to the
+ * caller, so rather than needing a second traversal to get them, just return
+ * them from here).
+ * @memberof DataTable#oApi
+ */
+ function _fnGetRowElements( settings, row, colIdx, d )
+ {
+ var
+ tds = [],
+ td = row.firstChild,
+ name, col, o, i=0, contents,
+ columns = settings.aoColumns,
+ objectRead = settings._rowReadObject;
+
+ // Allow the data object to be passed in, or construct
+ d = d !== undefined ?
+ d :
+ objectRead ?
+ {} :
+ [];
+
+ var attr = function ( str, td ) {
+ if ( typeof str === 'string' ) {
+ var idx = str.indexOf('@');
+
+ if ( idx !== -1 ) {
+ var attr = str.substring( idx+1 );
+ var setter = _fnSetObjectDataFn( str );
+ setter( d, td.getAttribute( attr ) );
+ }
+ }
+ };
+
+ // Read data from a cell and store into the data object
+ var cellProcess = function ( cell ) {
+ if ( colIdx === undefined || colIdx === i ) {
+ col = columns[i];
+ contents = $.trim(cell.innerHTML);
+
+ if ( col && col._bAttrSrc ) {
+ var setter = _fnSetObjectDataFn( col.mData._ );
+ setter( d, contents );
+
+ attr( col.mData.sort, cell );
+ attr( col.mData.type, cell );
+ attr( col.mData.filter, cell );
+ }
+ else {
+ // Depending on the `data` option for the columns the data can
+ // be read to either an object or an array.
+ if ( objectRead ) {
+ if ( ! col._setter ) {
+ // Cache the setter function
+ col._setter = _fnSetObjectDataFn( col.mData );
+ }
+ col._setter( d, contents );
+ }
+ else {
+ d[i] = contents;
+ }
+ }
+ }
+
+ i++;
+ };
+
+ if ( td ) {
+ // `tr` element was passed in
+ while ( td ) {
+ name = td.nodeName.toUpperCase();
+
+ if ( name == "TD" || name == "TH" ) {
+ cellProcess( td );
+ tds.push( td );
+ }
+
+ td = td.nextSibling;
+ }
+ }
+ else {
+ // Existing row object passed in
+ tds = row.anCells;
+
+ for ( var j=0, jen=tds.length ; j<jen ; j++ ) {
+ cellProcess( tds[j] );
+ }
+ }
+
+ // Read the ID from the DOM if present
+ var rowNode = row.firstChild ? row : row.nTr;
+
+ if ( rowNode ) {
+ var id = rowNode.getAttribute( 'id' );
+
+ if ( id ) {
+ _fnSetObjectDataFn( settings.rowId )( d, id );
+ }
+ }
+
+ return {
+ data: d,
+ cells: tds
+ };
+ }
+ /**
+ * Create a new TR element (and it's TD children) for a row
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iRow Row to consider
+ * @param {node} [nTrIn] TR element to add to the table - optional. If not given,
+ * DataTables will create a row automatically
+ * @param {array} [anTds] Array of TD|TH elements for the row - must be given
+ * if nTr is.
+ * @memberof DataTable#oApi
+ */
+ function _fnCreateTr ( oSettings, iRow, nTrIn, anTds )
+ {
+ var
+ row = oSettings.aoData[iRow],
+ rowData = row._aData,
+ cells = [],
+ nTr, nTd, oCol,
+ i, iLen;
+
+ if ( row.nTr === null )
+ {
+ nTr = nTrIn || document.createElement('tr');
+
+ row.nTr = nTr;
+ row.anCells = cells;
+
+ /* Use a private property on the node to allow reserve mapping from the node
+ * to the aoData array for fast look up
+ */
+ nTr._DT_RowIndex = iRow;
+
+ /* Special parameters can be given by the data source to be used on the row */
+ _fnRowAttributes( oSettings, row );
+
+ /* Process each column */
+ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+ {
+ oCol = oSettings.aoColumns[i];
+
+ nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType );
+ nTd._DT_CellIndex = {
+ row: iRow,
+ column: i
+ };
+
+ cells.push( nTd );
+
+ // Need to create the HTML if new, or if a rendering function is defined
+ if ( !nTrIn || oCol.mRender || oCol.mData !== i )
+ {
+ nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' );
+ }
+
+ /* Add user defined class */
+ if ( oCol.sClass )
+ {
+ nTd.className += ' '+oCol.sClass;
+ }
+
+ // Visibility - add or remove as required
+ if ( oCol.bVisible && ! nTrIn )
+ {
+ nTr.appendChild( nTd );
+ }
+ else if ( ! oCol.bVisible && nTrIn )
+ {
+ nTd.parentNode.removeChild( nTd );
+ }
+
+ if ( oCol.fnCreatedCell )
+ {
+ oCol.fnCreatedCell.call( oSettings.oInstance,
+ nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i
+ );
+ }
+ }
+
+ _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] );
+ }
+
+ // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved
+ // and deployed
+ row.nTr.setAttribute( 'role', 'row' );
+ }
+
+
+ /**
+ * Add attributes to a row based on the special `DT_*` parameters in a data
+ * source object.
+ * @param {object} settings DataTables settings object
+ * @param {object} DataTables row object for the row to be modified
+ * @memberof DataTable#oApi
+ */
+ function _fnRowAttributes( settings, row )
+ {
+ var tr = row.nTr;
+ var data = row._aData;
+
+ if ( tr ) {
+ var id = settings.rowIdFn( data );
+
+ if ( id ) {
+ tr.id = id;
+ }
+
+ if ( data.DT_RowClass ) {
+ // Remove any classes added by DT_RowClass before
+ var a = data.DT_RowClass.split(' ');
+ row.__rowc = row.__rowc ?
+ _unique( row.__rowc.concat( a ) ) :
+ a;
+
+ $(tr)
+ .removeClass( row.__rowc.join(' ') )
+ .addClass( data.DT_RowClass );
+ }
+
+ if ( data.DT_RowAttr ) {
+ $(tr).attr( data.DT_RowAttr );
+ }
+
+ if ( data.DT_RowData ) {
+ $(tr).data( data.DT_RowData );
+ }
+ }
+ }
+
+
+ /**
+ * Create the HTML header for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnBuildHead( oSettings )
+ {
+ var i, ien, cell, row, column;
+ var thead = oSettings.nTHead;
+ var tfoot = oSettings.nTFoot;
+ var createHeader = $('th, td', thead).length === 0;
+ var classes = oSettings.oClasses;
+ var columns = oSettings.aoColumns;
+
+ if ( createHeader ) {
+ row = $('<tr/>').appendTo( thead );
+ }
+
+ for ( i=0, ien=columns.length ; i<ien ; i++ ) {
+ column = columns[i];
+ cell = $( column.nTh ).addClass( column.sClass );
+
+ if ( createHeader ) {
+ cell.appendTo( row );
+ }
+
+ // 1.11 move into sorting
+ if ( oSettings.oFeatures.bSort ) {
+ cell.addClass( column.sSortingClass );
+
+ if ( column.bSortable !== false ) {
+ cell
+ .attr( 'tabindex', oSettings.iTabIndex )
+ .attr( 'aria-controls', oSettings.sTableId );
+
+ _fnSortAttachListener( oSettings, column.nTh, i );
+ }
+ }
+
+ if ( column.sTitle != cell[0].innerHTML ) {
+ cell.html( column.sTitle );
+ }
+
+ _fnRenderer( oSettings, 'header' )(
+ oSettings, cell, column, classes
+ );
+ }
+
+ if ( createHeader ) {
+ _fnDetectHeader( oSettings.aoHeader, thead );
+ }
+
+ /* ARIA role for the rows */
+ $(thead).find('>tr').attr('role', 'row');
+
+ /* Deal with the footer - add classes if required */
+ $(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH );
+ $(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH );
+
+ // Cache the footer cells. Note that we only take the cells from the first
+ // row in the footer. If there is more than one row the user wants to
+ // interact with, they need to use the table().foot() method. Note also this
+ // allows cells to be used for multiple columns using colspan
+ if ( tfoot !== null ) {
+ var cells = oSettings.aoFooter[0];
+
+ for ( i=0, ien=cells.length ; i<ien ; i++ ) {
+ column = columns[i];
+ column.nTf = cells[i].cell;
+
+ if ( column.sClass ) {
+ $(column.nTf).addClass( column.sClass );
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Draw the header (or footer) element based on the column visibility states. The
+ * methodology here is to use the layout array from _fnDetectHeader, modified for
+ * the instantaneous column visibility, to construct the new layout. The grid is
+ * traversed over cell at a time in a rows x columns grid fashion, although each
+ * cell insert can cover multiple elements in the grid - which is tracks using the
+ * aApplied array. Cell inserts in the grid will only occur where there isn't
+ * already a cell in that position.
+ * @param {object} oSettings dataTables settings object
+ * @param array {objects} aoSource Layout array from _fnDetectHeader
+ * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
+ * @memberof DataTable#oApi
+ */
+ function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
+ {
+ var i, iLen, j, jLen, k, kLen, n, nLocalTr;
+ var aoLocal = [];
+ var aApplied = [];
+ var iColumns = oSettings.aoColumns.length;
+ var iRowspan, iColspan;
+
+ if ( ! aoSource )
+ {
+ return;
+ }
+
+ if ( bIncludeHidden === undefined )
+ {
+ bIncludeHidden = false;
+ }
+
+ /* Make a copy of the master layout array, but without the visible columns in it */
+ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
+ {
+ aoLocal[i] = aoSource[i].slice();
+ aoLocal[i].nTr = aoSource[i].nTr;
+
+ /* Remove any columns which are currently hidden */
+ for ( j=iColumns-1 ; j>=0 ; j-- )
+ {
+ if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
+ {
+ aoLocal[i].splice( j, 1 );
+ }
+ }
+
+ /* Prep the applied array - it needs an element for each row */
+ aApplied.push( [] );
+ }
+
+ for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
+ {
+ nLocalTr = aoLocal[i].nTr;
+
+ /* All cells are going to be replaced, so empty out the row */
+ if ( nLocalTr )
+ {
+ while( (n = nLocalTr.firstChild) )
+ {
+ nLocalTr.removeChild( n );
+ }
+ }
+
+ for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
+ {
+ iRowspan = 1;
+ iColspan = 1;
+
+ /* Check to see if there is already a cell (row/colspan) covering our target
+ * insert point. If there is, then there is nothing to do.
+ */
+ if ( aApplied[i][j] === undefined )
+ {
+ nLocalTr.appendChild( aoLocal[i][j].cell );
+ aApplied[i][j] = 1;
+
+ /* Expand the cell to cover as many rows as needed */
+ while ( aoLocal[i+iRowspan] !== undefined &&
+ aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
+ {
+ aApplied[i+iRowspan][j] = 1;
+ iRowspan++;
+ }
+
+ /* Expand the cell to cover as many columns as needed */
+ while ( aoLocal[i][j+iColspan] !== undefined &&
+ aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
+ {
+ /* Must update the applied array over the rows for the columns */
+ for ( k=0 ; k<iRowspan ; k++ )
+ {
+ aApplied[i+k][j+iColspan] = 1;
+ }
+ iColspan++;
+ }
+
+ /* Do the actual expansion in the DOM */
+ $(aoLocal[i][j].cell)
+ .attr('rowspan', iRowspan)
+ .attr('colspan', iColspan);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Insert the required TR nodes into the table for display
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnDraw( oSettings )
+ {
+ /* Provide a pre-callback function which can be used to cancel the draw is false is returned */
+ var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
+ if ( $.inArray( false, aPreDraw ) !== -1 )
+ {
+ _fnProcessingDisplay( oSettings, false );
+ return;
+ }
+
+ var i, iLen, n;
+ var anRows = [];
+ var iRowCount = 0;
+ var asStripeClasses = oSettings.asStripeClasses;
+ var iStripes = asStripeClasses.length;
+ var iOpenRows = oSettings.aoOpenRows.length;
+ var oLang = oSettings.oLanguage;
+ var iInitDisplayStart = oSettings.iInitDisplayStart;
+ var bServerSide = _fnDataSource( oSettings ) == 'ssp';
+ var aiDisplay = oSettings.aiDisplay;
+
+ oSettings.bDrawing = true;
+
+ /* Check and see if we have an initial draw position from state saving */
+ if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 )
+ {
+ oSettings._iDisplayStart = bServerSide ?
+ iInitDisplayStart :
+ iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
+ 0 :
+ iInitDisplayStart;
+
+ oSettings.iInitDisplayStart = -1;
+ }
+
+ var iDisplayStart = oSettings._iDisplayStart;
+ var iDisplayEnd = oSettings.fnDisplayEnd();
+
+ /* Server-side processing draw intercept */
+ if ( oSettings.bDeferLoading )
+ {
+ oSettings.bDeferLoading = false;
+ oSettings.iDraw++;
+ _fnProcessingDisplay( oSettings, false );
+ }
+ else if ( !bServerSide )
+ {
+ oSettings.iDraw++;
+ }
+ else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
+ {
+ return;
+ }
+
+ if ( aiDisplay.length !== 0 )
+ {
+ var iStart = bServerSide ? 0 : iDisplayStart;
+ var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
+
+ for ( var j=iStart ; j<iEnd ; j++ )
+ {
+ var iDataIndex = aiDisplay[j];
+ var aoData = oSettings.aoData[ iDataIndex ];
+ if ( aoData.nTr === null )
+ {
+ _fnCreateTr( oSettings, iDataIndex );
+ }
+
+ var nRow = aoData.nTr;
+
+ /* Remove the old striping classes and then add the new one */
+ if ( iStripes !== 0 )
+ {
+ var sStripe = asStripeClasses[ iRowCount % iStripes ];
+ if ( aoData._sRowStripe != sStripe )
+ {
+ $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
+ aoData._sRowStripe = sStripe;
+ }
+ }
+
+ // Row callback functions - might want to manipulate the row
+ // iRowCount and j are not currently documented. Are they at all
+ // useful?
+ _fnCallbackFire( oSettings, 'aoRowCallback', null,
+ [nRow, aoData._aData, iRowCount, j] );
+
+ anRows.push( nRow );
+ iRowCount++;
+ }
+ }
+ else
+ {
+ /* Table is empty - create a row with an empty message in it */
+ var sZero = oLang.sZeroRecords;
+ if ( oSettings.iDraw == 1 && _fnDataSource( oSettings ) == 'ajax' )
+ {
+ sZero = oLang.sLoadingRecords;
+ }
+ else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
+ {
+ sZero = oLang.sEmptyTable;
+ }
+
+ anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } )
+ .append( $('<td />', {
+ 'valign': 'top',
+ 'colSpan': _fnVisbleColumns( oSettings ),
+ 'class': oSettings.oClasses.sRowEmpty
+ } ).html( sZero ) )[0];
+ }
+
+ /* Header and footer callbacks */
+ _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
+ _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
+
+ _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
+ _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
+
+ var body = $(oSettings.nTBody);
+
+ body.children().detach();
+ body.append( $(anRows) );
+
+ /* Call all required callback functions for the end of a draw */
+ _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
+
+ /* Draw is complete, sorting and filtering must be as well */
+ oSettings.bSorted = false;
+ oSettings.bFiltered = false;
+ oSettings.bDrawing = false;
+ }
+
+
+ /**
+ * Redraw the table - taking account of the various features which are enabled
+ * @param {object} oSettings dataTables settings object
+ * @param {boolean} [holdPosition] Keep the current paging position. By default
+ * the paging is reset to the first page
+ * @memberof DataTable#oApi
+ */
+ function _fnReDraw( settings, holdPosition )
+ {
+ var
+ features = settings.oFeatures,
+ sort = features.bSort,
+ filter = features.bFilter;
+
+ if ( sort ) {
+ _fnSort( settings );
+ }
+
+ if ( filter ) {
+ _fnFilterComplete( settings, settings.oPreviousSearch );
+ }
+ else {
+ // No filtering, so we want to just use the display master
+ settings.aiDisplay = settings.aiDisplayMaster.slice();
+ }
+
+ if ( holdPosition !== true ) {
+ settings._iDisplayStart = 0;
+ }
+
+ // Let any modules know about the draw hold position state (used by
+ // scrolling internally)
+ settings._drawHold = holdPosition;
+
+ _fnDraw( settings );
+
+ settings._drawHold = false;
+ }
+
+
+ /**
+ * Add the options to the page HTML for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnAddOptionsHtml ( oSettings )
+ {
+ var classes = oSettings.oClasses;
+ var table = $(oSettings.nTable);
+ var holding = $('<div/>').insertBefore( table ); // Holding element for speed
+ var features = oSettings.oFeatures;
+
+ // All DataTables are wrapped in a div
+ var insert = $('<div/>', {
+ id: oSettings.sTableId+'_wrapper',
+ 'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter)
+ } );
+
+ oSettings.nHolding = holding[0];
+ oSettings.nTableWrapper = insert[0];
+ oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
+
+ /* Loop over the user set positioning and place the elements as needed */
+ var aDom = oSettings.sDom.split('');
+ var featureNode, cOption, nNewNode, cNext, sAttr, j;
+ for ( var i=0 ; i<aDom.length ; i++ )
+ {
+ featureNode = null;
+ cOption = aDom[i];
+
+ if ( cOption == '<' )
+ {
+ /* New container div */
+ nNewNode = $('<div/>')[0];
+
+ /* Check to see if we should append an id and/or a class name to the container */
+ cNext = aDom[i+1];
+ if ( cNext == "'" || cNext == '"' )
+ {
+ sAttr = "";
+ j = 2;
+ while ( aDom[i+j] != cNext )
+ {
+ sAttr += aDom[i+j];
+ j++;
+ }
+
+ /* Replace jQuery UI constants @todo depreciated */
+ if ( sAttr == "H" )
+ {
+ sAttr = classes.sJUIHeader;
+ }
+ else if ( sAttr == "F" )
+ {
+ sAttr = classes.sJUIFooter;
+ }
+
+ /* The attribute can be in the format of "#id.class", "#id" or "class" This logic
+ * breaks the string into parts and applies them as needed
+ */
+ if ( sAttr.indexOf('.') != -1 )
+ {
+ var aSplit = sAttr.split('.');
+ nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
+ nNewNode.className = aSplit[1];
+ }
+ else if ( sAttr.charAt(0) == "#" )
+ {
+ nNewNode.id = sAttr.substr(1, sAttr.length-1);
+ }
+ else
+ {
+ nNewNode.className = sAttr;
+ }
+
+ i += j; /* Move along the position array */
+ }
+
+ insert.append( nNewNode );
+ insert = $(nNewNode);
+ }
+ else if ( cOption == '>' )
+ {
+ /* End container div */
+ insert = insert.parent();
+ }
+ // @todo Move options into their own plugins?
+ else if ( cOption == 'l' && features.bPaginate && features.bLengthChange )
+ {
+ /* Length */
+ featureNode = _fnFeatureHtmlLength( oSettings );
+ }
+ else if ( cOption == 'f' && features.bFilter )
+ {
+ /* Filter */
+ featureNode = _fnFeatureHtmlFilter( oSettings );
+ }
+ else if ( cOption == 'r' && features.bProcessing )
+ {
+ /* pRocessing */
+ featureNode = _fnFeatureHtmlProcessing( oSettings );
+ }
+ else if ( cOption == 't' )
+ {
+ /* Table */
+ featureNode = _fnFeatureHtmlTable( oSettings );
+ }
+ else if ( cOption == 'i' && features.bInfo )
+ {
+ /* Info */
+ featureNode = _fnFeatureHtmlInfo( oSettings );
+ }
+ else if ( cOption == 'p' && features.bPaginate )
+ {
+ /* Pagination */
+ featureNode = _fnFeatureHtmlPaginate( oSettings );
+ }
+ else if ( DataTable.ext.feature.length !== 0 )
+ {
+ /* Plug-in features */
+ var aoFeatures = DataTable.ext.feature;
+ for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
+ {
+ if ( cOption == aoFeatures[k].cFeature )
+ {
+ featureNode = aoFeatures[k].fnInit( oSettings );
+ break;
+ }
+ }
+ }
+
+ /* Add to the 2D features array */
+ if ( featureNode )
+ {
+ var aanFeatures = oSettings.aanFeatures;
+
+ if ( ! aanFeatures[cOption] )
+ {
+ aanFeatures[cOption] = [];
+ }
+
+ aanFeatures[cOption].push( featureNode );
+ insert.append( featureNode );
+ }
+ }
+
+ /* Built our DOM structure - replace the holding div with what we want */
+ holding.replaceWith( insert );
+ oSettings.nHolding = null;
+ }
+
+
+ /**
+ * Use the DOM source to create up an array of header cells. The idea here is to
+ * create a layout grid (array) of rows x columns, which contains a reference
+ * to the cell that that point in the grid (regardless of col/rowspan), such that
+ * any column / row could be removed and the new grid constructed
+ * @param array {object} aLayout Array to store the calculated layout in
+ * @param {node} nThead The header/footer element for the table
+ * @memberof DataTable#oApi
+ */
+ function _fnDetectHeader ( aLayout, nThead )
+ {
+ var nTrs = $(nThead).children('tr');
+ var nTr, nCell;
+ var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
+ var bUnique;
+ var fnShiftCol = function ( a, i, j ) {
+ var k = a[i];
+ while ( k[j] ) {
+ j++;
+ }
+ return j;
+ };
+
+ aLayout.splice( 0, aLayout.length );
+
+ /* We know how many rows there are in the layout - so prep it */
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
+ {
+ aLayout.push( [] );
+ }
+
+ /* Calculate a layout array */
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
+ {
+ nTr = nTrs[i];
+ iColumn = 0;
+
+ /* For every cell in the row... */
+ nCell = nTr.firstChild;
+ while ( nCell ) {
+ if ( nCell.nodeName.toUpperCase() == "TD" ||
+ nCell.nodeName.toUpperCase() == "TH" )
+ {
+ /* Get the col and rowspan attributes from the DOM and sanitise them */
+ iColspan = nCell.getAttribute('colspan') * 1;
+ iRowspan = nCell.getAttribute('rowspan') * 1;
+ iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
+ iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
+
+ /* There might be colspan cells already in this row, so shift our target
+ * accordingly
+ */
+ iColShifted = fnShiftCol( aLayout, i, iColumn );
+
+ /* Cache calculation for unique columns */
+ bUnique = iColspan === 1 ? true : false;
+
+ /* If there is col / rowspan, copy the information into the layout grid */
+ for ( l=0 ; l<iColspan ; l++ )
+ {
+ for ( k=0 ; k<iRowspan ; k++ )
+ {
+ aLayout[i+k][iColShifted+l] = {
+ "cell": nCell,
+ "unique": bUnique
+ };
+ aLayout[i+k].nTr = nTr;
+ }
+ }
+ }
+ nCell = nCell.nextSibling;
+ }
+ }
+ }
+
+
+ /**
+ * Get an array of unique th elements, one for each column
+ * @param {object} oSettings dataTables settings object
+ * @param {node} nHeader automatically detect the layout from this node - optional
+ * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
+ * @returns array {node} aReturn list of unique th's
+ * @memberof DataTable#oApi
+ */
+ function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
+ {
+ var aReturn = [];
+ if ( !aLayout )
+ {
+ aLayout = oSettings.aoHeader;
+ if ( nHeader )
+ {
+ aLayout = [];
+ _fnDetectHeader( aLayout, nHeader );
+ }
+ }
+
+ for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
+ {
+ for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
+ {
+ if ( aLayout[i][j].unique &&
+ (!aReturn[j] || !oSettings.bSortCellsTop) )
+ {
+ aReturn[j] = aLayout[i][j].cell;
+ }
+ }
+ }
+
+ return aReturn;
+ }
+
+ /**
+ * Create an Ajax call based on the table's settings, taking into account that
+ * parameters can have multiple forms, and backwards compatibility.
+ *
+ * @param {object} oSettings dataTables settings object
+ * @param {array} data Data to send to the server, required by
+ * DataTables - may be augmented by developer callbacks
+ * @param {function} fn Callback function to run when data is obtained
+ */
+ function _fnBuildAjax( oSettings, data, fn )
+ {
+ // Compatibility with 1.9-, allow fnServerData and event to manipulate
+ _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
+
+ // Convert to object based for 1.10+ if using the old array scheme which can
+ // come from server-side processing or serverParams
+ if ( data && $.isArray(data) ) {
+ var tmp = {};
+ var rbracket = /(.*?)\[\]$/;
+
+ $.each( data, function (key, val) {
+ var match = val.name.match(rbracket);
+
+ if ( match ) {
+ // Support for arrays
+ var name = match[0];
+
+ if ( ! tmp[ name ] ) {
+ tmp[ name ] = [];
+ }
+ tmp[ name ].push( val.value );
+ }
+ else {
+ tmp[val.name] = val.value;
+ }
+ } );
+ data = tmp;
+ }
+
+ var ajaxData;
+ var ajax = oSettings.ajax;
+ var instance = oSettings.oInstance;
+ var callback = function ( json ) {
+ _fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] );
+ fn( json );
+ };
+
+ if ( $.isPlainObject( ajax ) && ajax.data )
+ {
+ ajaxData = ajax.data;
+
+ var newData = $.isFunction( ajaxData ) ?
+ ajaxData( data, oSettings ) : // fn can manipulate data or return
+ ajaxData; // an object object or array to merge
+
+ // If the function returned something, use that alone
+ data = $.isFunction( ajaxData ) && newData ?
+ newData :
+ $.extend( true, data, newData );
+
+ // Remove the data property as we've resolved it already and don't want
+ // jQuery to do it again (it is restored at the end of the function)
+ delete ajax.data;
+ }
+
+ var baseAjax = {
+ "data": data,
+ "success": function (json) {
+ var error = json.error || json.sError;
+ if ( error ) {
+ _fnLog( oSettings, 0, error );
+ }
+
+ oSettings.json = json;
+ callback( json );
+ },
+ "dataType": "json",
+ "cache": false,
+ "type": oSettings.sServerMethod,
+ "error": function (xhr, error, thrown) {
+ var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] );
+
+ if ( $.inArray( true, ret ) === -1 ) {
+ if ( error == "parsererror" ) {
+ _fnLog( oSettings, 0, 'Invalid JSON response', 1 );
+ }
+ else if ( xhr.readyState === 4 ) {
+ _fnLog( oSettings, 0, 'Ajax error', 7 );
+ }
+ }
+
+ _fnProcessingDisplay( oSettings, false );
+ }
+ };
+
+ // Store the data submitted for the API
+ oSettings.oAjaxData = data;
+
+ // Allow plug-ins and external processes to modify the data
+ _fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] );
+
+ if ( oSettings.fnServerData )
+ {
+ // DataTables 1.9- compatibility
+ oSettings.fnServerData.call( instance,
+ oSettings.sAjaxSource,
+ $.map( data, function (val, key) { // Need to convert back to 1.9 trad format
+ return { name: key, value: val };
+ } ),
+ callback,
+ oSettings
+ );
+ }
+ else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
+ {
+ // DataTables 1.9- compatibility
+ oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
+ url: ajax || oSettings.sAjaxSource
+ } ) );
+ }
+ else if ( $.isFunction( ajax ) )
+ {
+ // Is a function - let the caller define what needs to be done
+ oSettings.jqXHR = ajax.call( instance, data, callback, oSettings );
+ }
+ else
+ {
+ // Object to extend the base settings
+ oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
+
+ // Restore for next time around
+ ajax.data = ajaxData;
+ }
+ }
+
+
+ /**
+ * Update the table using an Ajax call
+ * @param {object} settings dataTables settings object
+ * @returns {boolean} Block the table drawing or not
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxUpdate( settings )
+ {
+ if ( settings.bAjaxDataGet ) {
+ settings.iDraw++;
+ _fnProcessingDisplay( settings, true );
+
+ _fnBuildAjax(
+ settings,
+ _fnAjaxParameters( settings ),
+ function(json) {
+ _fnAjaxUpdateDraw( settings, json );
+ }
+ );
+
+ return false;
+ }
+ return true;
+ }
+
+
+ /**
+ * Build up the parameters in an object needed for a server-side processing
+ * request. Note that this is basically done twice, is different ways - a modern
+ * method which is used by default in DataTables 1.10 which uses objects and
+ * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
+ * the sAjaxSource option is used in the initialisation, or the legacyAjax
+ * option is set.
+ * @param {object} oSettings dataTables settings object
+ * @returns {bool} block the table drawing or not
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxParameters( settings )
+ {
+ var
+ columns = settings.aoColumns,
+ columnCount = columns.length,
+ features = settings.oFeatures,
+ preSearch = settings.oPreviousSearch,
+ preColSearch = settings.aoPreSearchCols,
+ i, data = [], dataProp, column, columnSearch,
+ sort = _fnSortFlatten( settings ),
+ displayStart = settings._iDisplayStart,
+ displayLength = features.bPaginate !== false ?
+ settings._iDisplayLength :
+ -1;
+
+ var param = function ( name, value ) {
+ data.push( { 'name': name, 'value': value } );
+ };
+
+ // DataTables 1.9- compatible method
+ param( 'sEcho', settings.iDraw );
+ param( 'iColumns', columnCount );
+ param( 'sColumns', _pluck( columns, 'sName' ).join(',') );
+ param( 'iDisplayStart', displayStart );
+ param( 'iDisplayLength', displayLength );
+
+ // DataTables 1.10+ method
+ var d = {
+ draw: settings.iDraw,
+ columns: [],
+ order: [],
+ start: displayStart,
+ length: displayLength,
+ search: {
+ value: preSearch.sSearch,
+ regex: preSearch.bRegex
+ }
+ };
+
+ for ( i=0 ; i<columnCount ; i++ ) {
+ column = columns[i];
+ columnSearch = preColSearch[i];
+ dataProp = typeof column.mData=="function" ? 'function' : column.mData ;
+
+ d.columns.push( {
+ data: dataProp,
+ name: column.sName,
+ searchable: column.bSearchable,
+ orderable: column.bSortable,
+ search: {
+ value: columnSearch.sSearch,
+ regex: columnSearch.bRegex
+ }
+ } );
+
+ param( "mDataProp_"+i, dataProp );
+
+ if ( features.bFilter ) {
+ param( 'sSearch_'+i, columnSearch.sSearch );
+ param( 'bRegex_'+i, columnSearch.bRegex );
+ param( 'bSearchable_'+i, column.bSearchable );
+ }
+
+ if ( features.bSort ) {
+ param( 'bSortable_'+i, column.bSortable );
+ }
+ }
+
+ if ( features.bFilter ) {
+ param( 'sSearch', preSearch.sSearch );
+ param( 'bRegex', preSearch.bRegex );
+ }
+
+ if ( features.bSort ) {
+ $.each( sort, function ( i, val ) {
+ d.order.push( { column: val.col, dir: val.dir } );
+
+ param( 'iSortCol_'+i, val.col );
+ param( 'sSortDir_'+i, val.dir );
+ } );
+
+ param( 'iSortingCols', sort.length );
+ }
+
+ // If the legacy.ajax parameter is null, then we automatically decide which
+ // form to use, based on sAjaxSource
+ var legacy = DataTable.ext.legacy.ajax;
+ if ( legacy === null ) {
+ return settings.sAjaxSource ? data : d;
+ }
+
+ // Otherwise, if legacy has been specified then we use that to decide on the
+ // form
+ return legacy ? data : d;
+ }
+
+
+ /**
+ * Data the data from the server (nuking the old) and redraw the table
+ * @param {object} oSettings dataTables settings object
+ * @param {object} json json data return from the server.
+ * @param {string} json.sEcho Tracking flag for DataTables to match requests
+ * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
+ * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
+ * @param {array} json.aaData The data to display on this page
+ * @param {string} [json.sColumns] Column ordering (sName, comma separated)
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxUpdateDraw ( settings, json )
+ {
+ // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
+ // Support both
+ var compat = function ( old, modern ) {
+ return json[old] !== undefined ? json[old] : json[modern];
+ };
+
+ var data = _fnAjaxDataSrc( settings, json );
+ var draw = compat( 'sEcho', 'draw' );
+ var recordsTotal = compat( 'iTotalRecords', 'recordsTotal' );
+ var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' );
+
+ if ( draw ) {
+ // Protect against out of sequence returns
+ if ( draw*1 < settings.iDraw ) {
+ return;
+ }
+ settings.iDraw = draw * 1;
+ }
+
+ _fnClearTable( settings );
+ settings._iRecordsTotal = parseInt(recordsTotal, 10);
+ settings._iRecordsDisplay = parseInt(recordsFiltered, 10);
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ _fnAddData( settings, data[i] );
+ }
+ settings.aiDisplay = settings.aiDisplayMaster.slice();
+
+ settings.bAjaxDataGet = false;
+ _fnDraw( settings );
+
+ if ( ! settings._bInitComplete ) {
+ _fnInitComplete( settings, json );
+ }
+
+ settings.bAjaxDataGet = true;
+ _fnProcessingDisplay( settings, false );
+ }
+
+
+ /**
+ * Get the data from the JSON data source to use for drawing a table. Using
+ * `_fnGetObjectDataFn` allows the data to be sourced from a property of the
+ * source object, or from a processing function.
+ * @param {object} oSettings dataTables settings object
+ * @param {object} json Data source object / array from the server
+ * @return {array} Array of data to use
+ */
+ function _fnAjaxDataSrc ( oSettings, json )
+ {
+ var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
+ oSettings.ajax.dataSrc :
+ oSettings.sAjaxDataProp; // Compatibility with 1.9-.
+
+ // Compatibility with 1.9-. In order to read from aaData, check if the
+ // default has been changed, if not, check for aaData
+ if ( dataSrc === 'data' ) {
+ return json.aaData || json[dataSrc];
+ }
+
+ return dataSrc !== "" ?
+ _fnGetObjectDataFn( dataSrc )( json ) :
+ json;
+ }
+
+ /**
+ * Generate the node required for filtering text
+ * @returns {node} Filter control element
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlFilter ( settings )
+ {
+ var classes = settings.oClasses;
+ var tableId = settings.sTableId;
+ var language = settings.oLanguage;
+ var previousSearch = settings.oPreviousSearch;
+ var features = settings.aanFeatures;
+ var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
+
+ var str = language.sSearch;
+ str = str.match(/_INPUT_/) ?
+ str.replace('_INPUT_', input) :
+ str+input;
+
+ var filter = $('<div/>', {
+ 'id': ! features.f ? tableId+'_filter' : null,
+ 'class': classes.sFilter
+ } )
+ .append( $('<label/>' ).append( str ) );
+
+ var searchFn = function() {
+ /* Update all other filter input elements for the new display */
+ var n = features.f;
+ var val = !this.value ? "" : this.value; // mental IE8 fix :-(
+
+ /* Now do the filter */
+ if ( val != previousSearch.sSearch ) {
+ _fnFilterComplete( settings, {
+ "sSearch": val,
+ "bRegex": previousSearch.bRegex,
+ "bSmart": previousSearch.bSmart ,
+ "bCaseInsensitive": previousSearch.bCaseInsensitive
+ } );
+
+ // Need to redraw, without resorting
+ settings._iDisplayStart = 0;
+ _fnDraw( settings );
+ }
+ };
+
+ var searchDelay = settings.searchDelay !== null ?
+ settings.searchDelay :
+ _fnDataSource( settings ) === 'ssp' ?
+ 400 :
+ 0;
+
+ var jqFilter = $('input', filter)
+ .val( previousSearch.sSearch )
+ .attr( 'placeholder', language.sSearchPlaceholder )
+ .bind(
+ 'keyup.DT search.DT input.DT paste.DT cut.DT',
+ searchDelay ?
+ _fnThrottle( searchFn, searchDelay ) :
+ searchFn
+ )
+ .bind( 'keypress.DT', function(e) {
+ /* Prevent form submission */
+ if ( e.keyCode == 13 ) {
+ return false;
+ }
+ } )
+ .attr('aria-controls', tableId);
+
+ // Update the input elements whenever the table is filtered
+ $(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
+ if ( settings === s ) {
+ // IE9 throws an 'unknown error' if document.activeElement is used
+ // inside an iframe or frame...
+ try {
+ if ( jqFilter[0] !== document.activeElement ) {
+ jqFilter.val( previousSearch.sSearch );
+ }
+ }
+ catch ( e ) {}
+ }
+ } );
+
+ return filter[0];
+ }
+
+
+ /**
+ * Filter the table using both the global filter and column based filtering
+ * @param {object} oSettings dataTables settings object
+ * @param {object} oSearch search information
+ * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterComplete ( oSettings, oInput, iForce )
+ {
+ var oPrevSearch = oSettings.oPreviousSearch;
+ var aoPrevSearch = oSettings.aoPreSearchCols;
+ var fnSaveFilter = function ( oFilter ) {
+ /* Save the filtering values */
+ oPrevSearch.sSearch = oFilter.sSearch;
+ oPrevSearch.bRegex = oFilter.bRegex;
+ oPrevSearch.bSmart = oFilter.bSmart;
+ oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
+ };
+ var fnRegex = function ( o ) {
+ // Backwards compatibility with the bEscapeRegex option
+ return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
+ };
+
+ // Resolve any column types that are unknown due to addition or invalidation
+ // @todo As per sort - can this be moved into an event handler?
+ _fnColumnTypes( oSettings );
+
+ /* In server-side processing all filtering is done by the server, so no point hanging around here */
+ if ( _fnDataSource( oSettings ) != 'ssp' )
+ {
+ /* Global filter */
+ _fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive );
+ fnSaveFilter( oInput );
+
+ /* Now do the individual column filter */
+ for ( var i=0 ; i<aoPrevSearch.length ; i++ )
+ {
+ _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
+ aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
+ }
+
+ /* Custom filtering */
+ _fnFilterCustom( oSettings );
+ }
+ else
+ {
+ fnSaveFilter( oInput );
+ }
+
+ /* Tell the draw function we have been filtering */
+ oSettings.bFiltered = true;
+ _fnCallbackFire( oSettings, null, 'search', [oSettings] );
+ }
+
+
+ /**
+ * Apply custom filtering functions
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterCustom( settings )
+ {
+ var filters = DataTable.ext.search;
+ var displayRows = settings.aiDisplay;
+ var row, rowIdx;
+
+ for ( var i=0, ien=filters.length ; i<ien ; i++ ) {
+ var rows = [];
+
+ // Loop over each row and see if it should be included
+ for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) {
+ rowIdx = displayRows[ j ];
+ row = settings.aoData[ rowIdx ];
+
+ if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) {
+ rows.push( rowIdx );
+ }
+ }
+
+ // So the array reference doesn't break set the results into the
+ // existing array
+ displayRows.length = 0;
+ $.merge( displayRows, rows );
+ }
+ }
+
+
+ /**
+ * Filter the table on a per-column basis
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sInput string to filter on
+ * @param {int} iColumn column to filter
+ * @param {bool} bRegex treat search string as a regular expression or not
+ * @param {bool} bSmart use smart filtering or not
+ * @param {bool} bCaseInsensitive Do case insenstive matching or not
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive )
+ {
+ if ( searchStr === '' ) {
+ return;
+ }
+
+ var data;
+ var display = settings.aiDisplay;
+ var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive );
+
+ for ( var i=display.length-1 ; i>=0 ; i-- ) {
+ data = settings.aoData[ display[i] ]._aFilterData[ colIdx ];
+
+ if ( ! rpSearch.test( data ) ) {
+ display.splice( i, 1 );
+ }
+ }
+ }
+
+
+ /**
+ * Filter the data table based on user input and draw the table
+ * @param {object} settings dataTables settings object
+ * @param {string} input string to filter on
+ * @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
+ * @param {bool} regex treat as a regular expression or not
+ * @param {bool} smart perform smart filtering or not
+ * @param {bool} caseInsensitive Do case insenstive matching or not
+ * @memberof DataTable#oApi
+ */
+ function _fnFilter( settings, input, force, regex, smart, caseInsensitive )
+ {
+ var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive );
+ var prevSearch = settings.oPreviousSearch.sSearch;
+ var displayMaster = settings.aiDisplayMaster;
+ var display, invalidated, i;
+
+ // Need to take account of custom filtering functions - always filter
+ if ( DataTable.ext.search.length !== 0 ) {
+ force = true;
+ }
+
+ // Check if any of the rows were invalidated
+ invalidated = _fnFilterData( settings );
+
+ // If the input is blank - we just want the full data set
+ if ( input.length <= 0 ) {
+ settings.aiDisplay = displayMaster.slice();
+ }
+ else {
+ // New search - start from the master array
+ if ( invalidated ||
+ force ||
+ prevSearch.length > input.length ||
+ input.indexOf(prevSearch) !== 0 ||
+ settings.bSorted // On resort, the display master needs to be
+ // re-filtered since indexes will have changed
+ ) {
+ settings.aiDisplay = displayMaster.slice();
+ }
+
+ // Search the display array
+ display = settings.aiDisplay;
+
+ for ( i=display.length-1 ; i>=0 ; i-- ) {
+ if ( ! rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) {
+ display.splice( i, 1 );
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Build a regular expression object suitable for searching a table
+ * @param {string} sSearch string to search for
+ * @param {bool} bRegex treat as a regular expression or not
+ * @param {bool} bSmart perform smart filtering or not
+ * @param {bool} bCaseInsensitive Do case insensitive matching or not
+ * @returns {RegExp} constructed object
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterCreateSearch( search, regex, smart, caseInsensitive )
+ {
+ search = regex ?
+ search :
+ _fnEscapeRegex( search );
+
+ if ( smart ) {
+ /* For smart filtering we want to allow the search to work regardless of
+ * word order. We also want double quoted text to be preserved, so word
+ * order is important - a la google. So this is what we want to
+ * generate:
+ *
+ * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
+ */
+ var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) {
+ if ( word.charAt(0) === '"' ) {
+ var m = word.match( /^"(.*)"$/ );
+ word = m ? m[1] : word;
+ }
+
+ return word.replace('"', '');
+ } );
+
+ search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$';
+ }
+
+ return new RegExp( search, caseInsensitive ? 'i' : '' );
+ }
+
+
+ /**
+ * Escape a string such that it can be used in a regular expression
+ * @param {string} sVal string to escape
+ * @returns {string} escaped string
+ * @memberof DataTable#oApi
+ */
+ function _fnEscapeRegex ( sVal )
+ {
+ return sVal.replace( _re_escape_regex, '\\$1' );
+ }
+
+
+
+ var __filter_div = $('<div>')[0];
+ var __filter_div_textContent = __filter_div.textContent !== undefined;
+
+ // Update the filtering data for each row if needed (by invalidation or first run)
+ function _fnFilterData ( settings )
+ {
+ var columns = settings.aoColumns;
+ var column;
+ var i, j, ien, jen, filterData, cellData, row;
+ var fomatters = DataTable.ext.type.search;
+ var wasInvalidated = false;
+
+ for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ row = settings.aoData[i];
+
+ if ( ! row._aFilterData ) {
+ filterData = [];
+
+ for ( j=0, jen=columns.length ; j<jen ; j++ ) {
+ column = columns[j];
+
+ if ( column.bSearchable ) {
+ cellData = _fnGetCellData( settings, i, j, 'filter' );
+
+ if ( fomatters[ column.sType ] ) {
+ cellData = fomatters[ column.sType ]( cellData );
+ }
+
+ // Search in DataTables 1.10 is string based. In 1.11 this
+ // should be altered to also allow strict type checking.
+ if ( cellData === null ) {
+ cellData = '';
+ }
+
+ if ( typeof cellData !== 'string' && cellData.toString ) {
+ cellData = cellData.toString();
+ }
+ }
+ else {
+ cellData = '';
+ }
+
+ // If it looks like there is an HTML entity in the string,
+ // attempt to decode it so sorting works as expected. Note that
+ // we could use a single line of jQuery to do this, but the DOM
+ // method used here is much faster http://jsperf.com/html-decode
+ if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) {
+ __filter_div.innerHTML = cellData;
+ cellData = __filter_div_textContent ?
+ __filter_div.textContent :
+ __filter_div.innerText;
+ }
+
+ if ( cellData.replace ) {
+ cellData = cellData.replace(/[\r\n]/g, '');
+ }
+
+ filterData.push( cellData );
+ }
+
+ row._aFilterData = filterData;
+ row._sFilterRow = filterData.join(' ');
+ wasInvalidated = true;
+ }
+ }
+
+ return wasInvalidated;
+ }
+
+
+ /**
+ * Convert from the internal Hungarian notation to camelCase for external
+ * interaction
+ * @param {object} obj Object to convert
+ * @returns {object} Inverted object
+ * @memberof DataTable#oApi
+ */
+ function _fnSearchToCamel ( obj )
+ {
+ return {
+ search: obj.sSearch,
+ smart: obj.bSmart,
+ regex: obj.bRegex,
+ caseInsensitive: obj.bCaseInsensitive
+ };
+ }
+
+
+
+ /**
+ * Convert from camelCase notation to the internal Hungarian. We could use the
+ * Hungarian convert function here, but this is cleaner
+ * @param {object} obj Object to convert
+ * @returns {object} Inverted object
+ * @memberof DataTable#oApi
+ */
+ function _fnSearchToHung ( obj )
+ {
+ return {
+ sSearch: obj.search,
+ bSmart: obj.smart,
+ bRegex: obj.regex,
+ bCaseInsensitive: obj.caseInsensitive
+ };
+ }
+
+ /**
+ * Generate the node required for the info display
+ * @param {object} oSettings dataTables settings object
+ * @returns {node} Information element
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlInfo ( settings )
+ {
+ var
+ tid = settings.sTableId,
+ nodes = settings.aanFeatures.i,
+ n = $('<div/>', {
+ 'class': settings.oClasses.sInfo,
+ 'id': ! nodes ? tid+'_info' : null
+ } );
+
+ if ( ! nodes ) {
+ // Update display on each draw
+ settings.aoDrawCallback.push( {
+ "fn": _fnUpdateInfo,
+ "sName": "information"
+ } );
+
+ n
+ .attr( 'role', 'status' )
+ .attr( 'aria-live', 'polite' );
+
+ // Table is described by our info div
+ $(settings.nTable).attr( 'aria-describedby', tid+'_info' );
+ }
+
+ return n[0];
+ }
+
+
+ /**
+ * Update the information elements in the display
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnUpdateInfo ( settings )
+ {
+ /* Show information about the table */
+ var nodes = settings.aanFeatures.i;
+ if ( nodes.length === 0 ) {
+ return;
+ }
+
+ var
+ lang = settings.oLanguage,
+ start = settings._iDisplayStart+1,
+ end = settings.fnDisplayEnd(),
+ max = settings.fnRecordsTotal(),
+ total = settings.fnRecordsDisplay(),
+ out = total ?
+ lang.sInfo :
+ lang.sInfoEmpty;
+
+ if ( total !== max ) {
+ /* Record set after filtering */
+ out += ' ' + lang.sInfoFiltered;
+ }
+
+ // Convert the macros
+ out += lang.sInfoPostFix;
+ out = _fnInfoMacros( settings, out );
+
+ var callback = lang.fnInfoCallback;
+ if ( callback !== null ) {
+ out = callback.call( settings.oInstance,
+ settings, start, end, max, total, out
+ );
+ }
+
+ $(nodes).html( out );
+ }
+
+
+ function _fnInfoMacros ( settings, str )
+ {
+ // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
+ // internally
+ var
+ formatter = settings.fnFormatNumber,
+ start = settings._iDisplayStart+1,
+ len = settings._iDisplayLength,
+ vis = settings.fnRecordsDisplay(),
+ all = len === -1;
+
+ return str.
+ replace(/_START_/g, formatter.call( settings, start ) ).
+ replace(/_END_/g, formatter.call( settings, settings.fnDisplayEnd() ) ).
+ replace(/_MAX_/g, formatter.call( settings, settings.fnRecordsTotal() ) ).
+ replace(/_TOTAL_/g, formatter.call( settings, vis ) ).
+ replace(/_PAGE_/g, formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ).
+ replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) );
+ }
+
+
+
+ /**
+ * Draw the table for the first time, adding all required features
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnInitialise ( settings )
+ {
+ var i, iLen, iAjaxStart=settings.iInitDisplayStart;
+ var columns = settings.aoColumns, column;
+ var features = settings.oFeatures;
+ var deferLoading = settings.bDeferLoading; // value modified by the draw
+
+ /* Ensure that the table data is fully initialised */
+ if ( ! settings.bInitialised ) {
+ setTimeout( function(){ _fnInitialise( settings ); }, 200 );
+ return;
+ }
+
+ /* Show the display HTML options */
+ _fnAddOptionsHtml( settings );
+
+ /* Build and draw the header / footer for the table */
+ _fnBuildHead( settings );
+ _fnDrawHead( settings, settings.aoHeader );
+ _fnDrawHead( settings, settings.aoFooter );
+
+ /* Okay to show that something is going on now */
+ _fnProcessingDisplay( settings, true );
+
+ /* Calculate sizes for columns */
+ if ( features.bAutoWidth ) {
+ _fnCalculateColumnWidths( settings );
+ }
+
+ for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
+ column = columns[i];
+
+ if ( column.sWidth ) {
+ column.nTh.style.width = _fnStringToCss( column.sWidth );
+ }
+ }
+
+ _fnCallbackFire( settings, null, 'preInit', [settings] );
+
+ // If there is default sorting required - let's do it. The sort function
+ // will do the drawing for us. Otherwise we draw the table regardless of the
+ // Ajax source - this allows the table to look initialised for Ajax sourcing
+ // data (show 'loading' message possibly)
+ _fnReDraw( settings );
+
+ // Server-side processing init complete is done by _fnAjaxUpdateDraw
+ var dataSrc = _fnDataSource( settings );
+ if ( dataSrc != 'ssp' || deferLoading ) {
+ // if there is an ajax source load the data
+ if ( dataSrc == 'ajax' ) {
+ _fnBuildAjax( settings, [], function(json) {
+ var aData = _fnAjaxDataSrc( settings, json );
+
+ // Got the data - add it to the table
+ for ( i=0 ; i<aData.length ; i++ ) {
+ _fnAddData( settings, aData[i] );
+ }
+
+ // Reset the init display for cookie saving. We've already done
+ // a filter, and therefore cleared it before. So we need to make
+ // it appear 'fresh'
+ settings.iInitDisplayStart = iAjaxStart;
+
+ _fnReDraw( settings );
+
+ _fnProcessingDisplay( settings, false );
+ _fnInitComplete( settings, json );
+ }, settings );
+ }
+ else {
+ _fnProcessingDisplay( settings, false );
+ _fnInitComplete( settings );
+ }
+ }
+ }
+
+
+ /**
+ * Draw the table for the first time, adding all required features
+ * @param {object} oSettings dataTables settings object
+ * @param {object} [json] JSON from the server that completed the table, if using Ajax source
+ * with client-side processing (optional)
+ * @memberof DataTable#oApi
+ */
+ function _fnInitComplete ( settings, json )
+ {
+ settings._bInitComplete = true;
+
+ // When data was added after the initialisation (data or Ajax) we need to
+ // calculate the column sizing
+ if ( json || settings.oInit.aaData ) {
+ _fnAdjustColumnSizing( settings );
+ }
+
+ _fnCallbackFire( settings, null, 'plugin-init', [settings, json] );
+ _fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] );
+ }
+
+
+ function _fnLengthChange ( settings, val )
+ {
+ var len = parseInt( val, 10 );
+ settings._iDisplayLength = len;
+
+ _fnLengthOverflow( settings );
+
+ // Fire length change event
+ _fnCallbackFire( settings, null, 'length', [settings, len] );
+ }
+
+
+ /**
+ * Generate the node required for user display length changing
+ * @param {object} settings dataTables settings object
+ * @returns {node} Display length feature node
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlLength ( settings )
+ {
+ var
+ classes = settings.oClasses,
+ tableId = settings.sTableId,
+ menu = settings.aLengthMenu,
+ d2 = $.isArray( menu[0] ),
+ lengths = d2 ? menu[0] : menu,
+ language = d2 ? menu[1] : menu;
+
+ var select = $('<select/>', {
+ 'name': tableId+'_length',
+ 'aria-controls': tableId,
+ 'class': classes.sLengthSelect
+ } );
+
+ for ( var i=0, ien=lengths.length ; i<ien ; i++ ) {
+ select[0][ i ] = new Option( language[i], lengths[i] );
+ }
+
+ var div = $('<div><label/></div>').addClass( classes.sLength );
+ if ( ! settings.aanFeatures.l ) {
+ div[0].id = tableId+'_length';
+ }
+
+ div.children().append(
+ settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML )
+ );
+
+ // Can't use `select` variable as user might provide their own and the
+ // reference is broken by the use of outerHTML
+ $('select', div)
+ .val( settings._iDisplayLength )
+ .bind( 'change.DT', function(e) {
+ _fnLengthChange( settings, $(this).val() );
+ _fnDraw( settings );
+ } );
+
+ // Update node value whenever anything changes the table's length
+ $(settings.nTable).bind( 'length.dt.DT', function (e, s, len) {
+ if ( settings === s ) {
+ $('select', div).val( len );
+ }
+ } );
+
+ return div[0];
+ }
+
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Note that most of the paging logic is done in
+ * DataTable.ext.pager
+ */
+
+ /**
+ * Generate the node required for default pagination
+ * @param {object} oSettings dataTables settings object
+ * @returns {node} Pagination feature node
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlPaginate ( settings )
+ {
+ var
+ type = settings.sPaginationType,
+ plugin = DataTable.ext.pager[ type ],
+ modern = typeof plugin === 'function',
+ redraw = function( settings ) {
+ _fnDraw( settings );
+ },
+ node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0],
+ features = settings.aanFeatures;
+
+ if ( ! modern ) {
+ plugin.fnInit( settings, node, redraw );
+ }
+
+ /* Add a draw callback for the pagination on first instance, to update the paging display */
+ if ( ! features.p )
+ {
+ node.id = settings.sTableId+'_paginate';
+
+ settings.aoDrawCallback.push( {
+ "fn": function( settings ) {
+ if ( modern ) {
+ var
+ start = settings._iDisplayStart,
+ len = settings._iDisplayLength,
+ visRecords = settings.fnRecordsDisplay(),
+ all = len === -1,
+ page = all ? 0 : Math.ceil( start / len ),
+ pages = all ? 1 : Math.ceil( visRecords / len ),
+ buttons = plugin(page, pages),
+ i, ien;
+
+ for ( i=0, ien=features.p.length ; i<ien ; i++ ) {
+ _fnRenderer( settings, 'pageButton' )(
+ settings, features.p[i], i, buttons, page, pages
+ );
+ }
+ }
+ else {
+ plugin.fnUpdate( settings, redraw );
+ }
+ },
+ "sName": "pagination"
+ } );
+ }
+
+ return node;
+ }
+
+
+ /**
+ * Alter the display settings to change the page
+ * @param {object} settings DataTables settings object
+ * @param {string|int} action Paging action to take: "first", "previous",
+ * "next" or "last" or page number to jump to (integer)
+ * @param [bool] redraw Automatically draw the update or not
+ * @returns {bool} true page has changed, false - no change
+ * @memberof DataTable#oApi
+ */
+ function _fnPageChange ( settings, action, redraw )
+ {
+ var
+ start = settings._iDisplayStart,
+ len = settings._iDisplayLength,
+ records = settings.fnRecordsDisplay();
+
+ if ( records === 0 || len === -1 )
+ {
+ start = 0;
+ }
+ else if ( typeof action === "number" )
+ {
+ start = action * len;
+
+ if ( start > records )
+ {
+ start = 0;
+ }
+ }
+ else if ( action == "first" )
+ {
+ start = 0;
+ }
+ else if ( action == "previous" )
+ {
+ start = len >= 0 ?
+ start - len :
+ 0;
+
+ if ( start < 0 )
+ {
+ start = 0;
+ }
+ }
+ else if ( action == "next" )
+ {
+ if ( start + len < records )
+ {
+ start += len;
+ }
+ }
+ else if ( action == "last" )
+ {
+ start = Math.floor( (records-1) / len) * len;
+ }
+ else
+ {
+ _fnLog( settings, 0, "Unknown paging action: "+action, 5 );
+ }
+
+ var changed = settings._iDisplayStart !== start;
+ settings._iDisplayStart = start;
+
+ if ( changed ) {
+ _fnCallbackFire( settings, null, 'page', [settings] );
+
+ if ( redraw ) {
+ _fnDraw( settings );
+ }
+ }
+
+ return changed;
+ }
+
+
+
+ /**
+ * Generate the node required for the processing node
+ * @param {object} settings dataTables settings object
+ * @returns {node} Processing element
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlProcessing ( settings )
+ {
+ return $('<div/>', {
+ 'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null,
+ 'class': settings.oClasses.sProcessing
+ } )
+ .html( settings.oLanguage.sProcessing )
+ .insertBefore( settings.nTable )[0];
+ }
+
+
+ /**
+ * Display or hide the processing indicator
+ * @param {object} settings dataTables settings object
+ * @param {bool} show Show the processing indicator (true) or not (false)
+ * @memberof DataTable#oApi
+ */
+ function _fnProcessingDisplay ( settings, show )
+ {
+ if ( settings.oFeatures.bProcessing ) {
+ $(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' );
+ }
+
+ _fnCallbackFire( settings, null, 'processing', [settings, show] );
+ }
+
+ /**
+ * Add any control elements for the table - specifically scrolling
+ * @param {object} settings dataTables settings object
+ * @returns {node} Node to add to the DOM
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlTable ( settings )
+ {
+ var table = $(settings.nTable);
+
+ // Add the ARIA grid role to the table
+ table.attr( 'role', 'grid' );
+
+ // Scrolling from here on in
+ var scroll = settings.oScroll;
+
+ if ( scroll.sX === '' && scroll.sY === '' ) {
+ return settings.nTable;
+ }
+
+ var scrollX = scroll.sX;
+ var scrollY = scroll.sY;
+ var classes = settings.oClasses;
+ var caption = table.children('caption');
+ var captionSide = caption.length ? caption[0]._captionSide : null;
+ var headerClone = $( table[0].cloneNode(false) );
+ var footerClone = $( table[0].cloneNode(false) );
+ var footer = table.children('tfoot');
+ var _div = '<div/>';
+ var size = function ( s ) {
+ return !s ? null : _fnStringToCss( s );
+ };
+
+ if ( ! footer.length ) {
+ footer = null;
+ }
+
+ /*
+ * The HTML structure that we want to generate in this function is:
+ * div - scroller
+ * div - scroll head
+ * div - scroll head inner
+ * table - scroll head table
+ * thead - thead
+ * div - scroll body
+ * table - table (master table)
+ * thead - thead clone for sizing
+ * tbody - tbody
+ * div - scroll foot
+ * div - scroll foot inner
+ * table - scroll foot table
+ * tfoot - tfoot
+ */
+ var scroller = $( _div, { 'class': classes.sScrollWrapper } )
+ .append(
+ $(_div, { 'class': classes.sScrollHead } )
+ .css( {
+ overflow: 'hidden',
+ position: 'relative',
+ border: 0,
+ width: scrollX ? size(scrollX) : '100%'
+ } )
+ .append(
+ $(_div, { 'class': classes.sScrollHeadInner } )
+ .css( {
+ 'box-sizing': 'content-box',
+ width: scroll.sXInner || '100%'
+ } )
+ .append(
+ headerClone
+ .removeAttr('id')
+ .css( 'margin-left', 0 )
+ .append( captionSide === 'top' ? caption : null )
+ .append(
+ table.children('thead')
+ )
+ )
+ )
+ )
+ .append(
+ $(_div, { 'class': classes.sScrollBody } )
+ .css( {
+ position: 'relative',
+ overflow: 'auto',
+ width: size( scrollX )
+ } )
+ .append( table )
+ );
+
+ if ( footer ) {
+ scroller.append(
+ $(_div, { 'class': classes.sScrollFoot } )
+ .css( {
+ overflow: 'hidden',
+ border: 0,
+ width: scrollX ? size(scrollX) : '100%'
+ } )
+ .append(
+ $(_div, { 'class': classes.sScrollFootInner } )
+ .append(
+ footerClone
+ .removeAttr('id')
+ .css( 'margin-left', 0 )
+ .append( captionSide === 'bottom' ? caption : null )
+ .append(
+ table.children('tfoot')
+ )
+ )
+ )
+ );
+ }
+
+ var children = scroller.children();
+ var scrollHead = children[0];
+ var scrollBody = children[1];
+ var scrollFoot = footer ? children[2] : null;
+
+ // When the body is scrolled, then we also want to scroll the headers
+ if ( scrollX ) {
+ $(scrollBody).on( 'scroll.DT', function (e) {
+ var scrollLeft = this.scrollLeft;
+
+ scrollHead.scrollLeft = scrollLeft;
+
+ if ( footer ) {
+ scrollFoot.scrollLeft = scrollLeft;
+ }
+ } );
+ }
+
+ $(scrollBody).css(
+ scrollY && scroll.bCollapse ? 'max-height' : 'height',
+ scrollY
+ );
+
+ settings.nScrollHead = scrollHead;
+ settings.nScrollBody = scrollBody;
+ settings.nScrollFoot = scrollFoot;
+
+ // On redraw - align columns
+ settings.aoDrawCallback.push( {
+ "fn": _fnScrollDraw,
+ "sName": "scrolling"
+ } );
+
+ return scroller[0];
+ }
+
+
+
+ /**
+ * Update the header, footer and body tables for resizing - i.e. column
+ * alignment.
+ *
+ * Welcome to the most horrible function DataTables. The process that this
+ * function follows is basically:
+ * 1. Re-create the table inside the scrolling div
+ * 2. Take live measurements from the DOM
+ * 3. Apply the measurements to align the columns
+ * 4. Clean up
+ *
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnScrollDraw ( settings )
+ {
+ // Given that this is such a monster function, a lot of variables are use
+ // to try and keep the minimised size as small as possible
+ var
+ scroll = settings.oScroll,
+ scrollX = scroll.sX,
+ scrollXInner = scroll.sXInner,
+ scrollY = scroll.sY,
+ barWidth = scroll.iBarWidth,
+ divHeader = $(settings.nScrollHead),
+ divHeaderStyle = divHeader[0].style,
+ divHeaderInner = divHeader.children('div'),
+ divHeaderInnerStyle = divHeaderInner[0].style,
+ divHeaderTable = divHeaderInner.children('table'),
+ divBodyEl = settings.nScrollBody,
+ divBody = $(divBodyEl),
+ divBodyStyle = divBodyEl.style,
+ divFooter = $(settings.nScrollFoot),
+ divFooterInner = divFooter.children('div'),
+ divFooterTable = divFooterInner.children('table'),
+ header = $(settings.nTHead),
+ table = $(settings.nTable),
+ tableEl = table[0],
+ tableStyle = tableEl.style,
+ footer = settings.nTFoot ? $(settings.nTFoot) : null,
+ browser = settings.oBrowser,
+ ie67 = browser.bScrollOversize,
+ headerTrgEls, footerTrgEls,
+ headerSrcEls, footerSrcEls,
+ headerCopy, footerCopy,
+ headerWidths=[], footerWidths=[],
+ headerContent=[],
+ idx, correction, sanityWidth,
+ zeroOut = function(nSizer) {
+ var style = nSizer.style;
+ style.paddingTop = "0";
+ style.paddingBottom = "0";
+ style.borderTopWidth = "0";
+ style.borderBottomWidth = "0";
+ style.height = 0;
+ };
+
+ // If the scrollbar visibility has changed from the last draw, we need to
+ // adjust the column sizes as the table width will have changed to account
+ // for the scrollbar
+ var scrollBarVis = divBodyEl.scrollHeight > divBodyEl.clientHeight;
+
+ if ( settings.scrollBarVis !== scrollBarVis && settings.scrollBarVis !== undefined ) {
+ settings.scrollBarVis = scrollBarVis;
+ _fnAdjustColumnSizing( settings );
+ return; // adjust column sizing will call this function again
+ }
+ else {
+ settings.scrollBarVis = scrollBarVis;
+ }
+
+ /*
+ * 1. Re-create the table inside the scrolling div
+ */
+
+ // Remove the old minimised thead and tfoot elements in the inner table
+ table.children('thead, tfoot').remove();
+
+ // Clone the current header and footer elements and then place it into the inner table
+ headerCopy = header.clone().prependTo( table );
+ headerTrgEls = header.find('tr'); // original header is in its own table
+ headerSrcEls = headerCopy.find('tr');
+ headerCopy.find('th, td').removeAttr('tabindex');
+
+ if ( footer ) {
+ footerCopy = footer.clone().prependTo( table );
+ footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
+ footerSrcEls = footerCopy.find('tr');
+ }
+
+
+ /*
+ * 2. Take live measurements from the DOM - do not alter the DOM itself!
+ */
+
+ // Remove old sizing and apply the calculated column widths
+ // Get the unique column headers in the newly created (cloned) header. We want to apply the
+ // calculated sizes to this header
+ if ( ! scrollX )
+ {
+ divBodyStyle.width = '100%';
+ divHeader[0].style.width = '100%';
+ }
+
+ $.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) {
+ idx = _fnVisibleToColumnIndex( settings, i );
+ el.style.width = settings.aoColumns[idx].sWidth;
+ } );
+
+ if ( footer ) {
+ _fnApplyToChildren( function(n) {
+ n.style.width = "";
+ }, footerSrcEls );
+ }
+
+ // Size the table as a whole
+ sanityWidth = table.outerWidth();
+ if ( scrollX === "" ) {
+ // No x scrolling
+ tableStyle.width = "100%";
+
+ // IE7 will make the width of the table when 100% include the scrollbar
+ // - which is shouldn't. When there is a scrollbar we need to take this
+ // into account.
+ if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
+ divBody.css('overflow-y') == "scroll")
+ ) {
+ tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth);
+ }
+
+ // Recalculate the sanity width
+ sanityWidth = table.outerWidth();
+ }
+ else if ( scrollXInner !== "" ) {
+ // legacy x scroll inner has been given - use it
+ tableStyle.width = _fnStringToCss(scrollXInner);
+
+ // Recalculate the sanity width
+ sanityWidth = table.outerWidth();
+ }
+
+ // Hidden header should have zero height, so remove padding and borders. Then
+ // set the width based on the real headers
+
+ // Apply all styles in one pass
+ _fnApplyToChildren( zeroOut, headerSrcEls );
+
+ // Read all widths in next pass
+ _fnApplyToChildren( function(nSizer) {
+ headerContent.push( nSizer.innerHTML );
+ headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
+ }, headerSrcEls );
+
+ // Apply all widths in final pass
+ _fnApplyToChildren( function(nToSize, i) {
+ nToSize.style.width = headerWidths[i];
+ }, headerTrgEls );
+
+ $(headerSrcEls).height(0);
+
+ /* Same again with the footer if we have one */
+ if ( footer )
+ {
+ _fnApplyToChildren( zeroOut, footerSrcEls );
+
+ _fnApplyToChildren( function(nSizer) {
+ footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
+ }, footerSrcEls );
+
+ _fnApplyToChildren( function(nToSize, i) {
+ nToSize.style.width = footerWidths[i];
+ }, footerTrgEls );
+
+ $(footerSrcEls).height(0);
+ }
+
+
+ /*
+ * 3. Apply the measurements
+ */
+
+ // "Hide" the header and footer that we used for the sizing. We need to keep
+ // the content of the cell so that the width applied to the header and body
+ // both match, but we want to hide it completely. We want to also fix their
+ // width to what they currently are
+ _fnApplyToChildren( function(nSizer, i) {
+ nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>';
+ nSizer.style.width = headerWidths[i];
+ }, headerSrcEls );
+
+ if ( footer )
+ {
+ _fnApplyToChildren( function(nSizer, i) {
+ nSizer.innerHTML = "";
+ nSizer.style.width = footerWidths[i];
+ }, footerSrcEls );
+ }
+
+ // Sanity check that the table is of a sensible width. If not then we are going to get
+ // misalignment - try to prevent this by not allowing the table to shrink below its min width
+ if ( table.outerWidth() < sanityWidth )
+ {
+ // The min width depends upon if we have a vertical scrollbar visible or not */
+ correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
+ divBody.css('overflow-y') == "scroll")) ?
+ sanityWidth+barWidth :
+ sanityWidth;
+
+ // IE6/7 are a law unto themselves...
+ if ( ie67 && (divBodyEl.scrollHeight >
+ divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
+ ) {
+ tableStyle.width = _fnStringToCss( correction-barWidth );
+ }
+
+ // And give the user a warning that we've stopped the table getting too small
+ if ( scrollX === "" || scrollXInner !== "" ) {
+ _fnLog( settings, 1, 'Possible column misalignment', 6 );
+ }
+ }
+ else
+ {
+ correction = '100%';
+ }
+
+ // Apply to the container elements
+ divBodyStyle.width = _fnStringToCss( correction );
+ divHeaderStyle.width = _fnStringToCss( correction );
+
+ if ( footer ) {
+ settings.nScrollFoot.style.width = _fnStringToCss( correction );
+ }
+
+
+ /*
+ * 4. Clean up
+ */
+ if ( ! scrollY ) {
+ /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
+ * the scrollbar height from the visible display, rather than adding it on. We need to
+ * set the height in order to sort this. Don't want to do it in any other browsers.
+ */
+ if ( ie67 ) {
+ divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth );
+ }
+ }
+
+ /* Finally set the width's of the header and footer tables */
+ var iOuterWidth = table.outerWidth();
+ divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth );
+ divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth );
+
+ // Figure out if there are scrollbar present - if so then we need a the header and footer to
+ // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
+ var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
+ var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
+ divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px";
+
+ if ( footer ) {
+ divFooterTable[0].style.width = _fnStringToCss( iOuterWidth );
+ divFooterInner[0].style.width = _fnStringToCss( iOuterWidth );
+ divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px";
+ }
+
+ /* Adjust the position of the header in case we loose the y-scrollbar */
+ divBody.scroll();
+
+ // If sorting or filtering has occurred, jump the scrolling back to the top
+ // only if we aren't holding the position
+ if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) {
+ divBodyEl.scrollTop = 0;
+ }
+ }
+
+
+
+ /**
+ * Apply a given function to the display child nodes of an element array (typically
+ * TD children of TR rows
+ * @param {function} fn Method to apply to the objects
+ * @param array {nodes} an1 List of elements to look through for display children
+ * @param array {nodes} an2 Another list (identical structure to the first) - optional
+ * @memberof DataTable#oApi
+ */
+ function _fnApplyToChildren( fn, an1, an2 )
+ {
+ var index=0, i=0, iLen=an1.length;
+ var nNode1, nNode2;
+
+ while ( i < iLen ) {
+ nNode1 = an1[i].firstChild;
+ nNode2 = an2 ? an2[i].firstChild : null;
+
+ while ( nNode1 ) {
+ if ( nNode1.nodeType === 1 ) {
+ if ( an2 ) {
+ fn( nNode1, nNode2, index );
+ }
+ else {
+ fn( nNode1, index );
+ }
+
+ index++;
+ }
+
+ nNode1 = nNode1.nextSibling;
+ nNode2 = an2 ? nNode2.nextSibling : null;
+ }
+
+ i++;
+ }
+ }
+
+
+
+ var __re_html_remove = /<.*?>/g;
+
+
+ /**
+ * Calculate the width of columns for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnCalculateColumnWidths ( oSettings )
+ {
+ var
+ table = oSettings.nTable,
+ columns = oSettings.aoColumns,
+ scroll = oSettings.oScroll,
+ scrollY = scroll.sY,
+ scrollX = scroll.sX,
+ scrollXInner = scroll.sXInner,
+ columnCount = columns.length,
+ visibleColumns = _fnGetColumns( oSettings, 'bVisible' ),
+ headerCells = $('th', oSettings.nTHead),
+ tableWidthAttr = table.getAttribute('width'), // from DOM element
+ tableContainer = table.parentNode,
+ userInputs = false,
+ i, column, columnIdx, width, outerWidth,
+ browser = oSettings.oBrowser,
+ ie67 = browser.bScrollOversize;
+
+ var styleWidth = table.style.width;
+ if ( styleWidth && styleWidth.indexOf('%') !== -1 ) {
+ tableWidthAttr = styleWidth;
+ }
+
+ /* Convert any user input sizes into pixel sizes */
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+
+ if ( column.sWidth !== null ) {
+ column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer );
+
+ userInputs = true;
+ }
+ }
+
+ /* If the number of columns in the DOM equals the number that we have to
+ * process in DataTables, then we can use the offsets that are created by
+ * the web- browser. No custom sizes can be set in order for this to happen,
+ * nor scrolling used
+ */
+ if ( ie67 || ! userInputs && ! scrollX && ! scrollY &&
+ columnCount == _fnVisbleColumns( oSettings ) &&
+ columnCount == headerCells.length
+ ) {
+ for ( i=0 ; i<columnCount ; i++ ) {
+ var colIdx = _fnVisibleToColumnIndex( oSettings, i );
+
+ if ( colIdx !== null ) {
+ columns[ colIdx ].sWidth = _fnStringToCss( headerCells.eq(i).width() );
+ }
+ }
+ }
+ else
+ {
+ // Otherwise construct a single row, worst case, table with the widest
+ // node in the data, assign any user defined widths, then insert it into
+ // the DOM and allow the browser to do all the hard work of calculating
+ // table widths
+ var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table
+ .css( 'visibility', 'hidden' )
+ .removeAttr( 'id' );
+
+ // Clean up the table body
+ tmpTable.find('tbody tr').remove();
+ var tr = $('<tr/>').appendTo( tmpTable.find('tbody') );
+
+ // Clone the table header and footer - we can't use the header / footer
+ // from the cloned table, since if scrolling is active, the table's
+ // real header and footer are contained in different table tags
+ tmpTable.find('thead, tfoot').remove();
+ tmpTable
+ .append( $(oSettings.nTHead).clone() )
+ .append( $(oSettings.nTFoot).clone() );
+
+ // Remove any assigned widths from the footer (from scrolling)
+ tmpTable.find('tfoot th, tfoot td').css('width', '');
+
+ // Apply custom sizing to the cloned header
+ headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );
+
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+
+ headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
+ _fnStringToCss( column.sWidthOrig ) :
+ '';
+
+ // For scrollX we need to force the column width otherwise the
+ // browser will collapse it. If this width is smaller than the
+ // width the column requires, then it will have no effect
+ if ( column.sWidthOrig && scrollX ) {
+ $( headerCells[i] ).append( $('<div/>').css( {
+ width: column.sWidthOrig,
+ margin: 0,
+ padding: 0,
+ border: 0,
+ height: 1
+ } ) );
+ }
+ }
+
+ // Find the widest cell for each column and put it into the table
+ if ( oSettings.aoData.length ) {
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ columnIdx = visibleColumns[i];
+ column = columns[ columnIdx ];
+
+ $( _fnGetWidestNode( oSettings, columnIdx ) )
+ .clone( false )
+ .append( column.sContentPadding )
+ .appendTo( tr );
+ }
+ }
+
+ // Table has been built, attach to the document so we can work with it.
+ // A holding element is used, positioned at the top of the container
+ // with minimal height, so it has no effect on if the container scrolls
+ // or not. Otherwise it might trigger scrolling when it actually isn't
+ // needed
+ var holder = $('<div/>').css( scrollX || scrollY ?
+ {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ height: 1,
+ right: 0,
+ overflow: 'hidden'
+ } :
+ {}
+ )
+ .append( tmpTable )
+ .appendTo( tableContainer );
+
+ // When scrolling (X or Y) we want to set the width of the table as
+ // appropriate. However, when not scrolling leave the table width as it
+ // is. This results in slightly different, but I think correct behaviour
+ if ( scrollX && scrollXInner ) {
+ tmpTable.width( scrollXInner );
+ }
+ else if ( scrollX ) {
+ tmpTable.css( 'width', 'auto' );
+ tmpTable.removeAttr('width');
+
+ // If there is no width attribute or style, then allow the table to
+ // collapse
+ if ( tmpTable.width() < tableContainer.clientWidth && tableWidthAttr ) {
+ tmpTable.width( tableContainer.clientWidth );
+ }
+ }
+ else if ( scrollY ) {
+ tmpTable.width( tableContainer.clientWidth );
+ }
+ else if ( tableWidthAttr ) {
+ tmpTable.width( tableWidthAttr );
+ }
+
+ // Get the width of each column in the constructed table - we need to
+ // know the inner width (so it can be assigned to the other table's
+ // cells) and the outer width so we can calculate the full width of the
+ // table. This is safe since DataTables requires a unique cell for each
+ // column, but if ever a header can span multiple columns, this will
+ // need to be modified.
+ var total = 0;
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ var cell = $(headerCells[i]);
+ var border = cell.outerWidth() - cell.width();
+
+ // Use getBounding... where possible (not IE8-) because it can give
+ // sub-pixel accuracy, which we then want to round up!
+ var bounding = browser.bBounding ?
+ Math.ceil( headerCells[i].getBoundingClientRect().width ) :
+ cell.outerWidth();
+
+ // Total is tracked to remove any sub-pixel errors as the outerWidth
+ // of the table might not equal the total given here (IE!).
+ total += bounding;
+
+ // Width for each column to use
+ columns[ visibleColumns[i] ].sWidth = _fnStringToCss( bounding - border );
+ }
+
+ table.style.width = _fnStringToCss( total );
+
+ // Finished with the table - ditch it
+ holder.remove();
+ }
+
+ // If there is a width attr, we want to attach an event listener which
+ // allows the table sizing to automatically adjust when the window is
+ // resized. Use the width attr rather than CSS, since we can't know if the
+ // CSS is a relative value or absolute - DOM read is always px.
+ if ( tableWidthAttr ) {
+ table.style.width = _fnStringToCss( tableWidthAttr );
+ }
+
+ if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) {
+ var bindResize = function () {
+ $(window).bind('resize.DT-'+oSettings.sInstance, _fnThrottle( function () {
+ _fnAdjustColumnSizing( oSettings );
+ } ) );
+ };
+
+ // IE6/7 will crash if we bind a resize event handler on page load.
+ // To be removed in 1.11 which drops IE6/7 support
+ if ( ie67 ) {
+ setTimeout( bindResize, 1000 );
+ }
+ else {
+ bindResize();
+ }
+
+ oSettings._reszEvt = true;
+ }
+ }
+
+
+ /**
+ * Throttle the calls to a function. Arguments and context are maintained for
+ * the throttled function
+ * @param {function} fn Function to be called
+ * @param {int} [freq=200] call frequency in mS
+ * @returns {function} wrapped function
+ * @memberof DataTable#oApi
+ */
+ function _fnThrottle( fn, freq ) {
+ var
+ frequency = freq !== undefined ? freq : 200,
+ last,
+ timer;
+
+ return function () {
+ var
+ that = this,
+ now = +new Date(),
+ args = arguments;
+
+ if ( last && now < last + frequency ) {
+ clearTimeout( timer );
+
+ timer = setTimeout( function () {
+ last = undefined;
+ fn.apply( that, args );
+ }, frequency );
+ }
+ else {
+ last = now;
+ fn.apply( that, args );
+ }
+ };
+ }
+
+
+ /**
+ * Convert a CSS unit width to pixels (e.g. 2em)
+ * @param {string} width width to be converted
+ * @param {node} parent parent to get the with for (required for relative widths) - optional
+ * @returns {int} width in pixels
+ * @memberof DataTable#oApi
+ */
+ function _fnConvertToWidth ( width, parent )
+ {
+ if ( ! width ) {
+ return 0;
+ }
+
+ var n = $('<div/>')
+ .css( 'width', _fnStringToCss( width ) )
+ .appendTo( parent || document.body );
+
+ var val = n[0].offsetWidth;
+ n.remove();
+
+ return val;
+ }
+
+
+ /**
+ * Get the widest node
+ * @param {object} settings dataTables settings object
+ * @param {int} colIdx column of interest
+ * @returns {node} widest table node
+ * @memberof DataTable#oApi
+ */
+ function _fnGetWidestNode( settings, colIdx )
+ {
+ var idx = _fnGetMaxLenString( settings, colIdx );
+ if ( idx < 0 ) {
+ return null;
+ }
+
+ var data = settings.aoData[ idx ];
+ return ! data.nTr ? // Might not have been created when deferred rendering
+ $('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] :
+ data.anCells[ colIdx ];
+ }
+
+
+ /**
+ * Get the maximum strlen for each data column
+ * @param {object} settings dataTables settings object
+ * @param {int} colIdx column of interest
+ * @returns {string} max string length for each column
+ * @memberof DataTable#oApi
+ */
+ function _fnGetMaxLenString( settings, colIdx )
+ {
+ var s, max=-1, maxIdx = -1;
+
+ for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ s = _fnGetCellData( settings, i, colIdx, 'display' )+'';
+ s = s.replace( __re_html_remove, '' );
+ s = s.replace( /&nbsp;/g, ' ' );
+
+ if ( s.length > max ) {
+ max = s.length;
+ maxIdx = i;
+ }
+ }
+
+ return maxIdx;
+ }
+
+
+ /**
+ * Append a CSS unit (only if required) to a string
+ * @param {string} value to css-ify
+ * @returns {string} value with css unit
+ * @memberof DataTable#oApi
+ */
+ function _fnStringToCss( s )
+ {
+ if ( s === null ) {
+ return '0px';
+ }
+
+ if ( typeof s == 'number' ) {
+ return s < 0 ?
+ '0px' :
+ s+'px';
+ }
+
+ // Check it has a unit character already
+ return s.match(/\d$/) ?
+ s+'px' :
+ s;
+ }
+
+
+
+ function _fnSortFlatten ( settings )
+ {
+ var
+ i, iLen, k, kLen,
+ aSort = [],
+ aiOrig = [],
+ aoColumns = settings.aoColumns,
+ aDataSort, iCol, sType, srcCol,
+ fixed = settings.aaSortingFixed,
+ fixedObj = $.isPlainObject( fixed ),
+ nestedSort = [],
+ add = function ( a ) {
+ if ( a.length && ! $.isArray( a[0] ) ) {
+ // 1D array
+ nestedSort.push( a );
+ }
+ else {
+ // 2D array
+ $.merge( nestedSort, a );
+ }
+ };
+
+ // Build the sort array, with pre-fix and post-fix options if they have been
+ // specified
+ if ( $.isArray( fixed ) ) {
+ add( fixed );
+ }
+
+ if ( fixedObj && fixed.pre ) {
+ add( fixed.pre );
+ }
+
+ add( settings.aaSorting );
+
+ if (fixedObj && fixed.post ) {
+ add( fixed.post );
+ }
+
+ for ( i=0 ; i<nestedSort.length ; i++ )
+ {
+ srcCol = nestedSort[i][0];
+ aDataSort = aoColumns[ srcCol ].aDataSort;
+
+ for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
+ {
+ iCol = aDataSort[k];
+ sType = aoColumns[ iCol ].sType || 'string';
+
+ if ( nestedSort[i]._idx === undefined ) {
+ nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting );
+ }
+
+ aSort.push( {
+ src: srcCol,
+ col: iCol,
+ dir: nestedSort[i][1],
+ index: nestedSort[i]._idx,
+ type: sType,
+ formatter: DataTable.ext.type.order[ sType+"-pre" ]
+ } );
+ }
+ }
+
+ return aSort;
+ }
+
+ /**
+ * Change the order of the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ * @todo This really needs split up!
+ */
+ function _fnSort ( oSettings )
+ {
+ var
+ i, ien, iLen, j, jLen, k, kLen,
+ sDataType, nTh,
+ aiOrig = [],
+ oExtSort = DataTable.ext.type.order,
+ aoData = oSettings.aoData,
+ aoColumns = oSettings.aoColumns,
+ aDataSort, data, iCol, sType, oSort,
+ formatters = 0,
+ sortCol,
+ displayMaster = oSettings.aiDisplayMaster,
+ aSort;
+
+ // Resolve any column types that are unknown due to addition or invalidation
+ // @todo Can this be moved into a 'data-ready' handler which is called when
+ // data is going to be used in the table?
+ _fnColumnTypes( oSettings );
+
+ aSort = _fnSortFlatten( oSettings );
+
+ for ( i=0, ien=aSort.length ; i<ien ; i++ ) {
+ sortCol = aSort[i];
+
+ // Track if we can use the fast sort algorithm
+ if ( sortCol.formatter ) {
+ formatters++;
+ }
+
+ // Load the data needed for the sort, for each cell
+ _fnSortData( oSettings, sortCol.col );
+ }
+
+ /* No sorting required if server-side or no sorting array */
+ if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 )
+ {
+ // Create a value - key array of the current row positions such that we can use their
+ // current position during the sort, if values match, in order to perform stable sorting
+ for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) {
+ aiOrig[ displayMaster[i] ] = i;
+ }
+
+ /* Do the sort - here we want multi-column sorting based on a given data source (column)
+ * and sorting function (from oSort) in a certain direction. It's reasonably complex to
+ * follow on it's own, but this is what we want (example two column sorting):
+ * fnLocalSorting = function(a,b){
+ * var iTest;
+ * iTest = oSort['string-asc']('data11', 'data12');
+ * if (iTest !== 0)
+ * return iTest;
+ * iTest = oSort['numeric-desc']('data21', 'data22');
+ * if (iTest !== 0)
+ * return iTest;
+ * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
+ * }
+ * Basically we have a test for each sorting column, if the data in that column is equal,
+ * test the next column. If all columns match, then we use a numeric sort on the row
+ * positions in the original data array to provide a stable sort.
+ *
+ * Note - I know it seems excessive to have two sorting methods, but the first is around
+ * 15% faster, so the second is only maintained for backwards compatibility with sorting
+ * methods which do not have a pre-sort formatting function.
+ */
+ if ( formatters === aSort.length ) {
+ // All sort types have formatting functions
+ displayMaster.sort( function ( a, b ) {
+ var
+ x, y, k, test, sort,
+ len=aSort.length,
+ dataA = aoData[a]._aSortData,
+ dataB = aoData[b]._aSortData;
+
+ for ( k=0 ; k<len ; k++ ) {
+ sort = aSort[k];
+
+ x = dataA[ sort.col ];
+ y = dataB[ sort.col ];
+
+ test = x<y ? -1 : x>y ? 1 : 0;
+ if ( test !== 0 ) {
+ return sort.dir === 'asc' ? test : -test;
+ }
+ }
+
+ x = aiOrig[a];
+ y = aiOrig[b];
+ return x<y ? -1 : x>y ? 1 : 0;
+ } );
+ }
+ else {
+ // Depreciated - remove in 1.11 (providing a plug-in option)
+ // Not all sort types have formatting methods, so we have to call their sorting
+ // methods.
+ displayMaster.sort( function ( a, b ) {
+ var
+ x, y, k, l, test, sort, fn,
+ len=aSort.length,
+ dataA = aoData[a]._aSortData,
+ dataB = aoData[b]._aSortData;
+
+ for ( k=0 ; k<len ; k++ ) {
+ sort = aSort[k];
+
+ x = dataA[ sort.col ];
+ y = dataB[ sort.col ];
+
+ fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ];
+ test = fn( x, y );
+ if ( test !== 0 ) {
+ return test;
+ }
+ }
+
+ x = aiOrig[a];
+ y = aiOrig[b];
+ return x<y ? -1 : x>y ? 1 : 0;
+ } );
+ }
+ }
+
+ /* Tell the draw function that we have sorted the data */
+ oSettings.bSorted = true;
+ }
+
+
+ function _fnSortAria ( settings )
+ {
+ var label;
+ var nextSort;
+ var columns = settings.aoColumns;
+ var aSort = _fnSortFlatten( settings );
+ var oAria = settings.oLanguage.oAria;
+
+ // ARIA attributes - need to loop all columns, to update all (removing old
+ // attributes as needed)
+ for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
+ {
+ var col = columns[i];
+ var asSorting = col.asSorting;
+ var sTitle = col.sTitle.replace( /<.*?>/g, "" );
+ var th = col.nTh;
+
+ // IE7 is throwing an error when setting these properties with jQuery's
+ // attr() and removeAttr() methods...
+ th.removeAttribute('aria-sort');
+
+ /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
+ if ( col.bSortable ) {
+ if ( aSort.length > 0 && aSort[0].col == i ) {
+ th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" );
+ nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0];
+ }
+ else {
+ nextSort = asSorting[0];
+ }
+
+ label = sTitle + ( nextSort === "asc" ?
+ oAria.sSortAscending :
+ oAria.sSortDescending
+ );
+ }
+ else {
+ label = sTitle;
+ }
+
+ th.setAttribute('aria-label', label);
+ }
+ }
+
+
+ /**
+ * Function to run on user sort request
+ * @param {object} settings dataTables settings object
+ * @param {node} attachTo node to attach the handler to
+ * @param {int} colIdx column sorting index
+ * @param {boolean} [append=false] Append the requested sort to the existing
+ * sort if true (i.e. multi-column sort)
+ * @param {function} [callback] callback function
+ * @memberof DataTable#oApi
+ */
+ function _fnSortListener ( settings, colIdx, append, callback )
+ {
+ var col = settings.aoColumns[ colIdx ];
+ var sorting = settings.aaSorting;
+ var asSorting = col.asSorting;
+ var nextSortIdx;
+ var next = function ( a, overflow ) {
+ var idx = a._idx;
+ if ( idx === undefined ) {
+ idx = $.inArray( a[1], asSorting );
+ }
+
+ return idx+1 < asSorting.length ?
+ idx+1 :
+ overflow ?
+ null :
+ 0;
+ };
+
+ // Convert to 2D array if needed
+ if ( typeof sorting[0] === 'number' ) {
+ sorting = settings.aaSorting = [ sorting ];
+ }
+
+ // If appending the sort then we are multi-column sorting
+ if ( append && settings.oFeatures.bSortMulti ) {
+ // Are we already doing some kind of sort on this column?
+ var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
+
+ if ( sortIdx !== -1 ) {
+ // Yes, modify the sort
+ nextSortIdx = next( sorting[sortIdx], true );
+
+ if ( nextSortIdx === null && sorting.length === 1 ) {
+ nextSortIdx = 0; // can't remove sorting completely
+ }
+
+ if ( nextSortIdx === null ) {
+ sorting.splice( sortIdx, 1 );
+ }
+ else {
+ sorting[sortIdx][1] = asSorting[ nextSortIdx ];
+ sorting[sortIdx]._idx = nextSortIdx;
+ }
+ }
+ else {
+ // No sort on this column yet
+ sorting.push( [ colIdx, asSorting[0], 0 ] );
+ sorting[sorting.length-1]._idx = 0;
+ }
+ }
+ else if ( sorting.length && sorting[0][0] == colIdx ) {
+ // Single column - already sorting on this column, modify the sort
+ nextSortIdx = next( sorting[0] );
+
+ sorting.length = 1;
+ sorting[0][1] = asSorting[ nextSortIdx ];
+ sorting[0]._idx = nextSortIdx;
+ }
+ else {
+ // Single column - sort only on this column
+ sorting.length = 0;
+ sorting.push( [ colIdx, asSorting[0] ] );
+ sorting[0]._idx = 0;
+ }
+
+ // Run the sort by calling a full redraw
+ _fnReDraw( settings );
+
+ // callback used for async user interaction
+ if ( typeof callback == 'function' ) {
+ callback( settings );
+ }
+ }
+
+
+ /**
+ * Attach a sort handler (click) to a node
+ * @param {object} settings dataTables settings object
+ * @param {node} attachTo node to attach the handler to
+ * @param {int} colIdx column sorting index
+ * @param {function} [callback] callback function
+ * @memberof DataTable#oApi
+ */
+ function _fnSortAttachListener ( settings, attachTo, colIdx, callback )
+ {
+ var col = settings.aoColumns[ colIdx ];
+
+ _fnBindAction( attachTo, {}, function (e) {
+ /* If the column is not sortable - don't to anything */
+ if ( col.bSortable === false ) {
+ return;
+ }
+
+ // If processing is enabled use a timeout to allow the processing
+ // display to be shown - otherwise to it synchronously
+ if ( settings.oFeatures.bProcessing ) {
+ _fnProcessingDisplay( settings, true );
+
+ setTimeout( function() {
+ _fnSortListener( settings, colIdx, e.shiftKey, callback );
+
+ // In server-side processing, the draw callback will remove the
+ // processing display
+ if ( _fnDataSource( settings ) !== 'ssp' ) {
+ _fnProcessingDisplay( settings, false );
+ }
+ }, 0 );
+ }
+ else {
+ _fnSortListener( settings, colIdx, e.shiftKey, callback );
+ }
+ } );
+ }
+
+
+ /**
+ * Set the sorting classes on table's body, Note: it is safe to call this function
+ * when bSort and bSortClasses are false
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnSortingClasses( settings )
+ {
+ var oldSort = settings.aLastSort;
+ var sortClass = settings.oClasses.sSortColumn;
+ var sort = _fnSortFlatten( settings );
+ var features = settings.oFeatures;
+ var i, ien, colIdx;
+
+ if ( features.bSort && features.bSortClasses ) {
+ // Remove old sorting classes
+ for ( i=0, ien=oldSort.length ; i<ien ; i++ ) {
+ colIdx = oldSort[i].src;
+
+ // Remove column sorting
+ $( _pluck( settings.aoData, 'anCells', colIdx ) )
+ .removeClass( sortClass + (i<2 ? i+1 : 3) );
+ }
+
+ // Add new column sorting
+ for ( i=0, ien=sort.length ; i<ien ; i++ ) {
+ colIdx = sort[i].src;
+
+ $( _pluck( settings.aoData, 'anCells', colIdx ) )
+ .addClass( sortClass + (i<2 ? i+1 : 3) );
+ }
+ }
+
+ settings.aLastSort = sort;
+ }
+
+
+ // Get the data to sort a column, be it from cache, fresh (populating the
+ // cache), or from a sort formatter
+ function _fnSortData( settings, idx )
+ {
+ // Custom sorting function - provided by the sort data type
+ var column = settings.aoColumns[ idx ];
+ var customSort = DataTable.ext.order[ column.sSortDataType ];
+ var customData;
+
+ if ( customSort ) {
+ customData = customSort.call( settings.oInstance, settings, idx,
+ _fnColumnIndexToVisible( settings, idx )
+ );
+ }
+
+ // Use / populate cache
+ var row, cellData;
+ var formatter = DataTable.ext.type.order[ column.sType+"-pre" ];
+
+ for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ row = settings.aoData[i];
+
+ if ( ! row._aSortData ) {
+ row._aSortData = [];
+ }
+
+ if ( ! row._aSortData[idx] || customSort ) {
+ cellData = customSort ?
+ customData[i] : // If there was a custom sort function, use data from there
+ _fnGetCellData( settings, i, idx, 'sort' );
+
+ row._aSortData[ idx ] = formatter ?
+ formatter( cellData ) :
+ cellData;
+ }
+ }
+ }
+
+
+
+ /**
+ * Save the state of a table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnSaveState ( settings )
+ {
+ if ( !settings.oFeatures.bStateSave || settings.bDestroying )
+ {
+ return;
+ }
+
+ /* Store the interesting variables */
+ var state = {
+ time: +new Date(),
+ start: settings._iDisplayStart,
+ length: settings._iDisplayLength,
+ order: $.extend( true, [], settings.aaSorting ),
+ search: _fnSearchToCamel( settings.oPreviousSearch ),
+ columns: $.map( settings.aoColumns, function ( col, i ) {
+ return {
+ visible: col.bVisible,
+ search: _fnSearchToCamel( settings.aoPreSearchCols[i] )
+ };
+ } )
+ };
+
+ _fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] );
+
+ settings.oSavedState = state;
+ settings.fnStateSaveCallback.call( settings.oInstance, settings, state );
+ }
+
+
+ /**
+ * Attempt to load a saved table state
+ * @param {object} oSettings dataTables settings object
+ * @param {object} oInit DataTables init object so we can override settings
+ * @memberof DataTable#oApi
+ */
+ function _fnLoadState ( settings, oInit )
+ {
+ var i, ien;
+ var columns = settings.aoColumns;
+
+ if ( ! settings.oFeatures.bStateSave ) {
+ return;
+ }
+
+ var state = settings.fnStateLoadCallback.call( settings.oInstance, settings );
+ if ( ! state || ! state.time ) {
+ return;
+ }
+
+ /* Allow custom and plug-in manipulation functions to alter the saved data set and
+ * cancelling of loading by returning false
+ */
+ var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, state] );
+ if ( $.inArray( false, abStateLoad ) !== -1 ) {
+ return;
+ }
+
+ /* Reject old data */
+ var duration = settings.iStateDuration;
+ if ( duration > 0 && state.time < +new Date() - (duration*1000) ) {
+ return;
+ }
+
+ // Number of columns have changed - all bets are off, no restore of settings
+ if ( columns.length !== state.columns.length ) {
+ return;
+ }
+
+ // Store the saved state so it might be accessed at any time
+ settings.oLoadedState = $.extend( true, {}, state );
+
+ // Restore key features - todo - for 1.11 this needs to be done by
+ // subscribed events
+ if ( state.start !== undefined ) {
+ settings._iDisplayStart = state.start;
+ settings.iInitDisplayStart = state.start;
+ }
+ if ( state.length !== undefined ) {
+ settings._iDisplayLength = state.length;
+ }
+
+ // Order
+ if ( state.order !== undefined ) {
+ settings.aaSorting = [];
+ $.each( state.order, function ( i, col ) {
+ settings.aaSorting.push( col[0] >= columns.length ?
+ [ 0, col[1] ] :
+ col
+ );
+ } );
+ }
+
+ // Search
+ if ( state.search !== undefined ) {
+ $.extend( settings.oPreviousSearch, _fnSearchToHung( state.search ) );
+ }
+
+ // Columns
+ for ( i=0, ien=state.columns.length ; i<ien ; i++ ) {
+ var col = state.columns[i];
+
+ // Visibility
+ if ( col.visible !== undefined ) {
+ columns[i].bVisible = col.visible;
+ }
+
+ // Search
+ if ( col.search !== undefined ) {
+ $.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) );
+ }
+ }
+
+ _fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, state] );
+ }
+
+
+ /**
+ * Return the settings object for a particular table
+ * @param {node} table table we are using as a dataTable
+ * @returns {object} Settings object - or null if not found
+ * @memberof DataTable#oApi
+ */
+ function _fnSettingsFromNode ( table )
+ {
+ var settings = DataTable.settings;
+ var idx = $.inArray( table, _pluck( settings, 'nTable' ) );
+
+ return idx !== -1 ?
+ settings[ idx ] :
+ null;
+ }
+
+
+ /**
+ * Log an error message
+ * @param {object} settings dataTables settings object
+ * @param {int} level log error messages, or display them to the user
+ * @param {string} msg error message
+ * @param {int} tn Technical note id to get more information about the error.
+ * @memberof DataTable#oApi
+ */
+ function _fnLog( settings, level, msg, tn )
+ {
+ msg = 'DataTables warning: '+
+ (settings ? 'table id='+settings.sTableId+' - ' : '')+msg;
+
+ if ( tn ) {
+ msg += '. For more information about this error, please see '+
+ 'http://datatables.net/tn/'+tn;
+ }
+
+ if ( ! level ) {
+ // Backwards compatibility pre 1.10
+ var ext = DataTable.ext;
+ var type = ext.sErrMode || ext.errMode;
+
+ if ( settings ) {
+ _fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] );
+ }
+
+ if ( type == 'alert' ) {
+ alert( msg );
+ }
+ else if ( type == 'throw' ) {
+ throw new Error(msg);
+ }
+ else if ( typeof type == 'function' ) {
+ type( settings, tn, msg );
+ }
+ }
+ else if ( window.console && console.log ) {
+ console.log( msg );
+ }
+ }
+
+
+ /**
+ * See if a property is defined on one object, if so assign it to the other object
+ * @param {object} ret target object
+ * @param {object} src source object
+ * @param {string} name property
+ * @param {string} [mappedName] name to map too - optional, name used if not given
+ * @memberof DataTable#oApi
+ */
+ function _fnMap( ret, src, name, mappedName )
+ {
+ if ( $.isArray( name ) ) {
+ $.each( name, function (i, val) {
+ if ( $.isArray( val ) ) {
+ _fnMap( ret, src, val[0], val[1] );
+ }
+ else {
+ _fnMap( ret, src, val );
+ }
+ } );
+
+ return;
+ }
+
+ if ( mappedName === undefined ) {
+ mappedName = name;
+ }
+
+ if ( src[name] !== undefined ) {
+ ret[mappedName] = src[name];
+ }
+ }
+
+
+ /**
+ * Extend objects - very similar to jQuery.extend, but deep copy objects, and
+ * shallow copy arrays. The reason we need to do this, is that we don't want to
+ * deep copy array init values (such as aaSorting) since the dev wouldn't be
+ * able to override them, but we do want to deep copy arrays.
+ * @param {object} out Object to extend
+ * @param {object} extender Object from which the properties will be applied to
+ * out
+ * @param {boolean} breakRefs If true, then arrays will be sliced to take an
+ * independent copy with the exception of the `data` or `aaData` parameters
+ * if they are present. This is so you can pass in a collection to
+ * DataTables and have that used as your data source without breaking the
+ * references
+ * @returns {object} out Reference, just for convenience - out === the return.
+ * @memberof DataTable#oApi
+ * @todo This doesn't take account of arrays inside the deep copied objects.
+ */
+ function _fnExtend( out, extender, breakRefs )
+ {
+ var val;
+
+ for ( var prop in extender ) {
+ if ( extender.hasOwnProperty(prop) ) {
+ val = extender[prop];
+
+ if ( $.isPlainObject( val ) ) {
+ if ( ! $.isPlainObject( out[prop] ) ) {
+ out[prop] = {};
+ }
+ $.extend( true, out[prop], val );
+ }
+ else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) {
+ out[prop] = val.slice();
+ }
+ else {
+ out[prop] = val;
+ }
+ }
+ }
+
+ return out;
+ }
+
+
+ /**
+ * Bind an event handers to allow a click or return key to activate the callback.
+ * This is good for accessibility since a return on the keyboard will have the
+ * same effect as a click, if the element has focus.
+ * @param {element} n Element to bind the action to
+ * @param {object} oData Data object to pass to the triggered function
+ * @param {function} fn Callback function for when the event is triggered
+ * @memberof DataTable#oApi
+ */
+ function _fnBindAction( n, oData, fn )
+ {
+ $(n)
+ .bind( 'click.DT', oData, function (e) {
+ n.blur(); // Remove focus outline for mouse users
+ fn(e);
+ } )
+ .bind( 'keypress.DT', oData, function (e){
+ if ( e.which === 13 ) {
+ e.preventDefault();
+ fn(e);
+ }
+ } )
+ .bind( 'selectstart.DT', function () {
+ /* Take the brutal approach to cancelling text selection */
+ return false;
+ } );
+ }
+
+
+ /**
+ * Register a callback function. Easily allows a callback function to be added to
+ * an array store of callback functions that can then all be called together.
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sStore Name of the array storage for the callbacks in oSettings
+ * @param {function} fn Function to be called back
+ * @param {string} sName Identifying name for the callback (i.e. a label)
+ * @memberof DataTable#oApi
+ */
+ function _fnCallbackReg( oSettings, sStore, fn, sName )
+ {
+ if ( fn )
+ {
+ oSettings[sStore].push( {
+ "fn": fn,
+ "sName": sName
+ } );
+ }
+ }
+
+
+ /**
+ * Fire callback functions and trigger events. Note that the loop over the
+ * callback array store is done backwards! Further note that you do not want to
+ * fire off triggers in time sensitive applications (for example cell creation)
+ * as its slow.
+ * @param {object} settings dataTables settings object
+ * @param {string} callbackArr Name of the array storage for the callbacks in
+ * oSettings
+ * @param {string} eventName Name of the jQuery custom event to trigger. If
+ * null no trigger is fired
+ * @param {array} args Array of arguments to pass to the callback function /
+ * trigger
+ * @memberof DataTable#oApi
+ */
+ function _fnCallbackFire( settings, callbackArr, eventName, args )
+ {
+ var ret = [];
+
+ if ( callbackArr ) {
+ ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) {
+ return val.fn.apply( settings.oInstance, args );
+ } );
+ }
+
+ if ( eventName !== null ) {
+ var e = $.Event( eventName+'.dt' );
+
+ $(settings.nTable).trigger( e, args );
+
+ ret.push( e.result );
+ }
+
+ return ret;
+ }
+
+
+ function _fnLengthOverflow ( settings )
+ {
+ var
+ start = settings._iDisplayStart,
+ end = settings.fnDisplayEnd(),
+ len = settings._iDisplayLength;
+
+ /* If we have space to show extra rows (backing up from the end point - then do so */
+ if ( start >= end )
+ {
+ start = end - len;
+ }
+
+ // Keep the start record on the current page
+ start -= (start % len);
+
+ if ( len === -1 || start < 0 )
+ {
+ start = 0;
+ }
+
+ settings._iDisplayStart = start;
+ }
+
+
+ function _fnRenderer( settings, type )
+ {
+ var renderer = settings.renderer;
+ var host = DataTable.ext.renderer[type];
+
+ if ( $.isPlainObject( renderer ) && renderer[type] ) {
+ // Specific renderer for this type. If available use it, otherwise use
+ // the default.
+ return host[renderer[type]] || host._;
+ }
+ else if ( typeof renderer === 'string' ) {
+ // Common renderer - if there is one available for this type use it,
+ // otherwise use the default
+ return host[renderer] || host._;
+ }
+
+ // Use the default
+ return host._;
+ }
+
+
+ /**
+ * Detect the data source being used for the table. Used to simplify the code
+ * a little (ajax) and to make it compress a little smaller.
+ *
+ * @param {object} settings dataTables settings object
+ * @returns {string} Data source
+ * @memberof DataTable#oApi
+ */
+ function _fnDataSource ( settings )
+ {
+ if ( settings.oFeatures.bServerSide ) {
+ return 'ssp';
+ }
+ else if ( settings.ajax || settings.sAjaxSource ) {
+ return 'ajax';
+ }
+ return 'dom';
+ }
+
+
+ DataTable = function( options )
+ {
+ /**
+ * Perform a jQuery selector action on the table's TR elements (from the tbody) and
+ * return the resulting jQuery object.
+ * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
+ * @param {object} [oOpts] Optional parameters for modifying the rows to be included
+ * @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
+ * criterion ("applied") or all TR elements (i.e. no filter).
+ * @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
+ * Can be either 'current', whereby the current sorting of the table is used, or
+ * 'original' whereby the original order the data was read into the table is used.
+ * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
+ * ("current") or not ("all"). If 'current' is given, then order is assumed to be
+ * 'current' and filter is 'applied', regardless of what they might be given as.
+ * @returns {object} jQuery object, filtered by the given selector.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Highlight every second row
+ * oTable.$('tr:odd').css('backgroundColor', 'blue');
+ * } );
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Filter to rows with 'Webkit' in them, add a background colour and then
+ * // remove the filter, thus highlighting the 'Webkit' rows only.
+ * oTable.fnFilter('Webkit');
+ * oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
+ * oTable.fnFilter('');
+ * } );
+ */
+ this.$ = function ( sSelector, oOpts )
+ {
+ return this.api(true).$( sSelector, oOpts );
+ };
+
+
+ /**
+ * Almost identical to $ in operation, but in this case returns the data for the matched
+ * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
+ * rather than any descendants, so the data can be obtained for the row/cell. If matching
+ * rows are found, the data returned is the original data array/object that was used to
+ * create the row (or a generated array if from a DOM source).
+ *
+ * This method is often useful in-combination with $ where both functions are given the
+ * same parameters and the array indexes will match identically.
+ * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
+ * @param {object} [oOpts] Optional parameters for modifying the rows to be included
+ * @param {string} [oOpts.filter=none] Select elements that meet the current filter
+ * criterion ("applied") or all elements (i.e. no filter).
+ * @param {string} [oOpts.order=current] Order of the data in the processed array.
+ * Can be either 'current', whereby the current sorting of the table is used, or
+ * 'original' whereby the original order the data was read into the table is used.
+ * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
+ * ("current") or not ("all"). If 'current' is given, then order is assumed to be
+ * 'current' and filter is 'applied', regardless of what they might be given as.
+ * @returns {array} Data for the matched elements. If any elements, as a result of the
+ * selector, were not TR, TD or TH elements in the DataTable, they will have a null
+ * entry in the array.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Get the data from the first row in the table
+ * var data = oTable._('tr:first');
+ *
+ * // Do something useful with the data
+ * alert( "First cell is: "+data[0] );
+ * } );
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Filter to 'Webkit' and get all data for
+ * oTable.fnFilter('Webkit');
+ * var data = oTable._('tr', {"search": "applied"});
+ *
+ * // Do something with the data
+ * alert( data.length+" rows matched the search" );
+ * } );
+ */
+ this._ = function ( sSelector, oOpts )
+ {
+ return this.api(true).rows( sSelector, oOpts ).data();
+ };
+
+
+ /**
+ * Create a DataTables Api instance, with the currently selected tables for
+ * the Api's context.
+ * @param {boolean} [traditional=false] Set the API instance's context to be
+ * only the table referred to by the `DataTable.ext.iApiIndex` option, as was
+ * used in the API presented by DataTables 1.9- (i.e. the traditional mode),
+ * or if all tables captured in the jQuery object should be used.
+ * @return {DataTables.Api}
+ */
+ this.api = function ( traditional )
+ {
+ return traditional ?
+ new _Api(
+ _fnSettingsFromNode( this[ _ext.iApiIndex ] )
+ ) :
+ new _Api( this );
+ };
+
+
+ /**
+ * Add a single new row or multiple rows of data to the table. Please note
+ * that this is suitable for client-side processing only - if you are using
+ * server-side processing (i.e. "bServerSide": true), then to add data, you
+ * must add it to the data source, i.e. the server-side, through an Ajax call.
+ * @param {array|object} data The data to be added to the table. This can be:
+ * <ul>
+ * <li>1D array of data - add a single row with the data provided</li>
+ * <li>2D array of arrays - add multiple rows in a single call</li>
+ * <li>object - data object when using <i>mData</i></li>
+ * <li>array of objects - multiple data objects when using <i>mData</i></li>
+ * </ul>
+ * @param {bool} [redraw=true] redraw the table or not
+ * @returns {array} An array of integers, representing the list of indexes in
+ * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
+ * the table.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * // Global var for counter
+ * var giCount = 2;
+ *
+ * $(document).ready(function() {
+ * $('#example').dataTable();
+ * } );
+ *
+ * function fnClickAddRow() {
+ * $('#example').dataTable().fnAddData( [
+ * giCount+".1",
+ * giCount+".2",
+ * giCount+".3",
+ * giCount+".4" ]
+ * );
+ *
+ * giCount++;
+ * }
+ */
+ this.fnAddData = function( data, redraw )
+ {
+ var api = this.api( true );
+
+ /* Check if we want to add multiple rows or not */
+ var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
+ api.rows.add( data ) :
+ api.row.add( data );
+
+ if ( redraw === undefined || redraw ) {
+ api.draw();
+ }
+
+ return rows.flatten().toArray();
+ };
+
+
+ /**
+ * This function will make DataTables recalculate the column sizes, based on the data
+ * contained in the table and the sizes applied to the columns (in the DOM, CSS or
+ * through the sWidth parameter). This can be useful when the width of the table's
+ * parent element changes (for example a window resize).
+ * @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable( {
+ * "sScrollY": "200px",
+ * "bPaginate": false
+ * } );
+ *
+ * $(window).bind('resize', function () {
+ * oTable.fnAdjustColumnSizing();
+ * } );
+ * } );
+ */
+ this.fnAdjustColumnSizing = function ( bRedraw )
+ {
+ var api = this.api( true ).columns.adjust();
+ var settings = api.settings()[0];
+ var scroll = settings.oScroll;
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw( false );
+ }
+ else if ( scroll.sX !== "" || scroll.sY !== "" ) {
+ /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
+ _fnScrollDraw( settings );
+ }
+ };
+
+
+ /**
+ * Quickly and simply clear a table
+ * @param {bool} [bRedraw=true] redraw the table or not
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
+ * oTable.fnClearTable();
+ * } );
+ */
+ this.fnClearTable = function( bRedraw )
+ {
+ var api = this.api( true ).clear();
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw();
+ }
+ };
+
+
+ /**
+ * The exact opposite of 'opening' a row, this function will close any rows which
+ * are currently 'open'.
+ * @param {node} nTr the table row to 'close'
+ * @returns {int} 0 on success, or 1 if failed (can't find the row)
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable;
+ *
+ * // 'open' an information row when a row is clicked on
+ * $('#example tbody tr').click( function () {
+ * if ( oTable.fnIsOpen(this) ) {
+ * oTable.fnClose( this );
+ * } else {
+ * oTable.fnOpen( this, "Temporary row opened", "info_row" );
+ * }
+ * } );
+ *
+ * oTable = $('#example').dataTable();
+ * } );
+ */
+ this.fnClose = function( nTr )
+ {
+ this.api( true ).row( nTr ).child.hide();
+ };
+
+
+ /**
+ * Remove a row for the table
+ * @param {mixed} target The index of the row from aoData to be deleted, or
+ * the TR element you want to delete
+ * @param {function|null} [callBack] Callback function
+ * @param {bool} [redraw=true] Redraw the table or not
+ * @returns {array} The row that was deleted
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Immediately remove the first row
+ * oTable.fnDeleteRow( 0 );
+ * } );
+ */
+ this.fnDeleteRow = function( target, callback, redraw )
+ {
+ var api = this.api( true );
+ var rows = api.rows( target );
+ var settings = rows.settings()[0];
+ var data = settings.aoData[ rows[0][0] ];
+
+ rows.remove();
+
+ if ( callback ) {
+ callback.call( this, settings, data );
+ }
+
+ if ( redraw === undefined || redraw ) {
+ api.draw();
+ }
+
+ return data;
+ };
+
+
+ /**
+ * Restore the table to it's original state in the DOM by removing all of DataTables
+ * enhancements, alterations to the DOM structure of the table and event listeners.
+ * @param {boolean} [remove=false] Completely remove the table from the DOM
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * // This example is fairly pointless in reality, but shows how fnDestroy can be used
+ * var oTable = $('#example').dataTable();
+ * oTable.fnDestroy();
+ * } );
+ */
+ this.fnDestroy = function ( remove )
+ {
+ this.api( true ).destroy( remove );
+ };
+
+
+ /**
+ * Redraw the table
+ * @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
+ * oTable.fnDraw();
+ * } );
+ */
+ this.fnDraw = function( complete )
+ {
+ // Note that this isn't an exact match to the old call to _fnDraw - it takes
+ // into account the new data, but can hold position.
+ this.api( true ).draw( complete );
+ };
+
+
+ /**
+ * Filter the input based on data
+ * @param {string} sInput String to filter the table on
+ * @param {int|null} [iColumn] Column to limit filtering to
+ * @param {bool} [bRegex=false] Treat as regular expression or not
+ * @param {bool} [bSmart=true] Perform smart filtering or not
+ * @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
+ * @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Sometime later - filter...
+ * oTable.fnFilter( 'test string' );
+ * } );
+ */
+ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
+ {
+ var api = this.api( true );
+
+ if ( iColumn === null || iColumn === undefined ) {
+ api.search( sInput, bRegex, bSmart, bCaseInsensitive );
+ }
+ else {
+ api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive );
+ }
+
+ api.draw();
+ };
+
+
+ /**
+ * Get the data for the whole table, an individual row or an individual cell based on the
+ * provided parameters.
+ * @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
+ * a TR node then the data source for the whole row will be returned. If given as a
+ * TD/TH cell node then iCol will be automatically calculated and the data for the
+ * cell returned. If given as an integer, then this is treated as the aoData internal
+ * data index for the row (see fnGetPosition) and the data for that row used.
+ * @param {int} [col] Optional column index that you want the data of.
+ * @returns {array|object|string} If mRow is undefined, then the data for all rows is
+ * returned. If mRow is defined, just data for that row, and is iCol is
+ * defined, only data for the designated cell is returned.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * // Row data
+ * $(document).ready(function() {
+ * oTable = $('#example').dataTable();
+ *
+ * oTable.$('tr').click( function () {
+ * var data = oTable.fnGetData( this );
+ * // ... do something with the array / object of data for the row
+ * } );
+ * } );
+ *
+ * @example
+ * // Individual cell data
+ * $(document).ready(function() {
+ * oTable = $('#example').dataTable();
+ *
+ * oTable.$('td').click( function () {
+ * var sData = oTable.fnGetData( this );
+ * alert( 'The cell clicked on had the value of '+sData );
+ * } );
+ * } );
+ */
+ this.fnGetData = function( src, col )
+ {
+ var api = this.api( true );
+
+ if ( src !== undefined ) {
+ var type = src.nodeName ? src.nodeName.toLowerCase() : '';
+
+ return col !== undefined || type == 'td' || type == 'th' ?
+ api.cell( src, col ).data() :
+ api.row( src ).data() || null;
+ }
+
+ return api.data().toArray();
+ };
+
+
+ /**
+ * Get an array of the TR nodes that are used in the table's body. Note that you will
+ * typically want to use the '$' API method in preference to this as it is more
+ * flexible.
+ * @param {int} [iRow] Optional row index for the TR element you want
+ * @returns {array|node} If iRow is undefined, returns an array of all TR elements
+ * in the table's body, or iRow is defined, just the TR element requested.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Get the nodes from the table
+ * var nNodes = oTable.fnGetNodes( );
+ * } );
+ */
+ this.fnGetNodes = function( iRow )
+ {
+ var api = this.api( true );
+
+ return iRow !== undefined ?
+ api.row( iRow ).node() :
+ api.rows().nodes().flatten().toArray();
+ };
+
+
+ /**
+ * Get the array indexes of a particular cell from it's DOM element
+ * and column index including hidden columns
+ * @param {node} node this can either be a TR, TD or TH in the table's body
+ * @returns {int} If nNode is given as a TR, then a single index is returned, or
+ * if given as a cell, an array of [row index, column index (visible),
+ * column index (all)] is given.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * $('#example tbody td').click( function () {
+ * // Get the position of the current data from the node
+ * var aPos = oTable.fnGetPosition( this );
+ *
+ * // Get the data array for this row
+ * var aData = oTable.fnGetData( aPos[0] );
+ *
+ * // Update the data array and return the value
+ * aData[ aPos[1] ] = 'clicked';
+ * this.innerHTML = 'clicked';
+ * } );
+ *
+ * // Init DataTables
+ * oTable = $('#example').dataTable();
+ * } );
+ */
+ this.fnGetPosition = function( node )
+ {
+ var api = this.api( true );
+ var nodeName = node.nodeName.toUpperCase();
+
+ if ( nodeName == 'TR' ) {
+ return api.row( node ).index();
+ }
+ else if ( nodeName == 'TD' || nodeName == 'TH' ) {
+ var cell = api.cell( node ).index();
+
+ return [
+ cell.row,
+ cell.columnVisible,
+ cell.column
+ ];
+ }
+ return null;
+ };
+
+
+ /**
+ * Check to see if a row is 'open' or not.
+ * @param {node} nTr the table row to check
+ * @returns {boolean} true if the row is currently open, false otherwise
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable;
+ *
+ * // 'open' an information row when a row is clicked on
+ * $('#example tbody tr').click( function () {
+ * if ( oTable.fnIsOpen(this) ) {
+ * oTable.fnClose( this );
+ * } else {
+ * oTable.fnOpen( this, "Temporary row opened", "info_row" );
+ * }
+ * } );
+ *
+ * oTable = $('#example').dataTable();
+ * } );
+ */
+ this.fnIsOpen = function( nTr )
+ {
+ return this.api( true ).row( nTr ).child.isShown();
+ };
+
+
+ /**
+ * This function will place a new row directly after a row which is currently
+ * on display on the page, with the HTML contents that is passed into the
+ * function. This can be used, for example, to ask for confirmation that a
+ * particular record should be deleted.
+ * @param {node} nTr The table row to 'open'
+ * @param {string|node|jQuery} mHtml The HTML to put into the row
+ * @param {string} sClass Class to give the new TD cell
+ * @returns {node} The row opened. Note that if the table row passed in as the
+ * first parameter, is not found in the table, this method will silently
+ * return.
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable;
+ *
+ * // 'open' an information row when a row is clicked on
+ * $('#example tbody tr').click( function () {
+ * if ( oTable.fnIsOpen(this) ) {
+ * oTable.fnClose( this );
+ * } else {
+ * oTable.fnOpen( this, "Temporary row opened", "info_row" );
+ * }
+ * } );
+ *
+ * oTable = $('#example').dataTable();
+ * } );
+ */
+ this.fnOpen = function( nTr, mHtml, sClass )
+ {
+ return this.api( true )
+ .row( nTr )
+ .child( mHtml, sClass )
+ .show()
+ .child()[0];
+ };
+
+
+ /**
+ * Change the pagination - provides the internal logic for pagination in a simple API
+ * function. With this function you can have a DataTables table go to the next,
+ * previous, first or last pages.
+ * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
+ * or page number to jump to (integer), note that page 0 is the first page.
+ * @param {bool} [bRedraw=true] Redraw the table or not
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ * oTable.fnPageChange( 'next' );
+ * } );
+ */
+ this.fnPageChange = function ( mAction, bRedraw )
+ {
+ var api = this.api( true ).page( mAction );
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw(false);
+ }
+ };
+
+
+ /**
+ * Show a particular column
+ * @param {int} iCol The column whose display should be changed
+ * @param {bool} bShow Show (true) or hide (false) the column
+ * @param {bool} [bRedraw=true] Redraw the table or not
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Hide the second column after initialisation
+ * oTable.fnSetColumnVis( 1, false );
+ * } );
+ */
+ this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
+ {
+ var api = this.api( true ).column( iCol ).visible( bShow );
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.columns.adjust().draw();
+ }
+ };
+
+
+ /**
+ * Get the settings for a particular table for external manipulation
+ * @returns {object} DataTables settings object. See
+ * {@link DataTable.models.oSettings}
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ * var oSettings = oTable.fnSettings();
+ *
+ * // Show an example parameter from the settings
+ * alert( oSettings._iDisplayStart );
+ * } );
+ */
+ this.fnSettings = function()
+ {
+ return _fnSettingsFromNode( this[_ext.iApiIndex] );
+ };
+
+
+ /**
+ * Sort the table by a particular column
+ * @param {int} iCol the data index to sort on. Note that this will not match the
+ * 'display index' if you have hidden data entries
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Sort immediately with columns 0 and 1
+ * oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
+ * } );
+ */
+ this.fnSort = function( aaSort )
+ {
+ this.api( true ).order( aaSort ).draw();
+ };
+
+
+ /**
+ * Attach a sort listener to an element for a given column
+ * @param {node} nNode the element to attach the sort listener to
+ * @param {int} iColumn the column that a click on this node will sort on
+ * @param {function} [fnCallback] callback function when sort is run
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ *
+ * // Sort on column 1, when 'sorter' is clicked on
+ * oTable.fnSortListener( document.getElementById('sorter'), 1 );
+ * } );
+ */
+ this.fnSortListener = function( nNode, iColumn, fnCallback )
+ {
+ this.api( true ).order.listener( nNode, iColumn, fnCallback );
+ };
+
+
+ /**
+ * Update a table cell or row - this method will accept either a single value to
+ * update the cell with, an array of values with one element for each column or
+ * an object in the same format as the original data source. The function is
+ * self-referencing in order to make the multi column updates easier.
+ * @param {object|array|string} mData Data to update the cell/row with
+ * @param {node|int} mRow TR element you want to update or the aoData index
+ * @param {int} [iColumn] The column to update, give as null or undefined to
+ * update a whole row.
+ * @param {bool} [bRedraw=true] Redraw the table or not
+ * @param {bool} [bAction=true] Perform pre-draw actions or not
+ * @returns {int} 0 on success, 1 on error
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ * oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
+ * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
+ * } );
+ */
+ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
+ {
+ var api = this.api( true );
+
+ if ( iColumn === undefined || iColumn === null ) {
+ api.row( mRow ).data( mData );
+ }
+ else {
+ api.cell( mRow, iColumn ).data( mData );
+ }
+
+ if ( bAction === undefined || bAction ) {
+ api.columns.adjust();
+ }
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw();
+ }
+ return 0;
+ };
+
+
+ /**
+ * Provide a common method for plug-ins to check the version of DataTables being used, in order
+ * to ensure compatibility.
+ * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
+ * formats "X" and "X.Y" are also acceptable.
+ * @returns {boolean} true if this version of DataTables is greater or equal to the required
+ * version, or false if this version of DataTales is not suitable
+ * @method
+ * @dtopt API
+ * @deprecated Since v1.10
+ *
+ * @example
+ * $(document).ready(function() {
+ * var oTable = $('#example').dataTable();
+ * alert( oTable.fnVersionCheck( '1.9.0' ) );
+ * } );
+ */
+ this.fnVersionCheck = _ext.fnVersionCheck;
+
+
+ var _that = this;
+ var emptyInit = options === undefined;
+ var len = this.length;
+
+ if ( emptyInit ) {
+ options = {};
+ }
+
+ this.oApi = this.internal = _ext.internal;
+
+ // Extend with old style plug-in API methods
+ for ( var fn in DataTable.ext.internal ) {
+ if ( fn ) {
+ this[fn] = _fnExternApiFunc(fn);
+ }
+ }
+
+ this.each(function() {
+ // For each initialisation we want to give it a clean initialisation
+ // object that can be bashed around
+ var o = {};
+ var oInit = len > 1 ? // optimisation for single table case
+ _fnExtend( o, options, true ) :
+ options;
+
+ /*global oInit,_that,emptyInit*/
+ var i=0, iLen, j, jLen, k, kLen;
+ var sId = this.getAttribute( 'id' );
+ var bInitHandedOff = false;
+ var defaults = DataTable.defaults;
+ var $this = $(this);
+
+
+ /* Sanity check */
+ if ( this.nodeName.toLowerCase() != 'table' )
+ {
+ _fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 );
+ return;
+ }
+
+ /* Backwards compatibility for the defaults */
+ _fnCompatOpts( defaults );
+ _fnCompatCols( defaults.column );
+
+ /* Convert the camel-case defaults to Hungarian */
+ _fnCamelToHungarian( defaults, defaults, true );
+ _fnCamelToHungarian( defaults.column, defaults.column, true );
+
+ /* Setting up the initialisation object */
+ _fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ) );
+
+
+
+ /* Check to see if we are re-initialising a table */
+ var allSettings = DataTable.settings;
+ for ( i=0, iLen=allSettings.length ; i<iLen ; i++ )
+ {
+ var s = allSettings[i];
+
+ /* Base check on table node */
+ if ( s.nTable == this || s.nTHead.parentNode == this || (s.nTFoot && s.nTFoot.parentNode == this) )
+ {
+ var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
+ var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
+
+ if ( emptyInit || bRetrieve )
+ {
+ return s.oInstance;
+ }
+ else if ( bDestroy )
+ {
+ s.oInstance.fnDestroy();
+ break;
+ }
+ else
+ {
+ _fnLog( s, 0, 'Cannot reinitialise DataTable', 3 );
+ return;
+ }
+ }
+
+ /* If the element we are initialising has the same ID as a table which was previously
+ * initialised, but the table nodes don't match (from before) then we destroy the old
+ * instance by simply deleting it. This is under the assumption that the table has been
+ * destroyed by other methods. Anyone using non-id selectors will need to do this manually
+ */
+ if ( s.sTableId == this.id )
+ {
+ allSettings.splice( i, 1 );
+ break;
+ }
+ }
+
+ /* Ensure the table has an ID - required for accessibility */
+ if ( sId === null || sId === "" )
+ {
+ sId = "DataTables_Table_"+(DataTable.ext._unique++);
+ this.id = sId;
+ }
+
+ /* Create the settings object for this table and set some of the default parameters */
+ var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
+ "sDestroyWidth": $this[0].style.width,
+ "sInstance": sId,
+ "sTableId": sId
+ } );
+ oSettings.nTable = this;
+ oSettings.oApi = _that.internal;
+ oSettings.oInit = oInit;
+
+ allSettings.push( oSettings );
+
+ // Need to add the instance after the instance after the settings object has been added
+ // to the settings array, so we can self reference the table instance if more than one
+ oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable();
+
+ // Backwards compatibility, before we apply all the defaults
+ _fnCompatOpts( oInit );
+
+ if ( oInit.oLanguage )
+ {
+ _fnLanguageCompat( oInit.oLanguage );
+ }
+
+ // If the length menu is given, but the init display length is not, use the length menu
+ if ( oInit.aLengthMenu && ! oInit.iDisplayLength )
+ {
+ oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ?
+ oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
+ }
+
+ // Apply the defaults and init options to make a single init object will all
+ // options defined from defaults and instance options.
+ oInit = _fnExtend( $.extend( true, {}, defaults ), oInit );
+
+
+ // Map the initialisation options onto the settings object
+ _fnMap( oSettings.oFeatures, oInit, [
+ "bPaginate",
+ "bLengthChange",
+ "bFilter",
+ "bSort",
+ "bSortMulti",
+ "bInfo",
+ "bProcessing",
+ "bAutoWidth",
+ "bSortClasses",
+ "bServerSide",
+ "bDeferRender"
+ ] );
+ _fnMap( oSettings, oInit, [
+ "asStripeClasses",
+ "ajax",
+ "fnServerData",
+ "fnFormatNumber",
+ "sServerMethod",
+ "aaSorting",
+ "aaSortingFixed",
+ "aLengthMenu",
+ "sPaginationType",
+ "sAjaxSource",
+ "sAjaxDataProp",
+ "iStateDuration",
+ "sDom",
+ "bSortCellsTop",
+ "iTabIndex",
+ "fnStateLoadCallback",
+ "fnStateSaveCallback",
+ "renderer",
+ "searchDelay",
+ "rowId",
+ [ "iCookieDuration", "iStateDuration" ], // backwards compat
+ [ "oSearch", "oPreviousSearch" ],
+ [ "aoSearchCols", "aoPreSearchCols" ],
+ [ "iDisplayLength", "_iDisplayLength" ],
+ [ "bJQueryUI", "bJUI" ]
+ ] );
+ _fnMap( oSettings.oScroll, oInit, [
+ [ "sScrollX", "sX" ],
+ [ "sScrollXInner", "sXInner" ],
+ [ "sScrollY", "sY" ],
+ [ "bScrollCollapse", "bCollapse" ]
+ ] );
+ _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
+
+ /* Callback functions which are array driven */
+ _fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' );
+ _fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' );
+ _fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' );
+ _fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' );
+ _fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' );
+ _fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' );
+ _fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' );
+ _fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' );
+ _fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' );
+ _fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' );
+ _fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' );
+
+ oSettings.rowIdFn = _fnGetObjectDataFn( oInit.rowId );
+
+ /* Browser support detection */
+ _fnBrowserDetect( oSettings );
+
+ var oClasses = oSettings.oClasses;
+
+ // @todo Remove in 1.11
+ if ( oInit.bJQueryUI )
+ {
+ /* Use the JUI classes object for display. You could clone the oStdClasses object if
+ * you want to have multiple tables with multiple independent classes
+ */
+ $.extend( oClasses, DataTable.ext.oJUIClasses, oInit.oClasses );
+
+ if ( oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip" )
+ {
+ /* Set the DOM to use a layout suitable for jQuery UI's theming */
+ oSettings.sDom = '<"H"lfr>t<"F"ip>';
+ }
+
+ if ( ! oSettings.renderer ) {
+ oSettings.renderer = 'jqueryui';
+ }
+ else if ( $.isPlainObject( oSettings.renderer ) && ! oSettings.renderer.header ) {
+ oSettings.renderer.header = 'jqueryui';
+ }
+ }
+ else
+ {
+ $.extend( oClasses, DataTable.ext.classes, oInit.oClasses );
+ }
+ $this.addClass( oClasses.sTable );
+
+
+ if ( oSettings.iInitDisplayStart === undefined )
+ {
+ /* Display start point, taking into account the save saving */
+ oSettings.iInitDisplayStart = oInit.iDisplayStart;
+ oSettings._iDisplayStart = oInit.iDisplayStart;
+ }
+
+ if ( oInit.iDeferLoading !== null )
+ {
+ oSettings.bDeferLoading = true;
+ var tmp = $.isArray( oInit.iDeferLoading );
+ oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
+ oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
+ }
+
+ /* Language definitions */
+ var oLanguage = oSettings.oLanguage;
+ $.extend( true, oLanguage, oInit.oLanguage );
+
+ if ( oLanguage.sUrl !== "" )
+ {
+ /* Get the language definitions from a file - because this Ajax call makes the language
+ * get async to the remainder of this function we use bInitHandedOff to indicate that
+ * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
+ */
+ $.ajax( {
+ dataType: 'json',
+ url: oLanguage.sUrl,
+ success: function ( json ) {
+ _fnLanguageCompat( json );
+ _fnCamelToHungarian( defaults.oLanguage, json );
+ $.extend( true, oLanguage, json );
+ _fnInitialise( oSettings );
+ },
+ error: function () {
+ // Error occurred loading language file, continue on as best we can
+ _fnInitialise( oSettings );
+ }
+ } );
+ bInitHandedOff = true;
+ }
+
+ /*
+ * Stripes
+ */
+ if ( oInit.asStripeClasses === null )
+ {
+ oSettings.asStripeClasses =[
+ oClasses.sStripeOdd,
+ oClasses.sStripeEven
+ ];
+ }
+
+ /* Remove row stripe classes if they are already on the table row */
+ var stripeClasses = oSettings.asStripeClasses;
+ var rowOne = $this.children('tbody').find('tr').eq(0);
+ if ( $.inArray( true, $.map( stripeClasses, function(el, i) {
+ return rowOne.hasClass(el);
+ } ) ) !== -1 ) {
+ $('tbody tr', this).removeClass( stripeClasses.join(' ') );
+ oSettings.asDestroyStripes = stripeClasses.slice();
+ }
+
+ /*
+ * Columns
+ * See if we should load columns automatically or use defined ones
+ */
+ var anThs = [];
+ var aoColumnsInit;
+ var nThead = this.getElementsByTagName('thead');
+ if ( nThead.length !== 0 )
+ {
+ _fnDetectHeader( oSettings.aoHeader, nThead[0] );
+ anThs = _fnGetUniqueThs( oSettings );
+ }
+
+ /* If not given a column array, generate one with nulls */
+ if ( oInit.aoColumns === null )
+ {
+ aoColumnsInit = [];
+ for ( i=0, iLen=anThs.length ; i<iLen ; i++ )
+ {
+ aoColumnsInit.push( null );
+ }
+ }
+ else
+ {
+ aoColumnsInit = oInit.aoColumns;
+ }
+
+ /* Add the columns */
+ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
+ {
+ _fnAddColumn( oSettings, anThs ? anThs[i] : null );
+ }
+
+ /* Apply the column definitions */
+ _fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
+ _fnColumnOptions( oSettings, iCol, oDef );
+ } );
+
+ /* HTML5 attribute detection - build an mData object automatically if the
+ * attributes are found
+ */
+ if ( rowOne.length ) {
+ var a = function ( cell, name ) {
+ return cell.getAttribute( 'data-'+name ) !== null ? name : null;
+ };
+
+ $( rowOne[0] ).children('th, td').each( function (i, cell) {
+ var col = oSettings.aoColumns[i];
+
+ if ( col.mData === i ) {
+ var sort = a( cell, 'sort' ) || a( cell, 'order' );
+ var filter = a( cell, 'filter' ) || a( cell, 'search' );
+
+ if ( sort !== null || filter !== null ) {
+ col.mData = {
+ _: i+'.display',
+ sort: sort !== null ? i+'.@data-'+sort : undefined,
+ type: sort !== null ? i+'.@data-'+sort : undefined,
+ filter: filter !== null ? i+'.@data-'+filter : undefined
+ };
+
+ _fnColumnOptions( oSettings, i );
+ }
+ }
+ } );
+ }
+
+ var features = oSettings.oFeatures;
+
+ /* Must be done after everything which can be overridden by the state saving! */
+ if ( oInit.bStateSave )
+ {
+ features.bStateSave = true;
+ _fnLoadState( oSettings, oInit );
+ _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
+ }
+
+
+ /*
+ * Sorting
+ * @todo For modularisation (1.11) this needs to do into a sort start up handler
+ */
+
+ // If aaSorting is not defined, then we use the first indicator in asSorting
+ // in case that has been altered, so the default sort reflects that option
+ if ( oInit.aaSorting === undefined )
+ {
+ var sorting = oSettings.aaSorting;
+ for ( i=0, iLen=sorting.length ; i<iLen ; i++ )
+ {
+ sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0];
+ }
+ }
+
+ /* Do a first pass on the sorting classes (allows any size changes to be taken into
+ * account, and also will apply sorting disabled classes if disabled
+ */
+ _fnSortingClasses( oSettings );
+
+ if ( features.bSort )
+ {
+ _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
+ if ( oSettings.bSorted ) {
+ var aSort = _fnSortFlatten( oSettings );
+ var sortedColumns = {};
+
+ $.each( aSort, function (i, val) {
+ sortedColumns[ val.src ] = val.dir;
+ } );
+
+ _fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] );
+ _fnSortAria( oSettings );
+ }
+ } );
+ }
+
+ _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
+ if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) {
+ _fnSortingClasses( oSettings );
+ }
+ }, 'sc' );
+
+
+ /*
+ * Final init
+ * Cache the header, body and footer as required, creating them if needed
+ */
+
+ // Work around for Webkit bug 83867 - store the caption-side before removing from doc
+ var captions = $this.children('caption').each( function () {
+ this._captionSide = $this.css('caption-side');
+ } );
+
+ var thead = $this.children('thead');
+ if ( thead.length === 0 )
+ {
+ thead = $('<thead/>').appendTo(this);
+ }
+ oSettings.nTHead = thead[0];
+
+ var tbody = $this.children('tbody');
+ if ( tbody.length === 0 )
+ {
+ tbody = $('<tbody/>').appendTo(this);
+ }
+ oSettings.nTBody = tbody[0];
+
+ var tfoot = $this.children('tfoot');
+ if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") )
+ {
+ // If we are a scrolling table, and no footer has been given, then we need to create
+ // a tfoot element for the caption element to be appended to
+ tfoot = $('<tfoot/>').appendTo(this);
+ }
+
+ if ( tfoot.length === 0 || tfoot.children().length === 0 ) {
+ $this.addClass( oClasses.sNoFooter );
+ }
+ else if ( tfoot.length > 0 ) {
+ oSettings.nTFoot = tfoot[0];
+ _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
+ }
+
+ /* Check if there is data passing into the constructor */
+ if ( oInit.aaData )
+ {
+ for ( i=0 ; i<oInit.aaData.length ; i++ )
+ {
+ _fnAddData( oSettings, oInit.aaData[ i ] );
+ }
+ }
+ else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' )
+ {
+ /* Grab the data from the page - only do this when deferred loading or no Ajax
+ * source since there is no point in reading the DOM data if we are then going
+ * to replace it with Ajax data
+ */
+ _fnAddTr( oSettings, $(oSettings.nTBody).children('tr') );
+ }
+
+ /* Copy the data index array */
+ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
+
+ /* Initialisation complete - table can be drawn */
+ oSettings.bInitialised = true;
+
+ /* Check if we need to initialise the table (it might not have been handed off to the
+ * language processor)
+ */
+ if ( bInitHandedOff === false )
+ {
+ _fnInitialise( oSettings );
+ }
+ } );
+ _that = null;
+ return this;
+ };
+
+
+
+ /**
+ * Computed structure of the DataTables API, defined by the options passed to
+ * `DataTable.Api.register()` when building the API.
+ *
+ * The structure is built in order to speed creation and extension of the Api
+ * objects since the extensions are effectively pre-parsed.
+ *
+ * The array is an array of objects with the following structure, where this
+ * base array represents the Api prototype base:
+ *
+ * [
+ * {
+ * name: 'data' -- string - Property name
+ * val: function () {}, -- function - Api method (or undefined if just an object
+ * methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
+ * propExt: [ ... ] -- array - Array of Api object definitions to extend the property
+ * },
+ * {
+ * name: 'row'
+ * val: {},
+ * methodExt: [ ... ],
+ * propExt: [
+ * {
+ * name: 'data'
+ * val: function () {},
+ * methodExt: [ ... ],
+ * propExt: [ ... ]
+ * },
+ * ...
+ * ]
+ * }
+ * ]
+ *
+ * @type {Array}
+ * @ignore
+ */
+ var __apiStruct = [];
+
+
+ /**
+ * `Array.prototype` reference.
+ *
+ * @type object
+ * @ignore
+ */
+ var __arrayProto = Array.prototype;
+
+
+ /**
+ * Abstraction for `context` parameter of the `Api` constructor to allow it to
+ * take several different forms for ease of use.
+ *
+ * Each of the input parameter types will be converted to a DataTables settings
+ * object where possible.
+ *
+ * @param {string|node|jQuery|object} mixed DataTable identifier. Can be one
+ * of:
+ *
+ * * `string` - jQuery selector. Any DataTables' matching the given selector
+ * with be found and used.
+ * * `node` - `TABLE` node which has already been formed into a DataTable.
+ * * `jQuery` - A jQuery object of `TABLE` nodes.
+ * * `object` - DataTables settings object
+ * * `DataTables.Api` - API instance
+ * @return {array|null} Matching DataTables settings objects. `null` or
+ * `undefined` is returned if no matching DataTable is found.
+ * @ignore
+ */
+ var _toSettings = function ( mixed )
+ {
+ var idx, jq;
+ var settings = DataTable.settings;
+ var tables = $.map( settings, function (el, i) {
+ return el.nTable;
+ } );
+
+ if ( ! mixed ) {
+ return [];
+ }
+ else if ( mixed.nTable && mixed.oApi ) {
+ // DataTables settings object
+ return [ mixed ];
+ }
+ else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
+ // Table node
+ idx = $.inArray( mixed, tables );
+ return idx !== -1 ? [ settings[idx] ] : null;
+ }
+ else if ( mixed && typeof mixed.settings === 'function' ) {
+ return mixed.settings().toArray();
+ }
+ else if ( typeof mixed === 'string' ) {
+ // jQuery selector
+ jq = $(mixed);
+ }
+ else if ( mixed instanceof $ ) {
+ // jQuery object (also DataTables instance)
+ jq = mixed;
+ }
+
+ if ( jq ) {
+ return jq.map( function(i) {
+ idx = $.inArray( this, tables );
+ return idx !== -1 ? settings[idx] : null;
+ } ).toArray();
+ }
+ };
+
+
+ /**
+ * DataTables API class - used to control and interface with one or more
+ * DataTables enhanced tables.
+ *
+ * The API class is heavily based on jQuery, presenting a chainable interface
+ * that you can use to interact with tables. Each instance of the API class has
+ * a "context" - i.e. the tables that it will operate on. This could be a single
+ * table, all tables on a page or a sub-set thereof.
+ *
+ * Additionally the API is designed to allow you to easily work with the data in
+ * the tables, retrieving and manipulating it as required. This is done by
+ * presenting the API class as an array like interface. The contents of the
+ * array depend upon the actions requested by each method (for example
+ * `rows().nodes()` will return an array of nodes, while `rows().data()` will
+ * return an array of objects or arrays depending upon your table's
+ * configuration). The API object has a number of array like methods (`push`,
+ * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
+ * `unique` etc) to assist your working with the data held in a table.
+ *
+ * Most methods (those which return an Api instance) are chainable, which means
+ * the return from a method call also has all of the methods available that the
+ * top level object had. For example, these two calls are equivalent:
+ *
+ * // Not chained
+ * api.row.add( {...} );
+ * api.draw();
+ *
+ * // Chained
+ * api.row.add( {...} ).draw();
+ *
+ * @class DataTable.Api
+ * @param {array|object|string|jQuery} context DataTable identifier. This is
+ * used to define which DataTables enhanced tables this API will operate on.
+ * Can be one of:
+ *
+ * * `string` - jQuery selector. Any DataTables' matching the given selector
+ * with be found and used.
+ * * `node` - `TABLE` node which has already been formed into a DataTable.
+ * * `jQuery` - A jQuery object of `TABLE` nodes.
+ * * `object` - DataTables settings object
+ * @param {array} [data] Data to initialise the Api instance with.
+ *
+ * @example
+ * // Direct initialisation during DataTables construction
+ * var api = $('#example').DataTable();
+ *
+ * @example
+ * // Initialisation using a DataTables jQuery object
+ * var api = $('#example').dataTable().api();
+ *
+ * @example
+ * // Initialisation as a constructor
+ * var api = new $.fn.DataTable.Api( 'table.dataTable' );
+ */
+ _Api = function ( context, data )
+ {
+ if ( ! (this instanceof _Api) ) {
+ return new _Api( context, data );
+ }
+
+ var settings = [];
+ var ctxSettings = function ( o ) {
+ var a = _toSettings( o );
+ if ( a ) {
+ settings = settings.concat( a );
+ }
+ };
+
+ if ( $.isArray( context ) ) {
+ for ( var i=0, ien=context.length ; i<ien ; i++ ) {
+ ctxSettings( context[i] );
+ }
+ }
+ else {
+ ctxSettings( context );
+ }
+
+ // Remove duplicates
+ this.context = _unique( settings );
+
+ // Initial data
+ if ( data ) {
+ $.merge( this, data );
+ }
+
+ // selector
+ this.selector = {
+ rows: null,
+ cols: null,
+ opts: null
+ };
+
+ _Api.extend( this, this, __apiStruct );
+ };
+
+ DataTable.Api = _Api;
+
+ // Don't destroy the existing prototype, just extend it. Required for jQuery 2's
+ // isPlainObject.
+ $.extend( _Api.prototype, {
+ any: function ()
+ {
+ return this.count() !== 0;
+ },
+
+
+ concat: __arrayProto.concat,
+
+
+ context: [], // array of table settings objects
+
+
+ count: function ()
+ {
+ return this.flatten().length;
+ },
+
+
+ each: function ( fn )
+ {
+ for ( var i=0, ien=this.length ; i<ien; i++ ) {
+ fn.call( this, this[i], i, this );
+ }
+
+ return this;
+ },
+
+
+ eq: function ( idx )
+ {
+ var ctx = this.context;
+
+ return ctx.length > idx ?
+ new _Api( ctx[idx], this[idx] ) :
+ null;
+ },
+
+
+ filter: function ( fn )
+ {
+ var a = [];
+
+ if ( __arrayProto.filter ) {
+ a = __arrayProto.filter.call( this, fn, this );
+ }
+ else {
+ // Compatibility for browsers without EMCA-252-5 (JS 1.6)
+ for ( var i=0, ien=this.length ; i<ien ; i++ ) {
+ if ( fn.call( this, this[i], i, this ) ) {
+ a.push( this[i] );
+ }
+ }
+ }
+
+ return new _Api( this.context, a );
+ },
+
+
+ flatten: function ()
+ {
+ var a = [];
+ return new _Api( this.context, a.concat.apply( a, this.toArray() ) );
+ },
+
+
+ join: __arrayProto.join,
+
+
+ indexOf: __arrayProto.indexOf || function (obj, start)
+ {
+ for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) {
+ if ( this[i] === obj ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ iterator: function ( flatten, type, fn, alwaysNew ) {
+ var
+ a = [], ret,
+ i, ien, j, jen,
+ context = this.context,
+ rows, items, item,
+ selector = this.selector;
+
+ // Argument shifting
+ if ( typeof flatten === 'string' ) {
+ alwaysNew = fn;
+ fn = type;
+ type = flatten;
+ flatten = false;
+ }
+
+ for ( i=0, ien=context.length ; i<ien ; i++ ) {
+ var apiInst = new _Api( context[i] );
+
+ if ( type === 'table' ) {
+ ret = fn.call( apiInst, context[i], i );
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ else if ( type === 'columns' || type === 'rows' ) {
+ // this has same length as context - one entry for each table
+ ret = fn.call( apiInst, context[i], this[i], i );
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
+ // columns and rows share the same structure.
+ // 'this' is an array of column indexes for each context
+ items = this[i];
+
+ if ( type === 'column-rows' ) {
+ rows = _selector_row_indexes( context[i], selector.opts );
+ }
+
+ for ( j=0, jen=items.length ; j<jen ; j++ ) {
+ item = items[j];
+
+ if ( type === 'cell' ) {
+ ret = fn.call( apiInst, context[i], item.row, item.column, i, j );
+ }
+ else {
+ ret = fn.call( apiInst, context[i], item, i, j, rows );
+ }
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ }
+ }
+
+ if ( a.length || alwaysNew ) {
+ var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
+ var apiSelector = api.selector;
+ apiSelector.rows = selector.rows;
+ apiSelector.cols = selector.cols;
+ apiSelector.opts = selector.opts;
+ return api;
+ }
+ return this;
+ },
+
+
+ lastIndexOf: __arrayProto.lastIndexOf || function (obj, start)
+ {
+ // Bit cheeky...
+ return this.indexOf.apply( this.toArray.reverse(), arguments );
+ },
+
+
+ length: 0,
+
+
+ map: function ( fn )
+ {
+ var a = [];
+
+ if ( __arrayProto.map ) {
+ a = __arrayProto.map.call( this, fn, this );
+ }
+ else {
+ // Compatibility for browsers without EMCA-252-5 (JS 1.6)
+ for ( var i=0, ien=this.length ; i<ien ; i++ ) {
+ a.push( fn.call( this, this[i], i ) );
+ }
+ }
+
+ return new _Api( this.context, a );
+ },
+
+
+ pluck: function ( prop )
+ {
+ return this.map( function ( el ) {
+ return el[ prop ];
+ } );
+ },
+
+ pop: __arrayProto.pop,
+
+
+ push: __arrayProto.push,
+
+
+ // Does not return an API instance
+ reduce: __arrayProto.reduce || function ( fn, init )
+ {
+ return _fnReduce( this, fn, init, 0, this.length, 1 );
+ },
+
+
+ reduceRight: __arrayProto.reduceRight || function ( fn, init )
+ {
+ return _fnReduce( this, fn, init, this.length-1, -1, -1 );
+ },
+
+
+ reverse: __arrayProto.reverse,
+
+
+ // Object with rows, columns and opts
+ selector: null,
+
+
+ shift: __arrayProto.shift,
+
+
+ sort: __arrayProto.sort, // ? name - order?
+
+
+ splice: __arrayProto.splice,
+
+
+ toArray: function ()
+ {
+ return __arrayProto.slice.call( this );
+ },
+
+
+ to$: function ()
+ {
+ return $( this );
+ },
+
+
+ toJQuery: function ()
+ {
+ return $( this );
+ },
+
+
+ unique: function ()
+ {
+ return new _Api( this.context, _unique(this) );
+ },
+
+
+ unshift: __arrayProto.unshift
+ } );
+
+
+ _Api.extend = function ( scope, obj, ext )
+ {
+ // Only extend API instances and static properties of the API
+ if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) {
+ return;
+ }
+
+ var
+ i, ien,
+ j, jen,
+ struct, inner,
+ methodScoping = function ( scope, fn, struc ) {
+ return function () {
+ var ret = fn.apply( scope, arguments );
+
+ // Method extension
+ _Api.extend( ret, ret, struc.methodExt );
+ return ret;
+ };
+ };
+
+ for ( i=0, ien=ext.length ; i<ien ; i++ ) {
+ struct = ext[i];
+
+ // Value
+ obj[ struct.name ] = typeof struct.val === 'function' ?
+ methodScoping( scope, struct.val, struct ) :
+ $.isPlainObject( struct.val ) ?
+ {} :
+ struct.val;
+
+ obj[ struct.name ].__dt_wrapper = true;
+
+ // Property extension
+ _Api.extend( scope, obj[ struct.name ], struct.propExt );
+ }
+ };
+
+
+ // @todo - Is there need for an augment function?
+ // _Api.augment = function ( inst, name )
+ // {
+ // // Find src object in the structure from the name
+ // var parts = name.split('.');
+
+ // _Api.extend( inst, obj );
+ // };
+
+
+ // [
+ // {
+ // name: 'data' -- string - Property name
+ // val: function () {}, -- function - Api method (or undefined if just an object
+ // methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
+ // propExt: [ ... ] -- array - Array of Api object definitions to extend the property
+ // },
+ // {
+ // name: 'row'
+ // val: {},
+ // methodExt: [ ... ],
+ // propExt: [
+ // {
+ // name: 'data'
+ // val: function () {},
+ // methodExt: [ ... ],
+ // propExt: [ ... ]
+ // },
+ // ...
+ // ]
+ // }
+ // ]
+
+ _Api.register = _api_register = function ( name, val )
+ {
+ if ( $.isArray( name ) ) {
+ for ( var j=0, jen=name.length ; j<jen ; j++ ) {
+ _Api.register( name[j], val );
+ }
+ return;
+ }
+
+ var
+ i, ien,
+ heir = name.split('.'),
+ struct = __apiStruct,
+ key, method;
+
+ var find = function ( src, name ) {
+ for ( var i=0, ien=src.length ; i<ien ; i++ ) {
+ if ( src[i].name === name ) {
+ return src[i];
+ }
+ }
+ return null;
+ };
+
+ for ( i=0, ien=heir.length ; i<ien ; i++ ) {
+ method = heir[i].indexOf('()') !== -1;
+ key = method ?
+ heir[i].replace('()', '') :
+ heir[i];
+
+ var src = find( struct, key );
+ if ( ! src ) {
+ src = {
+ name: key,
+ val: {},
+ methodExt: [],
+ propExt: []
+ };
+ struct.push( src );
+ }
+
+ if ( i === ien-1 ) {
+ src.val = val;
+ }
+ else {
+ struct = method ?
+ src.methodExt :
+ src.propExt;
+ }
+ }
+ };
+
+
+ _Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) {
+ _Api.register( pluralName, val );
+
+ _Api.register( singularName, function () {
+ var ret = val.apply( this, arguments );
+
+ if ( ret === this ) {
+ // Returned item is the API instance that was passed in, return it
+ return this;
+ }
+ else if ( ret instanceof _Api ) {
+ // New API instance returned, want the value from the first item
+ // in the returned array for the singular result.
+ return ret.length ?
+ $.isArray( ret[0] ) ?
+ new _Api( ret.context, ret[0] ) : // Array results are 'enhanced'
+ ret[0] :
+ undefined;
+ }
+
+ // Non-API return - just fire it back
+ return ret;
+ } );
+ };
+
+
+ /**
+ * Selector for HTML tables. Apply the given selector to the give array of
+ * DataTables settings objects.
+ *
+ * @param {string|integer} [selector] jQuery selector string or integer
+ * @param {array} Array of DataTables settings objects to be filtered
+ * @return {array}
+ * @ignore
+ */
+ var __table_selector = function ( selector, a )
+ {
+ // Integer is used to pick out a table by index
+ if ( typeof selector === 'number' ) {
+ return [ a[ selector ] ];
+ }
+
+ // Perform a jQuery selector on the table nodes
+ var nodes = $.map( a, function (el, i) {
+ return el.nTable;
+ } );
+
+ return $(nodes)
+ .filter( selector )
+ .map( function (i) {
+ // Need to translate back from the table node to the settings
+ var idx = $.inArray( this, nodes );
+ return a[ idx ];
+ } )
+ .toArray();
+ };
+
+
+
+ /**
+ * Context selector for the API's context (i.e. the tables the API instance
+ * refers to.
+ *
+ * @name DataTable.Api#tables
+ * @param {string|integer} [selector] Selector to pick which tables the iterator
+ * should operate on. If not given, all tables in the current context are
+ * used. This can be given as a jQuery selector (for example `':gt(0)'`) to
+ * select multiple tables or as an integer to select a single table.
+ * @returns {DataTable.Api} Returns a new API instance if a selector is given.
+ */
+ _api_register( 'tables()', function ( selector ) {
+ // A new instance is created if there was a selector specified
+ return selector ?
+ new _Api( __table_selector( selector, this.context ) ) :
+ this;
+ } );
+
+
+ _api_register( 'table()', function ( selector ) {
+ var tables = this.tables( selector );
+ var ctx = tables.context;
+
+ // Truncate to the first matched table
+ return ctx.length ?
+ new _Api( ctx[0] ) :
+ tables;
+ } );
+
+
+ _api_registerPlural( 'tables().nodes()', 'table().node()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTable;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().body()', 'table().body()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTBody;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().header()', 'table().header()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTHead;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().footer()', 'table().footer()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTFoot;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().containers()', 'table().container()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTableWrapper;
+ }, 1 );
+ } );
+
+
+
+ /**
+ * Redraw the tables in the current context.
+ */
+ _api_register( 'draw()', function ( paging ) {
+ return this.iterator( 'table', function ( settings ) {
+ if ( paging === 'page' ) {
+ _fnDraw( settings );
+ }
+ else {
+ if ( typeof paging === 'string' ) {
+ paging = paging === 'full-hold' ?
+ false :
+ true;
+ }
+
+ _fnReDraw( settings, paging===false );
+ }
+ } );
+ } );
+
+
+
+ /**
+ * Get the current page index.
+ *
+ * @return {integer} Current page index (zero based)
+ *//**
+ * Set the current page.
+ *
+ * Note that if you attempt to show a page which does not exist, DataTables will
+ * not throw an error, but rather reset the paging.
+ *
+ * @param {integer|string} action The paging action to take. This can be one of:
+ * * `integer` - The page index to jump to
+ * * `string` - An action to take:
+ * * `first` - Jump to first page.
+ * * `next` - Jump to the next page
+ * * `previous` - Jump to previous page
+ * * `last` - Jump to the last page.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'page()', function ( action ) {
+ if ( action === undefined ) {
+ return this.page.info().page; // not an expensive call
+ }
+
+ // else, have an action to take on all tables
+ return this.iterator( 'table', function ( settings ) {
+ _fnPageChange( settings, action );
+ } );
+ } );
+
+
+ /**
+ * Paging information for the first table in the current context.
+ *
+ * If you require paging information for another table, use the `table()` method
+ * with a suitable selector.
+ *
+ * @return {object} Object with the following properties set:
+ * * `page` - Current page index (zero based - i.e. the first page is `0`)
+ * * `pages` - Total number of pages
+ * * `start` - Display index for the first record shown on the current page
+ * * `end` - Display index for the last record shown on the current page
+ * * `length` - Display length (number of records). Note that generally `start
+ * + length = end`, but this is not always true, for example if there are
+ * only 2 records to show on the final page, with a length of 10.
+ * * `recordsTotal` - Full data set length
+ * * `recordsDisplay` - Data set length once the current filtering criterion
+ * are applied.
+ */
+ _api_register( 'page.info()', function ( action ) {
+ if ( this.context.length === 0 ) {
+ return undefined;
+ }
+
+ var
+ settings = this.context[0],
+ start = settings._iDisplayStart,
+ len = settings.oFeatures.bPaginate ? settings._iDisplayLength : -1,
+ visRecords = settings.fnRecordsDisplay(),
+ all = len === -1;
+
+ return {
+ "page": all ? 0 : Math.floor( start / len ),
+ "pages": all ? 1 : Math.ceil( visRecords / len ),
+ "start": start,
+ "end": settings.fnDisplayEnd(),
+ "length": len,
+ "recordsTotal": settings.fnRecordsTotal(),
+ "recordsDisplay": visRecords,
+ "serverSide": _fnDataSource( settings ) === 'ssp'
+ };
+ } );
+
+
+ /**
+ * Get the current page length.
+ *
+ * @return {integer} Current page length. Note `-1` indicates that all records
+ * are to be shown.
+ *//**
+ * Set the current page length.
+ *
+ * @param {integer} Page length to set. Use `-1` to show all records.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'page.len()', function ( len ) {
+ // Note that we can't call this function 'length()' because `length`
+ // is a Javascript property of functions which defines how many arguments
+ // the function expects.
+ if ( len === undefined ) {
+ return this.context.length !== 0 ?
+ this.context[0]._iDisplayLength :
+ undefined;
+ }
+
+ // else, set the page length
+ return this.iterator( 'table', function ( settings ) {
+ _fnLengthChange( settings, len );
+ } );
+ } );
+
+
+
+ var __reload = function ( settings, holdPosition, callback ) {
+ // Use the draw event to trigger a callback
+ if ( callback ) {
+ var api = new _Api( settings );
+
+ api.one( 'draw', function () {
+ callback( api.ajax.json() );
+ } );
+ }
+
+ if ( _fnDataSource( settings ) == 'ssp' ) {
+ _fnReDraw( settings, holdPosition );
+ }
+ else {
+ _fnProcessingDisplay( settings, true );
+
+ // Cancel an existing request
+ var xhr = settings.jqXHR;
+ if ( xhr && xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+
+ // Trigger xhr
+ _fnBuildAjax( settings, [], function( json ) {
+ _fnClearTable( settings );
+
+ var data = _fnAjaxDataSrc( settings, json );
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ _fnAddData( settings, data[i] );
+ }
+
+ _fnReDraw( settings, holdPosition );
+ _fnProcessingDisplay( settings, false );
+ } );
+ }
+ };
+
+
+ /**
+ * Get the JSON response from the last Ajax request that DataTables made to the
+ * server. Note that this returns the JSON from the first table in the current
+ * context.
+ *
+ * @return {object} JSON received from the server.
+ */
+ _api_register( 'ajax.json()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length > 0 ) {
+ return ctx[0].json;
+ }
+
+ // else return undefined;
+ } );
+
+
+ /**
+ * Get the data submitted in the last Ajax request
+ */
+ _api_register( 'ajax.params()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length > 0 ) {
+ return ctx[0].oAjaxData;
+ }
+
+ // else return undefined;
+ } );
+
+
+ /**
+ * Reload tables from the Ajax data source. Note that this function will
+ * automatically re-draw the table when the remote data has been loaded.
+ *
+ * @param {boolean} [reset=true] Reset (default) or hold the current paging
+ * position. A full re-sort and re-filter is performed when this method is
+ * called, which is why the pagination reset is the default action.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.reload()', function ( callback, resetPaging ) {
+ return this.iterator( 'table', function (settings) {
+ __reload( settings, resetPaging===false, callback );
+ } );
+ } );
+
+
+ /**
+ * Get the current Ajax URL. Note that this returns the URL from the first
+ * table in the current context.
+ *
+ * @return {string} Current Ajax source URL
+ *//**
+ * Set the Ajax URL. Note that this will set the URL for all tables in the
+ * current context.
+ *
+ * @param {string} url URL to set.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.url()', function ( url ) {
+ var ctx = this.context;
+
+ if ( url === undefined ) {
+ // get
+ if ( ctx.length === 0 ) {
+ return undefined;
+ }
+ ctx = ctx[0];
+
+ return ctx.ajax ?
+ $.isPlainObject( ctx.ajax ) ?
+ ctx.ajax.url :
+ ctx.ajax :
+ ctx.sAjaxSource;
+ }
+
+ // set
+ return this.iterator( 'table', function ( settings ) {
+ if ( $.isPlainObject( settings.ajax ) ) {
+ settings.ajax.url = url;
+ }
+ else {
+ settings.ajax = url;
+ }
+ // No need to consider sAjaxSource here since DataTables gives priority
+ // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
+ // value of `sAjaxSource` redundant.
+ } );
+ } );
+
+
+ /**
+ * Load data from the newly set Ajax URL. Note that this method is only
+ * available when `ajax.url()` is used to set a URL. Additionally, this method
+ * has the same effect as calling `ajax.reload()` but is provided for
+ * convenience when setting a new URL. Like `ajax.reload()` it will
+ * automatically redraw the table once the remote data has been loaded.
+ *
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.url().load()', function ( callback, resetPaging ) {
+ // Same as a reload, but makes sense to present it for easy access after a
+ // url change
+ return this.iterator( 'table', function ( ctx ) {
+ __reload( ctx, resetPaging===false, callback );
+ } );
+ } );
+
+
+
+
+ var _selector_run = function ( type, selector, selectFn, settings, opts )
+ {
+ var
+ out = [], res,
+ a, i, ien, j, jen,
+ selectorType = typeof selector;
+
+ // Can't just check for isArray here, as an API or jQuery instance might be
+ // given with their array like look
+ if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) {
+ selector = [ selector ];
+ }
+
+ for ( i=0, ien=selector.length ; i<ien ; i++ ) {
+ a = selector[i] && selector[i].split ?
+ selector[i].split(',') :
+ [ selector[i] ];
+
+ for ( j=0, jen=a.length ; j<jen ; j++ ) {
+ res = selectFn( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] );
+
+ if ( res && res.length ) {
+ out = out.concat( res );
+ }
+ }
+ }
+
+ // selector extensions
+ var ext = _ext.selector[ type ];
+ if ( ext.length ) {
+ for ( i=0, ien=ext.length ; i<ien ; i++ ) {
+ out = ext[i]( settings, opts, out );
+ }
+ }
+
+ return _unique( out );
+ };
+
+
+ var _selector_opts = function ( opts )
+ {
+ if ( ! opts ) {
+ opts = {};
+ }
+
+ // Backwards compatibility for 1.9- which used the terminology filter rather
+ // than search
+ if ( opts.filter && opts.search === undefined ) {
+ opts.search = opts.filter;
+ }
+
+ return $.extend( {
+ search: 'none',
+ order: 'current',
+ page: 'all'
+ }, opts );
+ };
+
+
+ var _selector_first = function ( inst )
+ {
+ // Reduce the API instance to the first item found
+ for ( var i=0, ien=inst.length ; i<ien ; i++ ) {
+ if ( inst[i].length > 0 ) {
+ // Assign the first element to the first item in the instance
+ // and truncate the instance and context
+ inst[0] = inst[i];
+ inst[0].length = 1;
+ inst.length = 1;
+ inst.context = [ inst.context[i] ];
+
+ return inst;
+ }
+ }
+
+ // Not found - return an empty instance
+ inst.length = 0;
+ return inst;
+ };
+
+
+ var _selector_row_indexes = function ( settings, opts )
+ {
+ var
+ i, ien, tmp, a=[],
+ displayFiltered = settings.aiDisplay,
+ displayMaster = settings.aiDisplayMaster;
+
+ var
+ search = opts.search, // none, applied, removed
+ order = opts.order, // applied, current, index (original - compatibility with 1.9)
+ page = opts.page; // all, current
+
+ if ( _fnDataSource( settings ) == 'ssp' ) {
+ // In server-side processing mode, most options are irrelevant since
+ // rows not shown don't exist and the index order is the applied order
+ // Removed is a special case - for consistency just return an empty
+ // array
+ return search === 'removed' ?
+ [] :
+ _range( 0, displayMaster.length );
+ }
+ else if ( page == 'current' ) {
+ // Current page implies that order=current and fitler=applied, since it is
+ // fairly senseless otherwise, regardless of what order and search actually
+ // are
+ for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) {
+ a.push( displayFiltered[i] );
+ }
+ }
+ else if ( order == 'current' || order == 'applied' ) {
+ a = search == 'none' ?
+ displayMaster.slice() : // no search
+ search == 'applied' ?
+ displayFiltered.slice() : // applied search
+ $.map( displayMaster, function (el, i) { // removed search
+ return $.inArray( el, displayFiltered ) === -1 ? el : null;
+ } );
+ }
+ else if ( order == 'index' || order == 'original' ) {
+ for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ if ( search == 'none' ) {
+ a.push( i );
+ }
+ else { // applied | removed
+ tmp = $.inArray( i, displayFiltered );
+
+ if ((tmp === -1 && search == 'removed') ||
+ (tmp >= 0 && search == 'applied') )
+ {
+ a.push( i );
+ }
+ }
+ }
+ }
+
+ return a;
+ };
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Rows
+ *
+ * {} - no selector - use all available rows
+ * {integer} - row aoData index
+ * {node} - TR node
+ * {string} - jQuery selector to apply to the TR elements
+ * {array} - jQuery array of nodes, or simply an array of TR nodes
+ *
+ */
+
+
+ var __row_selector = function ( settings, selector, opts )
+ {
+ var run = function ( sel ) {
+ var selInt = _intVal( sel );
+ var i, ien;
+
+ // Short cut - selector is a number and no options provided (default is
+ // all records, so no need to check if the index is in there, since it
+ // must be - dev error if the index doesn't exist).
+ if ( selInt !== null && ! opts ) {
+ return [ selInt ];
+ }
+
+ var rows = _selector_row_indexes( settings, opts );
+
+ if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) {
+ // Selector - integer
+ return [ selInt ];
+ }
+ else if ( ! sel ) {
+ // Selector - none
+ return rows;
+ }
+
+ // Selector - function
+ if ( typeof sel === 'function' ) {
+ return $.map( rows, function (idx) {
+ var row = settings.aoData[ idx ];
+ return sel( idx, row._aData, row.nTr ) ? idx : null;
+ } );
+ }
+
+ // Get nodes in the order from the `rows` array with null values removed
+ var nodes = _removeEmpty(
+ _pluck_order( settings.aoData, rows, 'nTr' )
+ );
+
+ // Selector - node
+ if ( sel.nodeName ) {
+ if ( $.inArray( sel, nodes ) !== -1 ) {
+ return [ sel._DT_RowIndex ]; // sel is a TR node that is in the table
+ // and DataTables adds a prop for fast lookup
+ }
+ }
+
+ // ID selector. Want to always be able to select rows by id, regardless
+ // of if the tr element has been created or not, so can't rely upon
+ // jQuery here - hence a custom implementation. This does not match
+ // Sizzle's fast selector or HTML4 - in HTML5 the ID can be anything,
+ // but to select it using a CSS selector engine (like Sizzle or
+ // querySelect) it would need to need to be escaped for some characters.
+ // DataTables simplifies this for row selectors since you can select
+ // only a row. A # indicates an id any anything that follows is the id -
+ // unescaped.
+ if ( typeof sel === 'string' && sel.charAt(0) === '#' ) {
+ // get row index from id
+ var rowObj = settings.aIds[ sel.replace( /^#/, '' ) ];
+ if ( rowObj !== undefined ) {
+ return [ rowObj.idx ];
+ }
+
+ // need to fall through to jQuery in case there is DOM id that
+ // matches
+ }
+
+ // Selector - jQuery selector string, array of nodes or jQuery object/
+ // As jQuery's .filter() allows jQuery objects to be passed in filter,
+ // it also allows arrays, so this will cope with all three options
+ return $(nodes)
+ .filter( sel )
+ .map( function () {
+ return this._DT_RowIndex;
+ } )
+ .toArray();
+ };
+
+ return _selector_run( 'row', selector, run, settings, opts );
+ };
+
+
+ _api_register( 'rows()', function ( selector, opts ) {
+ // argument shifting
+ if ( selector === undefined ) {
+ selector = '';
+ }
+ else if ( $.isPlainObject( selector ) ) {
+ opts = selector;
+ selector = '';
+ }
+
+ opts = _selector_opts( opts );
+
+ var inst = this.iterator( 'table', function ( settings ) {
+ return __row_selector( settings, selector, opts );
+ }, 1 );
+
+ // Want argument shifting here and in __row_selector?
+ inst.selector.rows = selector;
+ inst.selector.opts = opts;
+
+ return inst;
+ } );
+
+ _api_register( 'rows().nodes()', function () {
+ return this.iterator( 'row', function ( settings, row ) {
+ return settings.aoData[ row ].nTr || undefined;
+ }, 1 );
+ } );
+
+ _api_register( 'rows().data()', function () {
+ return this.iterator( true, 'rows', function ( settings, rows ) {
+ return _pluck_order( settings.aoData, rows, '_aData' );
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) {
+ return this.iterator( 'row', function ( settings, row ) {
+ var r = settings.aoData[ row ];
+ return type === 'search' ? r._aFilterData : r._aSortData;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) {
+ return this.iterator( 'row', function ( settings, row ) {
+ _fnInvalidate( settings, row, src );
+ } );
+ } );
+
+ _api_registerPlural( 'rows().indexes()', 'row().index()', function () {
+ return this.iterator( 'row', function ( settings, row ) {
+ return row;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().ids()', 'row().id()', function ( hash ) {
+ var a = [];
+ var context = this.context;
+
+ // `iterator` will drop undefined values, but in this case we want them
+ for ( var i=0, ien=context.length ; i<ien ; i++ ) {
+ for ( var j=0, jen=this[i].length ; j<jen ; j++ ) {
+ var id = context[i].rowIdFn( context[i].aoData[ this[i][j] ]._aData );
+ a.push( (hash === true ? '#' : '' )+ id );
+ }
+ }
+
+ return new _Api( context, a );
+ } );
+
+ _api_registerPlural( 'rows().remove()', 'row().remove()', function () {
+ var that = this;
+
+ this.iterator( 'row', function ( settings, row, thatIdx ) {
+ var data = settings.aoData;
+ var rowData = data[ row ];
+ var i, ien, j, jen;
+ var loopRow, loopCells;
+
+ data.splice( row, 1 );
+
+ // Update the cached indexes
+ for ( i=0, ien=data.length ; i<ien ; i++ ) {
+ loopRow = data[i];
+ loopCells = loopRow.anCells;
+
+ // Rows
+ if ( loopRow.nTr !== null ) {
+ loopRow.nTr._DT_RowIndex = i;
+ }
+
+ // Cells
+ if ( loopCells !== null ) {
+ for ( j=0, jen=loopCells.length ; j<jen ; j++ ) {
+ loopCells[j]._DT_CellIndex.row = i;
+ }
+ }
+ }
+
+ // Delete from the display arrays
+ _fnDeleteIndex( settings.aiDisplayMaster, row );
+ _fnDeleteIndex( settings.aiDisplay, row );
+ _fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes
+
+ // Check for an 'overflow' they case for displaying the table
+ _fnLengthOverflow( settings );
+
+ // Remove the row's ID reference if there is one
+ var id = settings.rowIdFn( rowData._aData );
+ if ( id !== undefined ) {
+ delete settings.aIds[ id ];
+ }
+ } );
+
+ this.iterator( 'table', function ( settings ) {
+ for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ settings.aoData[i].idx = i;
+ }
+ } );
+
+ return this;
+ } );
+
+
+ _api_register( 'rows.add()', function ( rows ) {
+ var newRows = this.iterator( 'table', function ( settings ) {
+ var row, i, ien;
+ var out = [];
+
+ for ( i=0, ien=rows.length ; i<ien ; i++ ) {
+ row = rows[i];
+
+ if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
+ out.push( _fnAddTr( settings, row )[0] );
+ }
+ else {
+ out.push( _fnAddData( settings, row ) );
+ }
+ }
+
+ return out;
+ }, 1 );
+
+ // Return an Api.rows() extended instance, so rows().nodes() etc can be used
+ var modRows = this.rows( -1 );
+ modRows.pop();
+ $.merge( modRows, newRows );
+
+ return modRows;
+ } );
+
+
+
+
+
+ /**
+ *
+ */
+ _api_register( 'row()', function ( selector, opts ) {
+ return _selector_first( this.rows( selector, opts ) );
+ } );
+
+
+ _api_register( 'row().data()', function ( data ) {
+ var ctx = this.context;
+
+ if ( data === undefined ) {
+ // Get
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ]._aData :
+ undefined;
+ }
+
+ // Set
+ ctx[0].aoData[ this[0] ]._aData = data;
+
+ // Automatically invalidate
+ _fnInvalidate( ctx[0], this[0], 'data' );
+
+ return this;
+ } );
+
+
+ _api_register( 'row().node()', function () {
+ var ctx = this.context;
+
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ].nTr || null :
+ null;
+ } );
+
+
+ _api_register( 'row.add()', function ( row ) {
+ // Allow a jQuery object to be passed in - only a single row is added from
+ // it though - the first element in the set
+ if ( row instanceof $ && row.length ) {
+ row = row[0];
+ }
+
+ var rows = this.iterator( 'table', function ( settings ) {
+ if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
+ return _fnAddTr( settings, row )[0];
+ }
+ return _fnAddData( settings, row );
+ } );
+
+ // Return an Api.rows() extended instance, with the newly added row selected
+ return this.row( rows[0] );
+ } );
+
+
+
+ var __details_add = function ( ctx, row, data, klass )
+ {
+ // Convert to array of TR elements
+ var rows = [];
+ var addRow = function ( r, k ) {
+ // Recursion to allow for arrays of jQuery objects
+ if ( $.isArray( r ) || r instanceof $ ) {
+ for ( var i=0, ien=r.length ; i<ien ; i++ ) {
+ addRow( r[i], k );
+ }
+ return;
+ }
+
+ // If we get a TR element, then just add it directly - up to the dev
+ // to add the correct number of columns etc
+ if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) {
+ rows.push( r );
+ }
+ else {
+ // Otherwise create a row with a wrapper
+ var created = $('<tr><td/></tr>').addClass( k );
+ $('td', created)
+ .addClass( k )
+ .html( r )
+ [0].colSpan = _fnVisbleColumns( ctx );
+
+ rows.push( created[0] );
+ }
+ };
+
+ addRow( data, klass );
+
+ if ( row._details ) {
+ row._details.remove();
+ }
+
+ row._details = $(rows);
+
+ // If the children were already shown, that state should be retained
+ if ( row._detailsShow ) {
+ row._details.insertAfter( row.nTr );
+ }
+ };
+
+
+ var __details_remove = function ( api, idx )
+ {
+ var ctx = api.context;
+
+ if ( ctx.length ) {
+ var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ];
+
+ if ( row && row._details ) {
+ row._details.remove();
+
+ row._detailsShow = undefined;
+ row._details = undefined;
+ }
+ }
+ };
+
+
+ var __details_display = function ( api, show ) {
+ var ctx = api.context;
+
+ if ( ctx.length && api.length ) {
+ var row = ctx[0].aoData[ api[0] ];
+
+ if ( row._details ) {
+ row._detailsShow = show;
+
+ if ( show ) {
+ row._details.insertAfter( row.nTr );
+ }
+ else {
+ row._details.detach();
+ }
+
+ __details_events( ctx[0] );
+ }
+ }
+ };
+
+
+ var __details_events = function ( settings )
+ {
+ var api = new _Api( settings );
+ var namespace = '.dt.DT_details';
+ var drawEvent = 'draw'+namespace;
+ var colvisEvent = 'column-visibility'+namespace;
+ var destroyEvent = 'destroy'+namespace;
+ var data = settings.aoData;
+
+ api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent );
+
+ if ( _pluck( data, '_details' ).length > 0 ) {
+ // On each draw, insert the required elements into the document
+ api.on( drawEvent, function ( e, ctx ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ api.rows( {page:'current'} ).eq(0).each( function (idx) {
+ // Internal data grab
+ var row = data[ idx ];
+
+ if ( row._detailsShow ) {
+ row._details.insertAfter( row.nTr );
+ }
+ } );
+ } );
+
+ // Column visibility change - update the colspan
+ api.on( colvisEvent, function ( e, ctx, idx, vis ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ // Update the colspan for the details rows (note, only if it already has
+ // a colspan)
+ var row, visible = _fnVisbleColumns( ctx );
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ row = data[i];
+
+ if ( row._details ) {
+ row._details.children('td[colspan]').attr('colspan', visible );
+ }
+ }
+ } );
+
+ // Table destroyed - nuke any child rows
+ api.on( destroyEvent, function ( e, ctx ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ if ( data[i]._details ) {
+ __details_remove( api, i );
+ }
+ }
+ } );
+ }
+ };
+
+ // Strings for the method names to help minification
+ var _emp = '';
+ var _child_obj = _emp+'row().child';
+ var _child_mth = _child_obj+'()';
+
+ // data can be:
+ // tr
+ // string
+ // jQuery or array of any of the above
+ _api_register( _child_mth, function ( data, klass ) {
+ var ctx = this.context;
+
+ if ( data === undefined ) {
+ // get
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ]._details :
+ undefined;
+ }
+ else if ( data === true ) {
+ // show
+ this.child.show();
+ }
+ else if ( data === false ) {
+ // remove
+ __details_remove( this );
+ }
+ else if ( ctx.length && this.length ) {
+ // set
+ __details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass );
+ }
+
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.show()',
+ _child_mth+'.show()' // only when `child()` was called with parameters (without
+ ], function ( show ) { // it returns an object and this method is not executed)
+ __details_display( this, true );
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.hide()',
+ _child_mth+'.hide()' // only when `child()` was called with parameters (without
+ ], function () { // it returns an object and this method is not executed)
+ __details_display( this, false );
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.remove()',
+ _child_mth+'.remove()' // only when `child()` was called with parameters (without
+ ], function () { // it returns an object and this method is not executed)
+ __details_remove( this );
+ return this;
+ } );
+
+
+ _api_register( _child_obj+'.isShown()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length && this.length ) {
+ // _detailsShown as false or undefined will fall through to return false
+ return ctx[0].aoData[ this[0] ]._detailsShow || false;
+ }
+ return false;
+ } );
+
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Columns
+ *
+ * {integer} - column index (>=0 count from left, <0 count from right)
+ * "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right)
+ * "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right)
+ * "{string}:name" - column name
+ * "{string}" - jQuery selector on column header nodes
+ *
+ */
+
+ // can be an array of these items, comma separated list, or an array of comma
+ // separated lists
+
+ var __re_column_selector = /^(.+):(name|visIdx|visible)$/;
+
+
+ // r1 and r2 are redundant - but it means that the parameters match for the
+ // iterator callback in columns().data()
+ var __columnData = function ( settings, column, r1, r2, rows ) {
+ var a = [];
+ for ( var row=0, ien=rows.length ; row<ien ; row++ ) {
+ a.push( _fnGetCellData( settings, rows[row], column ) );
+ }
+ return a;
+ };
+
+
+ var __column_selector = function ( settings, selector, opts )
+ {
+ var
+ columns = settings.aoColumns,
+ names = _pluck( columns, 'sName' ),
+ nodes = _pluck( columns, 'nTh' );
+
+ var run = function ( s ) {
+ var selInt = _intVal( s );
+
+ // Selector - all
+ if ( s === '' ) {
+ return _range( columns.length );
+ }
+
+ // Selector - index
+ if ( selInt !== null ) {
+ return [ selInt >= 0 ?
+ selInt : // Count from left
+ columns.length + selInt // Count from right (+ because its a negative value)
+ ];
+ }
+
+ // Selector = function
+ if ( typeof s === 'function' ) {
+ var rows = _selector_row_indexes( settings, opts );
+
+ return $.map( columns, function (col, idx) {
+ return s(
+ idx,
+ __columnData( settings, idx, 0, 0, rows ),
+ nodes[ idx ]
+ ) ? idx : null;
+ } );
+ }
+
+ // jQuery or string selector
+ var match = typeof s === 'string' ?
+ s.match( __re_column_selector ) :
+ '';
+
+ if ( match ) {
+ switch( match[2] ) {
+ case 'visIdx':
+ case 'visible':
+ var idx = parseInt( match[1], 10 );
+ // Visible index given, convert to column index
+ if ( idx < 0 ) {
+ // Counting from the right
+ var visColumns = $.map( columns, function (col,i) {
+ return col.bVisible ? i : null;
+ } );
+ return [ visColumns[ visColumns.length + idx ] ];
+ }
+ // Counting from the left
+ return [ _fnVisibleToColumnIndex( settings, idx ) ];
+
+ case 'name':
+ // match by name. `names` is column index complete and in order
+ return $.map( names, function (name, i) {
+ return name === match[1] ? i : null;
+ } );
+ }
+ }
+ else {
+ // jQuery selector on the TH elements for the columns
+ return $( nodes )
+ .filter( s )
+ .map( function () {
+ return $.inArray( this, nodes ); // `nodes` is column index complete and in order
+ } )
+ .toArray();
+ }
+ };
+
+ return _selector_run( 'column', selector, run, settings, opts );
+ };
+
+
+ var __setColumnVis = function ( settings, column, vis, recalc ) {
+ var
+ cols = settings.aoColumns,
+ col = cols[ column ],
+ data = settings.aoData,
+ row, cells, i, ien, tr;
+
+ // Get
+ if ( vis === undefined ) {
+ return col.bVisible;
+ }
+
+ // Set
+ // No change
+ if ( col.bVisible === vis ) {
+ return;
+ }
+
+ if ( vis ) {
+ // Insert column
+ // Need to decide if we should use appendChild or insertBefore
+ var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 );
+
+ for ( i=0, ien=data.length ; i<ien ; i++ ) {
+ tr = data[i].nTr;
+ cells = data[i].anCells;
+
+ if ( tr ) {
+ // insertBefore can act like appendChild if 2nd arg is null
+ tr.insertBefore( cells[ column ], cells[ insertBefore ] || null );
+ }
+ }
+ }
+ else {
+ // Remove column
+ $( _pluck( settings.aoData, 'anCells', column ) ).detach();
+ }
+
+ // Common actions
+ col.bVisible = vis;
+ _fnDrawHead( settings, settings.aoHeader );
+ _fnDrawHead( settings, settings.aoFooter );
+
+ if ( recalc === undefined || recalc ) {
+ // Automatically adjust column sizing
+ _fnAdjustColumnSizing( settings );
+
+ // Realign columns for scrolling
+ if ( settings.oScroll.sX || settings.oScroll.sY ) {
+ _fnScrollDraw( settings );
+ }
+ }
+
+ _fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis, recalc] );
+
+ _fnSaveState( settings );
+ };
+
+
+ _api_register( 'columns()', function ( selector, opts ) {
+ // argument shifting
+ if ( selector === undefined ) {
+ selector = '';
+ }
+ else if ( $.isPlainObject( selector ) ) {
+ opts = selector;
+ selector = '';
+ }
+
+ opts = _selector_opts( opts );
+
+ var inst = this.iterator( 'table', function ( settings ) {
+ return __column_selector( settings, selector, opts );
+ }, 1 );
+
+ // Want argument shifting here and in _row_selector?
+ inst.selector.cols = selector;
+ inst.selector.opts = opts;
+
+ return inst;
+ } );
+
+ _api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].nTh;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].nTf;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().data()', 'column().data()', function () {
+ return this.iterator( 'column-rows', __columnData, 1 );
+ } );
+
+ _api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].mData;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) {
+ return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
+ return _pluck_order( settings.aoData, rows,
+ type === 'search' ? '_aFilterData' : '_aSortData', column
+ );
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().nodes()', 'column().nodes()', function () {
+ return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
+ return _pluck_order( settings.aoData, rows, 'anCells', column ) ;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ if ( vis === undefined ) {
+ return settings.aoColumns[ column ].bVisible;
+ } // else
+ __setColumnVis( settings, column, vis, calc );
+ } );
+ } );
+
+ _api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return type === 'visible' ?
+ _fnColumnIndexToVisible( settings, column ) :
+ column;
+ }, 1 );
+ } );
+
+ _api_register( 'columns.adjust()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnAdjustColumnSizing( settings );
+ }, 1 );
+ } );
+
+ _api_register( 'column.index()', function ( type, idx ) {
+ if ( this.context.length !== 0 ) {
+ var ctx = this.context[0];
+
+ if ( type === 'fromVisible' || type === 'toData' ) {
+ return _fnVisibleToColumnIndex( ctx, idx );
+ }
+ else if ( type === 'fromData' || type === 'toVisible' ) {
+ return _fnColumnIndexToVisible( ctx, idx );
+ }
+ }
+ } );
+
+ _api_register( 'column()', function ( selector, opts ) {
+ return _selector_first( this.columns( selector, opts ) );
+ } );
+
+
+
+
+ var __cell_selector = function ( settings, selector, opts )
+ {
+ var data = settings.aoData;
+ var rows = _selector_row_indexes( settings, opts );
+ var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) );
+ var allCells = $( [].concat.apply([], cells) );
+ var row;
+ var columns = settings.aoColumns.length;
+ var a, i, ien, j, o, host;
+
+ var run = function ( s ) {
+ var fnSelector = typeof s === 'function';
+
+ if ( s === null || s === undefined || fnSelector ) {
+ // All cells and function selectors
+ a = [];
+
+ for ( i=0, ien=rows.length ; i<ien ; i++ ) {
+ row = rows[i];
+
+ for ( j=0 ; j<columns ; j++ ) {
+ o = {
+ row: row,
+ column: j
+ };
+
+ if ( fnSelector ) {
+ // Selector - function
+ host = data[ row ];
+
+ if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) {
+ a.push( o );
+ }
+ }
+ else {
+ // Selector - all
+ a.push( o );
+ }
+ }
+ }
+
+ return a;
+ }
+
+ // Selector - index
+ if ( $.isPlainObject( s ) ) {
+ return [s];
+ }
+
+ // Selector - jQuery filtered cells
+ return allCells
+ .filter( s )
+ .map( function (i, el) {
+ return { // use a new object, in case someone changes the values
+ row: el._DT_CellIndex.row,
+ column: el._DT_CellIndex.column
+ };
+ } )
+ .toArray();
+ };
+
+ return _selector_run( 'cell', selector, run, settings, opts );
+ };
+
+
+
+
+ _api_register( 'cells()', function ( rowSelector, columnSelector, opts ) {
+ // Argument shifting
+ if ( $.isPlainObject( rowSelector ) ) {
+ // Indexes
+ if ( rowSelector.row === undefined ) {
+ // Selector options in first parameter
+ opts = rowSelector;
+ rowSelector = null;
+ }
+ else {
+ // Cell index objects in first parameter
+ opts = columnSelector;
+ columnSelector = null;
+ }
+ }
+ if ( $.isPlainObject( columnSelector ) ) {
+ opts = columnSelector;
+ columnSelector = null;
+ }
+
+ // Cell selector
+ if ( columnSelector === null || columnSelector === undefined ) {
+ return this.iterator( 'table', function ( settings ) {
+ return __cell_selector( settings, rowSelector, _selector_opts( opts ) );
+ } );
+ }
+
+ // Row + column selector
+ var columns = this.columns( columnSelector, opts );
+ var rows = this.rows( rowSelector, opts );
+ var a, i, ien, j, jen;
+
+ var cells = this.iterator( 'table', function ( settings, idx ) {
+ a = [];
+
+ for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) {
+ for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) {
+ a.push( {
+ row: rows[idx][i],
+ column: columns[idx][j]
+ } );
+ }
+ }
+
+ return a;
+ }, 1 );
+
+ $.extend( cells.selector, {
+ cols: columnSelector,
+ rows: rowSelector,
+ opts: opts
+ } );
+
+ return cells;
+ } );
+
+
+ _api_registerPlural( 'cells().nodes()', 'cell().node()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ var cells = settings.aoData[ row ].anCells;
+ return cells ?
+ cells[ column ] :
+ undefined;
+ }, 1 );
+ } );
+
+
+ _api_register( 'cells().data()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return _fnGetCellData( settings, row, column );
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) {
+ type = type === 'search' ? '_aFilterData' : '_aSortData';
+
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return settings.aoData[ row ][ type ][ column ];
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return _fnGetCellData( settings, row, column, type );
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().indexes()', 'cell().index()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return {
+ row: row,
+ column: column,
+ columnVisible: _fnColumnIndexToVisible( settings, column )
+ };
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ _fnInvalidate( settings, row, src, column );
+ } );
+ } );
+
+
+
+ _api_register( 'cell()', function ( rowSelector, columnSelector, opts ) {
+ return _selector_first( this.cells( rowSelector, columnSelector, opts ) );
+ } );
+
+
+ _api_register( 'cell().data()', function ( data ) {
+ var ctx = this.context;
+ var cell = this[0];
+
+ if ( data === undefined ) {
+ // Get
+ return ctx.length && cell.length ?
+ _fnGetCellData( ctx[0], cell[0].row, cell[0].column ) :
+ undefined;
+ }
+
+ // Set
+ _fnSetCellData( ctx[0], cell[0].row, cell[0].column, data );
+ _fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column );
+
+ return this;
+ } );
+
+
+
+ /**
+ * Get current ordering (sorting) that has been applied to the table.
+ *
+ * @returns {array} 2D array containing the sorting information for the first
+ * table in the current context. Each element in the parent array represents
+ * a column being sorted upon (i.e. multi-sorting with two columns would have
+ * 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
+ * the column index that the sorting condition applies to, the second is the
+ * direction of the sort (`desc` or `asc`) and, optionally, the third is the
+ * index of the sorting order from the `column.sorting` initialisation array.
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {integer} order Column index to sort upon.
+ * @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
+ * @returns {DataTables.Api} this
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {array} order 1D array of sorting information to be applied.
+ * @param {array} [...] Optional additional sorting conditions
+ * @returns {DataTables.Api} this
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {array} order 2D array of sorting information to be applied.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'order()', function ( order, dir ) {
+ var ctx = this.context;
+
+ if ( order === undefined ) {
+ // get
+ return ctx.length !== 0 ?
+ ctx[0].aaSorting :
+ undefined;
+ }
+
+ // set
+ if ( typeof order === 'number' ) {
+ // Simple column / direction passed in
+ order = [ [ order, dir ] ];
+ }
+ else if ( ! $.isArray( order[0] ) ) {
+ // Arguments passed in (list of 1D arrays)
+ order = Array.prototype.slice.call( arguments );
+ }
+ // otherwise a 2D array was passed in
+
+ return this.iterator( 'table', function ( settings ) {
+ settings.aaSorting = order.slice();
+ } );
+ } );
+
+
+ /**
+ * Attach a sort listener to an element for a given column
+ *
+ * @param {node|jQuery|string} node Identifier for the element(s) to attach the
+ * listener to. This can take the form of a single DOM node, a jQuery
+ * collection of nodes or a jQuery selector which will identify the node(s).
+ * @param {integer} column the column that a click on this node will sort on
+ * @param {function} [callback] callback function when sort is run
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'order.listener()', function ( node, column, callback ) {
+ return this.iterator( 'table', function ( settings ) {
+ _fnSortAttachListener( settings, node, column, callback );
+ } );
+ } );
+
+
+ _api_register( 'order.fixed()', function ( set ) {
+ if ( ! set ) {
+ var ctx = this.context;
+ var fixed = ctx.length ?
+ ctx[0].aaSortingFixed :
+ undefined;
+
+ return $.isArray( fixed ) ?
+ { pre: fixed } :
+ fixed;
+ }
+
+ return this.iterator( 'table', function ( settings ) {
+ settings.aaSortingFixed = $.extend( true, {}, set );
+ } );
+ } );
+
+
+ // Order by the selected column(s)
+ _api_register( [
+ 'columns().order()',
+ 'column().order()'
+ ], function ( dir ) {
+ var that = this;
+
+ return this.iterator( 'table', function ( settings, i ) {
+ var sort = [];
+
+ $.each( that[i], function (j, col) {
+ sort.push( [ col, dir ] );
+ } );
+
+ settings.aaSorting = sort;
+ } );
+ } );
+
+
+
+ _api_register( 'search()', function ( input, regex, smart, caseInsen ) {
+ var ctx = this.context;
+
+ if ( input === undefined ) {
+ // get
+ return ctx.length !== 0 ?
+ ctx[0].oPreviousSearch.sSearch :
+ undefined;
+ }
+
+ // set
+ return this.iterator( 'table', function ( settings ) {
+ if ( ! settings.oFeatures.bFilter ) {
+ return;
+ }
+
+ _fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, {
+ "sSearch": input+"",
+ "bRegex": regex === null ? false : regex,
+ "bSmart": smart === null ? true : smart,
+ "bCaseInsensitive": caseInsen === null ? true : caseInsen
+ } ), 1 );
+ } );
+ } );
+
+
+ _api_registerPlural(
+ 'columns().search()',
+ 'column().search()',
+ function ( input, regex, smart, caseInsen ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ var preSearch = settings.aoPreSearchCols;
+
+ if ( input === undefined ) {
+ // get
+ return preSearch[ column ].sSearch;
+ }
+
+ // set
+ if ( ! settings.oFeatures.bFilter ) {
+ return;
+ }
+
+ $.extend( preSearch[ column ], {
+ "sSearch": input+"",
+ "bRegex": regex === null ? false : regex,
+ "bSmart": smart === null ? true : smart,
+ "bCaseInsensitive": caseInsen === null ? true : caseInsen
+ } );
+
+ _fnFilterComplete( settings, settings.oPreviousSearch, 1 );
+ } );
+ }
+ );
+
+ /*
+ * State API methods
+ */
+
+ _api_register( 'state()', function () {
+ return this.context.length ?
+ this.context[0].oSavedState :
+ null;
+ } );
+
+
+ _api_register( 'state.clear()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ // Save an empty object
+ settings.fnStateSaveCallback.call( settings.oInstance, settings, {} );
+ } );
+ } );
+
+
+ _api_register( 'state.loaded()', function () {
+ return this.context.length ?
+ this.context[0].oLoadedState :
+ null;
+ } );
+
+
+ _api_register( 'state.save()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnSaveState( settings );
+ } );
+ } );
+
+
+
+ /**
+ * Provide a common method for plug-ins to check the version of DataTables being
+ * used, in order to ensure compatibility.
+ *
+ * @param {string} version Version string to check for, in the format "X.Y.Z".
+ * Note that the formats "X" and "X.Y" are also acceptable.
+ * @returns {boolean} true if this version of DataTables is greater or equal to
+ * the required version, or false if this version of DataTales is not
+ * suitable
+ * @static
+ * @dtopt API-Static
+ *
+ * @example
+ * alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
+ */
+ DataTable.versionCheck = DataTable.fnVersionCheck = function( version )
+ {
+ var aThis = DataTable.version.split('.');
+ var aThat = version.split('.');
+ var iThis, iThat;
+
+ for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) {
+ iThis = parseInt( aThis[i], 10 ) || 0;
+ iThat = parseInt( aThat[i], 10 ) || 0;
+
+ // Parts are the same, keep comparing
+ if (iThis === iThat) {
+ continue;
+ }
+
+ // Parts are different, return immediately
+ return iThis > iThat;
+ }
+
+ return true;
+ };
+
+
+ /**
+ * Check if a `<table>` node is a DataTable table already or not.
+ *
+ * @param {node|jquery|string} table Table node, jQuery object or jQuery
+ * selector for the table to test. Note that if more than more than one
+ * table is passed on, only the first will be checked
+ * @returns {boolean} true the table given is a DataTable, or false otherwise
+ * @static
+ * @dtopt API-Static
+ *
+ * @example
+ * if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
+ * $('#example').dataTable();
+ * }
+ */
+ DataTable.isDataTable = DataTable.fnIsDataTable = function ( table )
+ {
+ var t = $(table).get(0);
+ var is = false;
+
+ $.each( DataTable.settings, function (i, o) {
+ var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null;
+ var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null;
+
+ if ( o.nTable === t || head === t || foot === t ) {
+ is = true;
+ }
+ } );
+
+ return is;
+ };
+
+
+ /**
+ * Get all DataTable tables that have been initialised - optionally you can
+ * select to get only currently visible tables.
+ *
+ * @param {boolean} [visible=false] Flag to indicate if you want all (default)
+ * or visible tables only.
+ * @returns {array} Array of `table` nodes (not DataTable instances) which are
+ * DataTables
+ * @static
+ * @dtopt API-Static
+ *
+ * @example
+ * $.each( $.fn.dataTable.tables(true), function () {
+ * $(table).DataTable().columns.adjust();
+ * } );
+ */
+ DataTable.tables = DataTable.fnTables = function ( visible )
+ {
+ var api = false;
+
+ if ( $.isPlainObject( visible ) ) {
+ api = visible.api;
+ visible = visible.visible;
+ }
+
+ var a = $.map( DataTable.settings, function (o) {
+ if ( !visible || (visible && $(o.nTable).is(':visible')) ) {
+ return o.nTable;
+ }
+ } );
+
+ return api ?
+ new _Api( a ) :
+ a;
+ };
+
+
+ /**
+ * DataTables utility methods
+ *
+ * This namespace provides helper methods that DataTables uses internally to
+ * create a DataTable, but which are not exclusively used only for DataTables.
+ * These methods can be used by extension authors to save the duplication of
+ * code.
+ *
+ * @namespace
+ */
+ DataTable.util = {
+ /**
+ * Throttle the calls to a function. Arguments and context are maintained
+ * for the throttled function.
+ *
+ * @param {function} fn Function to be called
+ * @param {integer} freq Call frequency in mS
+ * @return {function} Wrapped function
+ */
+ throttle: _fnThrottle,
+
+
+ /**
+ * Escape a string such that it can be used in a regular expression
+ *
+ * @param {string} sVal string to escape
+ * @returns {string} escaped string
+ */
+ escapeRegex: _fnEscapeRegex
+ };
+
+
+ /**
+ * Convert from camel case parameters to Hungarian notation. This is made public
+ * for the extensions to provide the same ability as DataTables core to accept
+ * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
+ * parameters.
+ *
+ * @param {object} src The model object which holds all parameters that can be
+ * mapped.
+ * @param {object} user The object to convert from camel case to Hungarian.
+ * @param {boolean} force When set to `true`, properties which already have a
+ * Hungarian value in the `user` object will be overwritten. Otherwise they
+ * won't be.
+ */
+ DataTable.camelToHungarian = _fnCamelToHungarian;
+
+
+
+ /**
+ *
+ */
+ _api_register( '$()', function ( selector, opts ) {
+ var
+ rows = this.rows( opts ).nodes(), // Get all rows
+ jqRows = $(rows);
+
+ return $( [].concat(
+ jqRows.filter( selector ).toArray(),
+ jqRows.find( selector ).toArray()
+ ) );
+ } );
+
+
+ // jQuery functions to operate on the tables
+ $.each( [ 'on', 'one', 'off' ], function (i, key) {
+ _api_register( key+'()', function ( /* event, handler */ ) {
+ var args = Array.prototype.slice.call(arguments);
+
+ // Add the `dt` namespace automatically if it isn't already present
+ if ( ! args[0].match(/\.dt\b/) ) {
+ args[0] += '.dt';
+ }
+
+ var inst = $( this.tables().nodes() );
+ inst[key].apply( inst, args );
+ return this;
+ } );
+ } );
+
+
+ _api_register( 'clear()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnClearTable( settings );
+ } );
+ } );
+
+
+ _api_register( 'settings()', function () {
+ return new _Api( this.context, this.context );
+ } );
+
+
+ _api_register( 'init()', function () {
+ var ctx = this.context;
+ return ctx.length ? ctx[0].oInit : null;
+ } );
+
+
+ _api_register( 'data()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ return _pluck( settings.aoData, '_aData' );
+ } ).flatten();
+ } );
+
+
+ _api_register( 'destroy()', function ( remove ) {
+ remove = remove || false;
+
+ return this.iterator( 'table', function ( settings ) {
+ var orig = settings.nTableWrapper.parentNode;
+ var classes = settings.oClasses;
+ var table = settings.nTable;
+ var tbody = settings.nTBody;
+ var thead = settings.nTHead;
+ var tfoot = settings.nTFoot;
+ var jqTable = $(table);
+ var jqTbody = $(tbody);
+ var jqWrapper = $(settings.nTableWrapper);
+ var rows = $.map( settings.aoData, function (r) { return r.nTr; } );
+ var i, ien;
+
+ // Flag to note that the table is currently being destroyed - no action
+ // should be taken
+ settings.bDestroying = true;
+
+ // Fire off the destroy callbacks for plug-ins etc
+ _fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] );
+
+ // If not being removed from the document, make all columns visible
+ if ( ! remove ) {
+ new _Api( settings ).columns().visible( true );
+ }
+
+ // Blitz all `DT` namespaced events (these are internal events, the
+ // lowercase, `dt` events are user subscribed and they are responsible
+ // for removing them
+ jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT');
+ $(window).unbind('.DT-'+settings.sInstance);
+
+ // When scrolling we had to break the table up - restore it
+ if ( table != thead.parentNode ) {
+ jqTable.children('thead').detach();
+ jqTable.append( thead );
+ }
+
+ if ( tfoot && table != tfoot.parentNode ) {
+ jqTable.children('tfoot').detach();
+ jqTable.append( tfoot );
+ }
+
+ settings.aaSorting = [];
+ settings.aaSortingFixed = [];
+ _fnSortingClasses( settings );
+
+ $( rows ).removeClass( settings.asStripeClasses.join(' ') );
+
+ $('th, td', thead).removeClass( classes.sSortable+' '+
+ classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone
+ );
+
+ if ( settings.bJUI ) {
+ $('th span.'+classes.sSortIcon+ ', td span.'+classes.sSortIcon, thead).detach();
+ $('th, td', thead).each( function () {
+ var wrapper = $('div.'+classes.sSortJUIWrapper, this);
+ $(this).append( wrapper.contents() );
+ wrapper.detach();
+ } );
+ }
+
+ // Add the TR elements back into the table in their original order
+ jqTbody.children().detach();
+ jqTbody.append( rows );
+
+ // Remove the DataTables generated nodes, events and classes
+ var removedMethod = remove ? 'remove' : 'detach';
+ jqTable[ removedMethod ]();
+ jqWrapper[ removedMethod ]();
+
+ // If we need to reattach the table to the document
+ if ( ! remove && orig ) {
+ // insertBefore acts like appendChild if !arg[1]
+ orig.insertBefore( table, settings.nTableReinsertBefore );
+
+ // Restore the width of the original table - was read from the style property,
+ // so we can restore directly to that
+ jqTable
+ .css( 'width', settings.sDestroyWidth )
+ .removeClass( classes.sTable );
+
+ // If the were originally stripe classes - then we add them back here.
+ // Note this is not fool proof (for example if not all rows had stripe
+ // classes - but it's a good effort without getting carried away
+ ien = settings.asDestroyStripes.length;
+
+ if ( ien ) {
+ jqTbody.children().each( function (i) {
+ $(this).addClass( settings.asDestroyStripes[i % ien] );
+ } );
+ }
+ }
+
+ /* Remove the settings object from the settings array */
+ var idx = $.inArray( settings, DataTable.settings );
+ if ( idx !== -1 ) {
+ DataTable.settings.splice( idx, 1 );
+ }
+ } );
+ } );
+
+
+ // Add the `every()` method for rows, columns and cells in a compact form
+ $.each( [ 'column', 'row', 'cell' ], function ( i, type ) {
+ _api_register( type+'s().every()', function ( fn ) {
+ var opts = this.selector.opts;
+ var api = this;
+
+ return this.iterator( type, function ( settings, arg1, arg2, arg3, arg4 ) {
+ // Rows and columns:
+ // arg1 - index
+ // arg2 - table counter
+ // arg3 - loop counter
+ // arg4 - undefined
+ // Cells:
+ // arg1 - row index
+ // arg2 - column index
+ // arg3 - table counter
+ // arg4 - loop counter
+ fn.call(
+ api[ type ](
+ arg1,
+ type==='cell' ? arg2 : opts,
+ type==='cell' ? opts : undefined
+ ),
+ arg1, arg2, arg3, arg4
+ );
+ } );
+ } );
+ } );
+
+
+ // i18n method for extensions to be able to use the language object from the
+ // DataTable
+ _api_register( 'i18n()', function ( token, def, plural ) {
+ var ctx = this.context[0];
+ var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage );
+
+ if ( resolved === undefined ) {
+ resolved = def;
+ }
+
+ if ( plural !== undefined && $.isPlainObject( resolved ) ) {
+ resolved = resolved[ plural ] !== undefined ?
+ resolved[ plural ] :
+ resolved._;
+ }
+
+ return resolved.replace( '%d', plural ); // nb: plural might be undefined,
+ } );
+
+ /**
+ * Version string for plug-ins to check compatibility. Allowed format is
+ * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
+ * only for non-release builds. See http://semver.org/ for more information.
+ * @member
+ * @type string
+ * @default Version number
+ */
+ DataTable.version = "1.10.10";
+
+ /**
+ * Private data store, containing all of the settings objects that are
+ * created for the tables on a given page.
+ *
+ * Note that the `DataTable.settings` object is aliased to
+ * `jQuery.fn.dataTableExt` through which it may be accessed and
+ * manipulated, or `jQuery.fn.dataTable.settings`.
+ * @member
+ * @type array
+ * @default []
+ * @private
+ */
+ DataTable.settings = [];
+
+ /**
+ * Object models container, for the various models that DataTables has
+ * available to it. These models define the objects that are used to hold
+ * the active state and configuration of the table.
+ * @namespace
+ */
+ DataTable.models = {};
+
+
+
+ /**
+ * Template object for the way in which DataTables holds information about
+ * search information for the global filter and individual column filters.
+ * @namespace
+ */
+ DataTable.models.oSearch = {
+ /**
+ * Flag to indicate if the filtering should be case insensitive or not
+ * @type boolean
+ * @default true
+ */
+ "bCaseInsensitive": true,
+
+ /**
+ * Applied search term
+ * @type string
+ * @default <i>Empty string</i>
+ */
+ "sSearch": "",
+
+ /**
+ * Flag to indicate if the search term should be interpreted as a
+ * regular expression (true) or not (false) and therefore and special
+ * regex characters escaped.
+ * @type boolean
+ * @default false
+ */
+ "bRegex": false,
+
+ /**
+ * Flag to indicate if DataTables is to use its smart filtering or not.
+ * @type boolean
+ * @default true
+ */
+ "bSmart": true
+ };
+
+
+
+
+ /**
+ * Template object for the way in which DataTables holds information about
+ * each individual row. This is the object format used for the settings
+ * aoData array.
+ * @namespace
+ */
+ DataTable.models.oRow = {
+ /**
+ * TR element for the row
+ * @type node
+ * @default null
+ */
+ "nTr": null,
+
+ /**
+ * Array of TD elements for each row. This is null until the row has been
+ * created.
+ * @type array nodes
+ * @default []
+ */
+ "anCells": null,
+
+ /**
+ * Data object from the original data source for the row. This is either
+ * an array if using the traditional form of DataTables, or an object if
+ * using mData options. The exact type will depend on the passed in
+ * data from the data source, or will be an array if using DOM a data
+ * source.
+ * @type array|object
+ * @default []
+ */
+ "_aData": [],
+
+ /**
+ * Sorting data cache - this array is ostensibly the same length as the
+ * number of columns (although each index is generated only as it is
+ * needed), and holds the data that is used for sorting each column in the
+ * row. We do this cache generation at the start of the sort in order that
+ * the formatting of the sort data need be done only once for each cell
+ * per sort. This array should not be read from or written to by anything
+ * other than the master sorting methods.
+ * @type array
+ * @default null
+ * @private
+ */
+ "_aSortData": null,
+
+ /**
+ * Per cell filtering data cache. As per the sort data cache, used to
+ * increase the performance of the filtering in DataTables
+ * @type array
+ * @default null
+ * @private
+ */
+ "_aFilterData": null,
+
+ /**
+ * Filtering data cache. This is the same as the cell filtering cache, but
+ * in this case a string rather than an array. This is easily computed with
+ * a join on `_aFilterData`, but is provided as a cache so the join isn't
+ * needed on every search (memory traded for performance)
+ * @type array
+ * @default null
+ * @private
+ */
+ "_sFilterRow": null,
+
+ /**
+ * Cache of the class name that DataTables has applied to the row, so we
+ * can quickly look at this variable rather than needing to do a DOM check
+ * on className for the nTr property.
+ * @type string
+ * @default <i>Empty string</i>
+ * @private
+ */
+ "_sRowStripe": "",
+
+ /**
+ * Denote if the original data source was from the DOM, or the data source
+ * object. This is used for invalidating data, so DataTables can
+ * automatically read data from the original source, unless uninstructed
+ * otherwise.
+ * @type string
+ * @default null
+ * @private
+ */
+ "src": null,
+
+ /**
+ * Index in the aoData array. This saves an indexOf lookup when we have the
+ * object, but want to know the index
+ * @type integer
+ * @default -1
+ * @private
+ */
+ "idx": -1
+ };
+
+
+ /**
+ * Template object for the column information object in DataTables. This object
+ * is held in the settings aoColumns array and contains all the information that
+ * DataTables needs about each individual column.
+ *
+ * Note that this object is related to {@link DataTable.defaults.column}
+ * but this one is the internal data store for DataTables's cache of columns.
+ * It should NOT be manipulated outside of DataTables. Any configuration should
+ * be done through the initialisation options.
+ * @namespace
+ */
+ DataTable.models.oColumn = {
+ /**
+ * Column index. This could be worked out on-the-fly with $.inArray, but it
+ * is faster to just hold it as a variable
+ * @type integer
+ * @default null
+ */
+ "idx": null,
+
+ /**
+ * A list of the columns that sorting should occur on when this column
+ * is sorted. That this property is an array allows multi-column sorting
+ * to be defined for a column (for example first name / last name columns
+ * would benefit from this). The values are integers pointing to the
+ * columns to be sorted on (typically it will be a single integer pointing
+ * at itself, but that doesn't need to be the case).
+ * @type array
+ */
+ "aDataSort": null,
+
+ /**
+ * Define the sorting directions that are applied to the column, in sequence
+ * as the column is repeatedly sorted upon - i.e. the first value is used
+ * as the sorting direction when the column if first sorted (clicked on).
+ * Sort it again (click again) and it will move on to the next index.
+ * Repeat until loop.
+ * @type array
+ */
+ "asSorting": null,
+
+ /**
+ * Flag to indicate if the column is searchable, and thus should be included
+ * in the filtering or not.
+ * @type boolean
+ */
+ "bSearchable": null,
+
+ /**
+ * Flag to indicate if the column is sortable or not.
+ * @type boolean
+ */
+ "bSortable": null,
+
+ /**
+ * Flag to indicate if the column is currently visible in the table or not
+ * @type boolean
+ */
+ "bVisible": null,
+
+ /**
+ * Store for manual type assignment using the `column.type` option. This
+ * is held in store so we can manipulate the column's `sType` property.
+ * @type string
+ * @default null
+ * @private
+ */
+ "_sManualType": null,
+
+ /**
+ * Flag to indicate if HTML5 data attributes should be used as the data
+ * source for filtering or sorting. True is either are.
+ * @type boolean
+ * @default false
+ * @private
+ */
+ "_bAttrSrc": false,
+
+ /**
+ * Developer definable function that is called whenever a cell is created (Ajax source,
+ * etc) or processed for input (DOM source). This can be used as a compliment to mRender
+ * allowing you to modify the DOM element (add background colour for example) when the
+ * element is available.
+ * @type function
+ * @param {element} nTd The TD node that has been created
+ * @param {*} sData The Data for the cell
+ * @param {array|object} oData The data for the whole row
+ * @param {int} iRow The row index for the aoData data store
+ * @default null
+ */
+ "fnCreatedCell": null,
+
+ /**
+ * Function to get data from a cell in a column. You should <b>never</b>
+ * access data directly through _aData internally in DataTables - always use
+ * the method attached to this property. It allows mData to function as
+ * required. This function is automatically assigned by the column
+ * initialisation method
+ * @type function
+ * @param {array|object} oData The data array/object for the array
+ * (i.e. aoData[]._aData)
+ * @param {string} sSpecific The specific data type you want to get -
+ * 'display', 'type' 'filter' 'sort'
+ * @returns {*} The data for the cell from the given row's data
+ * @default null
+ */
+ "fnGetData": null,
+
+ /**
+ * Function to set data for a cell in the column. You should <b>never</b>
+ * set the data directly to _aData internally in DataTables - always use
+ * this method. It allows mData to function as required. This function
+ * is automatically assigned by the column initialisation method
+ * @type function
+ * @param {array|object} oData The data array/object for the array
+ * (i.e. aoData[]._aData)
+ * @param {*} sValue Value to set
+ * @default null
+ */
+ "fnSetData": null,
+
+ /**
+ * Property to read the value for the cells in the column from the data
+ * source array / object. If null, then the default content is used, if a
+ * function is given then the return from the function is used.
+ * @type function|int|string|null
+ * @default null
+ */
+ "mData": null,
+
+ /**
+ * Partner property to mData which is used (only when defined) to get
+ * the data - i.e. it is basically the same as mData, but without the
+ * 'set' option, and also the data fed to it is the result from mData.
+ * This is the rendering method to match the data method of mData.
+ * @type function|int|string|null
+ * @default null
+ */
+ "mRender": null,
+
+ /**
+ * Unique header TH/TD element for this column - this is what the sorting
+ * listener is attached to (if sorting is enabled.)
+ * @type node
+ * @default null
+ */
+ "nTh": null,
+
+ /**
+ * Unique footer TH/TD element for this column (if there is one). Not used
+ * in DataTables as such, but can be used for plug-ins to reference the
+ * footer for each column.
+ * @type node
+ * @default null
+ */
+ "nTf": null,
+
+ /**
+ * The class to apply to all TD elements in the table's TBODY for the column
+ * @type string
+ * @default null
+ */
+ "sClass": null,
+
+ /**
+ * When DataTables calculates the column widths to assign to each column,
+ * it finds the longest string in each column and then constructs a
+ * temporary table and reads the widths from that. The problem with this
+ * is that "mmm" is much wider then "iiii", but the latter is a longer
+ * string - thus the calculation can go wrong (doing it properly and putting
+ * it into an DOM object and measuring that is horribly(!) slow). Thus as
+ * a "work around" we provide this option. It will append its value to the
+ * text that is found to be the longest string for the column - i.e. padding.
+ * @type string
+ */
+ "sContentPadding": null,
+
+ /**
+ * Allows a default value to be given for a column's data, and will be used
+ * whenever a null data source is encountered (this can be because mData
+ * is set to null, or because the data source itself is null).
+ * @type string
+ * @default null
+ */
+ "sDefaultContent": null,
+
+ /**
+ * Name for the column, allowing reference to the column by name as well as
+ * by index (needs a lookup to work by name).
+ * @type string
+ */
+ "sName": null,
+
+ /**
+ * Custom sorting data type - defines which of the available plug-ins in
+ * afnSortData the custom sorting will use - if any is defined.
+ * @type string
+ * @default std
+ */
+ "sSortDataType": 'std',
+
+ /**
+ * Class to be applied to the header element when sorting on this column
+ * @type string
+ * @default null
+ */
+ "sSortingClass": null,
+
+ /**
+ * Class to be applied to the header element when sorting on this column -
+ * when jQuery UI theming is used.
+ * @type string
+ * @default null
+ */
+ "sSortingClassJUI": null,
+
+ /**
+ * Title of the column - what is seen in the TH element (nTh).
+ * @type string
+ */
+ "sTitle": null,
+
+ /**
+ * Column sorting and filtering type
+ * @type string
+ * @default null
+ */
+ "sType": null,
+
+ /**
+ * Width of the column
+ * @type string
+ * @default null
+ */
+ "sWidth": null,
+
+ /**
+ * Width of the column when it was first "encountered"
+ * @type string
+ * @default null
+ */
+ "sWidthOrig": null
+ };
+
+
+ /*
+ * Developer note: The properties of the object below are given in Hungarian
+ * notation, that was used as the interface for DataTables prior to v1.10, however
+ * from v1.10 onwards the primary interface is camel case. In order to avoid
+ * breaking backwards compatibility utterly with this change, the Hungarian
+ * version is still, internally the primary interface, but is is not documented
+ * - hence the @name tags in each doc comment. This allows a Javascript function
+ * to create a map from Hungarian notation to camel case (going the other direction
+ * would require each property to be listed, which would at around 3K to the size
+ * of DataTables, while this method is about a 0.5K hit.
+ *
+ * Ultimately this does pave the way for Hungarian notation to be dropped
+ * completely, but that is a massive amount of work and will break current
+ * installs (therefore is on-hold until v2).
+ */
+
+ /**
+ * Initialisation options that can be given to DataTables at initialisation
+ * time.
+ * @namespace
+ */
+ DataTable.defaults = {
+ /**
+ * An array of data to use for the table, passed in at initialisation which
+ * will be used in preference to any data which is already in the DOM. This is
+ * particularly useful for constructing tables purely in Javascript, for
+ * example with a custom Ajax call.
+ * @type array
+ * @default null
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.data
+ *
+ * @example
+ * // Using a 2D array data source
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "data": [
+ * ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
+ * ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
+ * ],
+ * "columns": [
+ * { "title": "Engine" },
+ * { "title": "Browser" },
+ * { "title": "Platform" },
+ * { "title": "Version" },
+ * { "title": "Grade" }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using an array of objects as a data source (`data`)
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "data": [
+ * {
+ * "engine": "Trident",
+ * "browser": "Internet Explorer 4.0",
+ * "platform": "Win 95+",
+ * "version": 4,
+ * "grade": "X"
+ * },
+ * {
+ * "engine": "Trident",
+ * "browser": "Internet Explorer 5.0",
+ * "platform": "Win 95+",
+ * "version": 5,
+ * "grade": "C"
+ * }
+ * ],
+ * "columns": [
+ * { "title": "Engine", "data": "engine" },
+ * { "title": "Browser", "data": "browser" },
+ * { "title": "Platform", "data": "platform" },
+ * { "title": "Version", "data": "version" },
+ * { "title": "Grade", "data": "grade" }
+ * ]
+ * } );
+ * } );
+ */
+ "aaData": null,
+
+
+ /**
+ * If ordering is enabled, then DataTables will perform a first pass sort on
+ * initialisation. You can define which column(s) the sort is performed
+ * upon, and the sorting direction, with this variable. The `sorting` array
+ * should contain an array for each column to be sorted initially containing
+ * the column's index and a direction string ('asc' or 'desc').
+ * @type array
+ * @default [[0,'asc']]
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.order
+ *
+ * @example
+ * // Sort by 3rd column first, and then 4th column
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "order": [[2,'asc'], [3,'desc']]
+ * } );
+ * } );
+ *
+ * // No initial sorting
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "order": []
+ * } );
+ * } );
+ */
+ "aaSorting": [[0,'asc']],
+
+
+ /**
+ * This parameter is basically identical to the `sorting` parameter, but
+ * cannot be overridden by user interaction with the table. What this means
+ * is that you could have a column (visible or hidden) which the sorting
+ * will always be forced on first - any sorting after that (from the user)
+ * will then be performed as required. This can be useful for grouping rows
+ * together.
+ * @type array
+ * @default null
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.orderFixed
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "orderFixed": [[0,'asc']]
+ * } );
+ * } )
+ */
+ "aaSortingFixed": [],
+
+
+ /**
+ * DataTables can be instructed to load data to display in the table from a
+ * Ajax source. This option defines how that Ajax call is made and where to.
+ *
+ * The `ajax` property has three different modes of operation, depending on
+ * how it is defined. These are:
+ *
+ * * `string` - Set the URL from where the data should be loaded from.
+ * * `object` - Define properties for `jQuery.ajax`.
+ * * `function` - Custom data get function
+ *
+ * `string`
+ * --------
+ *
+ * As a string, the `ajax` property simply defines the URL from which
+ * DataTables will load data.
+ *
+ * `object`
+ * --------
+ *
+ * As an object, the parameters in the object are passed to
+ * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
+ * of the Ajax request. DataTables has a number of default parameters which
+ * you can override using this option. Please refer to the jQuery
+ * documentation for a full description of the options available, although
+ * the following parameters provide additional options in DataTables or
+ * require special consideration:
+ *
+ * * `data` - As with jQuery, `data` can be provided as an object, but it
+ * can also be used as a function to manipulate the data DataTables sends
+ * to the server. The function takes a single parameter, an object of
+ * parameters with the values that DataTables has readied for sending. An
+ * object may be returned which will be merged into the DataTables
+ * defaults, or you can add the items to the object that was passed in and
+ * not return anything from the function. This supersedes `fnServerParams`
+ * from DataTables 1.9-.
+ *
+ * * `dataSrc` - By default DataTables will look for the property `data` (or
+ * `aaData` for compatibility with DataTables 1.9-) when obtaining data
+ * from an Ajax source or for server-side processing - this parameter
+ * allows that property to be changed. You can use Javascript dotted
+ * object notation to get a data source for multiple levels of nesting, or
+ * it my be used as a function. As a function it takes a single parameter,
+ * the JSON returned from the server, which can be manipulated as
+ * required, with the returned value being that used by DataTables as the
+ * data source for the table. This supersedes `sAjaxDataProp` from
+ * DataTables 1.9-.
+ *
+ * * `success` - Should not be overridden it is used internally in
+ * DataTables. To manipulate / transform the data returned by the server
+ * use `ajax.dataSrc`, or use `ajax` as a function (see below).
+ *
+ * `function`
+ * ----------
+ *
+ * As a function, making the Ajax call is left up to yourself allowing
+ * complete control of the Ajax request. Indeed, if desired, a method other
+ * than Ajax could be used to obtain the required data, such as Web storage
+ * or an AIR database.
+ *
+ * The function is given four parameters and no return is required. The
+ * parameters are:
+ *
+ * 1. _object_ - Data to send to the server
+ * 2. _function_ - Callback function that must be executed when the required
+ * data has been obtained. That data should be passed into the callback
+ * as the only parameter
+ * 3. _object_ - DataTables settings object for the table
+ *
+ * Note that this supersedes `fnServerData` from DataTables 1.9-.
+ *
+ * @type string|object|function
+ * @default null
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.ajax
+ * @since 1.10.0
+ *
+ * @example
+ * // Get JSON data from a file via Ajax.
+ * // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
+ * $('#example').dataTable( {
+ * "ajax": "data.json"
+ * } );
+ *
+ * @example
+ * // Get JSON data from a file via Ajax, using `dataSrc` to change
+ * // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": "tableData"
+ * }
+ * } );
+ *
+ * @example
+ * // Get JSON data from a file via Ajax, using `dataSrc` to read data
+ * // from a plain array rather than an array in an object
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": ""
+ * }
+ * } );
+ *
+ * @example
+ * // Manipulate the data returned from the server - add a link to data
+ * // (note this can, should, be done using `render` for the column - this
+ * // is just a simple example of how the data can be manipulated).
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": function ( json ) {
+ * for ( var i=0, ien=json.length ; i<ien ; i++ ) {
+ * json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
+ * }
+ * return json;
+ * }
+ * }
+ * } );
+ *
+ * @example
+ * // Add data to the request
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "data": function ( d ) {
+ * return {
+ * "extra_search": $('#extra').val()
+ * };
+ * }
+ * }
+ * } );
+ *
+ * @example
+ * // Send request as POST
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "type": "POST"
+ * }
+ * } );
+ *
+ * @example
+ * // Get the data from localStorage (could interface with a form for
+ * // adding, editing and removing rows).
+ * $('#example').dataTable( {
+ * "ajax": function (data, callback, settings) {
+ * callback(
+ * JSON.parse( localStorage.getItem('dataTablesData') )
+ * );
+ * }
+ * } );
+ */
+ "ajax": null,
+
+
+ /**
+ * This parameter allows you to readily specify the entries in the length drop
+ * down menu that DataTables shows when pagination is enabled. It can be
+ * either a 1D array of options which will be used for both the displayed
+ * option and the value, or a 2D array which will use the array in the first
+ * position as the value, and the array in the second position as the
+ * displayed options (useful for language strings such as 'All').
+ *
+ * Note that the `pageLength` property will be automatically set to the
+ * first value given in this array, unless `pageLength` is also provided.
+ * @type array
+ * @default [ 10, 25, 50, 100 ]
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.lengthMenu
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
+ * } );
+ * } );
+ */
+ "aLengthMenu": [ 10, 25, 50, 100 ],
+
+
+ /**
+ * The `columns` option in the initialisation parameter allows you to define
+ * details about the way individual columns behave. For a full list of
+ * column options that can be set, please see
+ * {@link DataTable.defaults.column}. Note that if you use `columns` to
+ * define your columns, you must have an entry in the array for every single
+ * column that you have in your table (these can be null if you don't which
+ * to specify any options).
+ * @member
+ *
+ * @name DataTable.defaults.column
+ */
+ "aoColumns": null,
+
+ /**
+ * Very similar to `columns`, `columnDefs` allows you to target a specific
+ * column, multiple columns, or all columns, using the `targets` property of
+ * each object in the array. This allows great flexibility when creating
+ * tables, as the `columnDefs` arrays can be of any length, targeting the
+ * columns you specifically want. `columnDefs` may use any of the column
+ * options available: {@link DataTable.defaults.column}, but it _must_
+ * have `targets` defined in each object in the array. Values in the `targets`
+ * array may be:
+ * <ul>
+ * <li>a string - class name will be matched on the TH for the column</li>
+ * <li>0 or a positive integer - column index counting from the left</li>
+ * <li>a negative integer - column index counting from the right</li>
+ * <li>the string "_all" - all columns (i.e. assign a default)</li>
+ * </ul>
+ * @member
+ *
+ * @name DataTable.defaults.columnDefs
+ */
+ "aoColumnDefs": null,
+
+
+ /**
+ * Basically the same as `search`, this parameter defines the individual column
+ * filtering state at initialisation time. The array must be of the same size
+ * as the number of columns, and each element be an object with the parameters
+ * `search` and `escapeRegex` (the latter is optional). 'null' is also
+ * accepted and the default will be used.
+ * @type array
+ * @default []
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.searchCols
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "searchCols": [
+ * null,
+ * { "search": "My filter" },
+ * null,
+ * { "search": "^[0-9]", "escapeRegex": false }
+ * ]
+ * } );
+ * } )
+ */
+ "aoSearchCols": [],
+
+
+ /**
+ * An array of CSS classes that should be applied to displayed rows. This
+ * array may be of any length, and DataTables will apply each class
+ * sequentially, looping when required.
+ * @type array
+ * @default null <i>Will take the values determined by the `oClasses.stripe*`
+ * options</i>
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.stripeClasses
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
+ * } );
+ * } )
+ */
+ "asStripeClasses": null,
+
+
+ /**
+ * Enable or disable automatic column width calculation. This can be disabled
+ * as an optimisation (it takes some time to calculate the widths) if the
+ * tables widths are passed in using `columns`.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.autoWidth
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "autoWidth": false
+ * } );
+ * } );
+ */
+ "bAutoWidth": true,
+
+
+ /**
+ * Deferred rendering can provide DataTables with a huge speed boost when you
+ * are using an Ajax or JS data source for the table. This option, when set to
+ * true, will cause DataTables to defer the creation of the table elements for
+ * each row until they are needed for a draw - saving a significant amount of
+ * time.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.deferRender
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "ajax": "sources/arrays.txt",
+ * "deferRender": true
+ * } );
+ * } );
+ */
+ "bDeferRender": false,
+
+
+ /**
+ * Replace a DataTable which matches the given selector and replace it with
+ * one which has the properties of the new initialisation object passed. If no
+ * table matches the selector, then the new DataTable will be constructed as
+ * per normal.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.destroy
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "srollY": "200px",
+ * "paginate": false
+ * } );
+ *
+ * // Some time later....
+ * $('#example').dataTable( {
+ * "filter": false,
+ * "destroy": true
+ * } );
+ * } );
+ */
+ "bDestroy": false,
+
+
+ /**
+ * Enable or disable filtering of data. Filtering in DataTables is "smart" in
+ * that it allows the end user to input multiple words (space separated) and
+ * will match a row containing those words, even if not in the order that was
+ * specified (this allow matching across multiple columns). Note that if you
+ * wish to use filtering in DataTables this must remain 'true' - to remove the
+ * default filtering input box and retain filtering abilities, please use
+ * {@link DataTable.defaults.dom}.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.searching
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "searching": false
+ * } );
+ * } );
+ */
+ "bFilter": true,
+
+
+ /**
+ * Enable or disable the table information display. This shows information
+ * about the data that is currently visible on the page, including information
+ * about filtered data if that action is being performed.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.info
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "info": false
+ * } );
+ * } );
+ */
+ "bInfo": true,
+
+
+ /**
+ * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
+ * slightly different and additional mark-up from what DataTables has
+ * traditionally used).
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.jQueryUI
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "jQueryUI": true
+ * } );
+ * } );
+ */
+ "bJQueryUI": false,
+
+
+ /**
+ * Allows the end user to select the size of a formatted page from a select
+ * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.lengthChange
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "lengthChange": false
+ * } );
+ * } );
+ */
+ "bLengthChange": true,
+
+
+ /**
+ * Enable or disable pagination.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.paging
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "paging": false
+ * } );
+ * } );
+ */
+ "bPaginate": true,
+
+
+ /**
+ * Enable or disable the display of a 'processing' indicator when the table is
+ * being processed (e.g. a sort). This is particularly useful for tables with
+ * large amounts of data where it can take a noticeable amount of time to sort
+ * the entries.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.processing
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "processing": true
+ * } );
+ * } );
+ */
+ "bProcessing": false,
+
+
+ /**
+ * Retrieve the DataTables object for the given selector. Note that if the
+ * table has already been initialised, this parameter will cause DataTables
+ * to simply return the object that has already been set up - it will not take
+ * account of any changes you might have made to the initialisation object
+ * passed to DataTables (setting this parameter to true is an acknowledgement
+ * that you understand this). `destroy` can be used to reinitialise a table if
+ * you need.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.retrieve
+ *
+ * @example
+ * $(document).ready( function() {
+ * initTable();
+ * tableActions();
+ * } );
+ *
+ * function initTable ()
+ * {
+ * return $('#example').dataTable( {
+ * "scrollY": "200px",
+ * "paginate": false,
+ * "retrieve": true
+ * } );
+ * }
+ *
+ * function tableActions ()
+ * {
+ * var table = initTable();
+ * // perform API operations with oTable
+ * }
+ */
+ "bRetrieve": false,
+
+
+ /**
+ * When vertical (y) scrolling is enabled, DataTables will force the height of
+ * the table's viewport to the given height at all times (useful for layout).
+ * However, this can look odd when filtering data down to a small data set,
+ * and the footer is left "floating" further down. This parameter (when
+ * enabled) will cause DataTables to collapse the table's viewport down when
+ * the result set will fit within the given Y height.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.scrollCollapse
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "scrollY": "200",
+ * "scrollCollapse": true
+ * } );
+ * } );
+ */
+ "bScrollCollapse": false,
+
+
+ /**
+ * Configure DataTables to use server-side processing. Note that the
+ * `ajax` parameter must also be given in order to give DataTables a
+ * source to obtain the required data for each draw.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Features
+ * @dtopt Server-side
+ * @name DataTable.defaults.serverSide
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "serverSide": true,
+ * "ajax": "xhr.php"
+ * } );
+ * } );
+ */
+ "bServerSide": false,
+
+
+ /**
+ * Enable or disable sorting of columns. Sorting of individual columns can be
+ * disabled by the `sortable` option for each column.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.ordering
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "ordering": false
+ * } );
+ * } );
+ */
+ "bSort": true,
+
+
+ /**
+ * Enable or display DataTables' ability to sort multiple columns at the
+ * same time (activated by shift-click by the user).
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.orderMulti
+ *
+ * @example
+ * // Disable multiple column sorting ability
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "orderMulti": false
+ * } );
+ * } );
+ */
+ "bSortMulti": true,
+
+
+ /**
+ * Allows control over whether DataTables should use the top (true) unique
+ * cell that is found for a single column, or the bottom (false - default).
+ * This is useful when using complex headers.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.orderCellsTop
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "orderCellsTop": true
+ * } );
+ * } );
+ */
+ "bSortCellsTop": false,
+
+
+ /**
+ * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
+ * `sorting\_3` to the columns which are currently being sorted on. This is
+ * presented as a feature switch as it can increase processing time (while
+ * classes are removed and added) so for large data sets you might want to
+ * turn this off.
+ * @type boolean
+ * @default true
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.orderClasses
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "orderClasses": false
+ * } );
+ * } );
+ */
+ "bSortClasses": true,
+
+
+ /**
+ * Enable or disable state saving. When enabled HTML5 `localStorage` will be
+ * used to save table display information such as pagination information,
+ * display length, filtering and sorting. As such when the end user reloads
+ * the page the display display will match what thy had previously set up.
+ *
+ * Due to the use of `localStorage` the default state saving is not supported
+ * in IE6 or 7. If state saving is required in those browsers, use
+ * `stateSaveCallback` to provide a storage solution such as cookies.
+ * @type boolean
+ * @default false
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.stateSave
+ *
+ * @example
+ * $(document).ready( function () {
+ * $('#example').dataTable( {
+ * "stateSave": true
+ * } );
+ * } );
+ */
+ "bStateSave": false,
+
+
+ /**
+ * This function is called when a TR element is created (and all TD child
+ * elements have been inserted), or registered if using a DOM source, allowing
+ * manipulation of the TR element (adding classes etc).
+ * @type function
+ * @param {node} row "TR" element for the current row
+ * @param {array} data Raw data array for this row
+ * @param {int} dataIndex The index of this row in the internal aoData array
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.createdRow
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "createdRow": function( row, data, dataIndex ) {
+ * // Bold the grade for all 'A' grade browsers
+ * if ( data[4] == "A" )
+ * {
+ * $('td:eq(4)', row).html( '<b>A</b>' );
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "fnCreatedRow": null,
+
+
+ /**
+ * This function is called on every 'draw' event, and allows you to
+ * dynamically modify any aspect you want about the created DOM.
+ * @type function
+ * @param {object} settings DataTables settings object
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.drawCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "drawCallback": function( settings ) {
+ * alert( 'DataTables has redrawn the table' );
+ * }
+ * } );
+ * } );
+ */
+ "fnDrawCallback": null,
+
+
+ /**
+ * Identical to fnHeaderCallback() but for the table footer this function
+ * allows you to modify the table footer on every 'draw' event.
+ * @type function
+ * @param {node} foot "TR" element for the footer
+ * @param {array} data Full table data (as derived from the original HTML)
+ * @param {int} start Index for the current display starting point in the
+ * display array
+ * @param {int} end Index for the current display ending point in the
+ * display array
+ * @param {array int} display Index array to translate the visual position
+ * to the full data array
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.footerCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "footerCallback": function( tfoot, data, start, end, display ) {
+ * tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
+ * }
+ * } );
+ * } )
+ */
+ "fnFooterCallback": null,
+
+
+ /**
+ * When rendering large numbers in the information element for the table
+ * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
+ * to have a comma separator for the 'thousands' units (e.g. 1 million is
+ * rendered as "1,000,000") to help readability for the end user. This
+ * function will override the default method DataTables uses.
+ * @type function
+ * @member
+ * @param {int} toFormat number to be formatted
+ * @returns {string} formatted string for DataTables to show the number
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.formatNumber
+ *
+ * @example
+ * // Format a number using a single quote for the separator (note that
+ * // this can also be done with the language.thousands option)
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "formatNumber": function ( toFormat ) {
+ * return toFormat.toString().replace(
+ * /\B(?=(\d{3})+(?!\d))/g, "'"
+ * );
+ * };
+ * } );
+ * } );
+ */
+ "fnFormatNumber": function ( toFormat ) {
+ return toFormat.toString().replace(
+ /\B(?=(\d{3})+(?!\d))/g,
+ this.oLanguage.sThousands
+ );
+ },
+
+
+ /**
+ * This function is called on every 'draw' event, and allows you to
+ * dynamically modify the header row. This can be used to calculate and
+ * display useful information about the table.
+ * @type function
+ * @param {node} head "TR" element for the header
+ * @param {array} data Full table data (as derived from the original HTML)
+ * @param {int} start Index for the current display starting point in the
+ * display array
+ * @param {int} end Index for the current display ending point in the
+ * display array
+ * @param {array int} display Index array to translate the visual position
+ * to the full data array
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.headerCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "fheaderCallback": function( head, data, start, end, display ) {
+ * head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
+ * }
+ * } );
+ * } )
+ */
+ "fnHeaderCallback": null,
+
+
+ /**
+ * The information element can be used to convey information about the current
+ * state of the table. Although the internationalisation options presented by
+ * DataTables are quite capable of dealing with most customisations, there may
+ * be times where you wish to customise the string further. This callback
+ * allows you to do exactly that.
+ * @type function
+ * @param {object} oSettings DataTables settings object
+ * @param {int} start Starting position in data for the draw
+ * @param {int} end End position in data for the draw
+ * @param {int} max Total number of rows in the table (regardless of
+ * filtering)
+ * @param {int} total Total number of rows in the data set, after filtering
+ * @param {string} pre The string that DataTables has formatted using it's
+ * own rules
+ * @returns {string} The string to be displayed in the information element.
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.infoCallback
+ *
+ * @example
+ * $('#example').dataTable( {
+ * "infoCallback": function( settings, start, end, max, total, pre ) {
+ * return start +" to "+ end;
+ * }
+ * } );
+ */
+ "fnInfoCallback": null,
+
+
+ /**
+ * Called when the table has been initialised. Normally DataTables will
+ * initialise sequentially and there will be no need for this function,
+ * however, this does not hold true when using external language information
+ * since that is obtained using an async XHR call.
+ * @type function
+ * @param {object} settings DataTables settings object
+ * @param {object} json The JSON object request from the server - only
+ * present if client-side Ajax sourced data is used
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.initComplete
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "initComplete": function(settings, json) {
+ * alert( 'DataTables has finished its initialisation.' );
+ * }
+ * } );
+ * } )
+ */
+ "fnInitComplete": null,
+
+
+ /**
+ * Called at the very start of each table draw and can be used to cancel the
+ * draw by returning false, any other return (including undefined) results in
+ * the full draw occurring).
+ * @type function
+ * @param {object} settings DataTables settings object
+ * @returns {boolean} False will cancel the draw, anything else (including no
+ * return) will allow it to complete.
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.preDrawCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "preDrawCallback": function( settings ) {
+ * if ( $('#test').val() == 1 ) {
+ * return false;
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "fnPreDrawCallback": null,
+
+
+ /**
+ * This function allows you to 'post process' each row after it have been
+ * generated for each table draw, but before it is rendered on screen. This
+ * function might be used for setting the row class name etc.
+ * @type function
+ * @param {node} row "TR" element for the current row
+ * @param {array} data Raw data array for this row
+ * @param {int} displayIndex The display index for the current table draw
+ * @param {int} displayIndexFull The index of the data in the full list of
+ * rows (after filtering)
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.rowCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
+ * // Bold the grade for all 'A' grade browsers
+ * if ( data[4] == "A" ) {
+ * $('td:eq(4)', row).html( '<b>A</b>' );
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "fnRowCallback": null,
+
+
+ /**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * This parameter allows you to override the default function which obtains
+ * the data from the server so something more suitable for your application.
+ * For example you could use POST data, or pull information from a Gears or
+ * AIR database.
+ * @type function
+ * @member
+ * @param {string} source HTTP source to obtain the data from (`ajax`)
+ * @param {array} data A key/value pair object containing the data to send
+ * to the server
+ * @param {function} callback to be called on completion of the data get
+ * process that will draw the data on the page.
+ * @param {object} settings DataTables settings object
+ *
+ * @dtopt Callbacks
+ * @dtopt Server-side
+ * @name DataTable.defaults.serverData
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "fnServerData": null,
+
+
+ /**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * It is often useful to send extra data to the server when making an Ajax
+ * request - for example custom filtering information, and this callback
+ * function makes it trivial to send extra information to the server. The
+ * passed in parameter is the data set that has been constructed by
+ * DataTables, and you can add to this or modify it as you require.
+ * @type function
+ * @param {array} data Data array (array of objects which are name/value
+ * pairs) that has been constructed by DataTables and will be sent to the
+ * server. In the case of Ajax sourced data with server-side processing
+ * this will be an empty array, for server-side processing there will be a
+ * significant number of parameters!
+ * @returns {undefined} Ensure that you modify the data array passed in,
+ * as this is passed by reference.
+ *
+ * @dtopt Callbacks
+ * @dtopt Server-side
+ * @name DataTable.defaults.serverParams
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "fnServerParams": null,
+
+
+ /**
+ * Load the table state. With this function you can define from where, and how, the
+ * state of a table is loaded. By default DataTables will load from `localStorage`
+ * but you might wish to use a server-side database or cookies.
+ * @type function
+ * @member
+ * @param {object} settings DataTables settings object
+ * @return {object} The DataTables state object to be loaded
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.stateLoadCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateLoadCallback": function (settings) {
+ * var o;
+ *
+ * // Send an Ajax request to the server to get the data. Note that
+ * // this is a synchronous request.
+ * $.ajax( {
+ * "url": "/state_load",
+ * "async": false,
+ * "dataType": "json",
+ * "success": function (json) {
+ * o = json;
+ * }
+ * } );
+ *
+ * return o;
+ * }
+ * } );
+ * } );
+ */
+ "fnStateLoadCallback": function ( settings ) {
+ try {
+ return JSON.parse(
+ (settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
+ 'DataTables_'+settings.sInstance+'_'+location.pathname
+ )
+ );
+ } catch (e) {}
+ },
+
+
+ /**
+ * Callback which allows modification of the saved state prior to loading that state.
+ * This callback is called when the table is loading state from the stored data, but
+ * prior to the settings object being modified by the saved state. Note that for
+ * plug-in authors, you should use the `stateLoadParams` event to load parameters for
+ * a plug-in.
+ * @type function
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object that is to be loaded
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.stateLoadParams
+ *
+ * @example
+ * // Remove a saved filter, so filtering is never loaded
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateLoadParams": function (settings, data) {
+ * data.oSearch.sSearch = "";
+ * }
+ * } );
+ * } );
+ *
+ * @example
+ * // Disallow state loading by returning false
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateLoadParams": function (settings, data) {
+ * return false;
+ * }
+ * } );
+ * } );
+ */
+ "fnStateLoadParams": null,
+
+
+ /**
+ * Callback that is called when the state has been loaded from the state saving method
+ * and the DataTables settings object has been modified as a result of the loaded state.
+ * @type function
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object that was loaded
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.stateLoaded
+ *
+ * @example
+ * // Show an alert with the filtering value that was saved
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateLoaded": function (settings, data) {
+ * alert( 'Saved filter was: '+data.oSearch.sSearch );
+ * }
+ * } );
+ * } );
+ */
+ "fnStateLoaded": null,
+
+
+ /**
+ * Save the table state. This function allows you to define where and how the state
+ * information for the table is stored By default DataTables will use `localStorage`
+ * but you might wish to use a server-side database or cookies.
+ * @type function
+ * @member
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object to be saved
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.stateSaveCallback
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateSaveCallback": function (settings, data) {
+ * // Send an Ajax request to the server with the state object
+ * $.ajax( {
+ * "url": "/state_save",
+ * "data": data,
+ * "dataType": "json",
+ * "method": "POST"
+ * "success": function () {}
+ * } );
+ * }
+ * } );
+ * } );
+ */
+ "fnStateSaveCallback": function ( settings, data ) {
+ try {
+ (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
+ 'DataTables_'+settings.sInstance+'_'+location.pathname,
+ JSON.stringify( data )
+ );
+ } catch (e) {}
+ },
+
+
+ /**
+ * Callback which allows modification of the state to be saved. Called when the table
+ * has changed state a new state save is required. This method allows modification of
+ * the state saving object prior to actually doing the save, including addition or
+ * other state properties or modification. Note that for plug-in authors, you should
+ * use the `stateSaveParams` event to save parameters for a plug-in.
+ * @type function
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object to be saved
+ *
+ * @dtopt Callbacks
+ * @name DataTable.defaults.stateSaveParams
+ *
+ * @example
+ * // Remove a saved filter, so filtering is never saved
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateSave": true,
+ * "stateSaveParams": function (settings, data) {
+ * data.oSearch.sSearch = "";
+ * }
+ * } );
+ * } );
+ */
+ "fnStateSaveParams": null,
+
+
+ /**
+ * Duration for which the saved state information is considered valid. After this period
+ * has elapsed the state will be returned to the default.
+ * Value is given in seconds.
+ * @type int
+ * @default 7200 <i>(2 hours)</i>
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.stateDuration
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "stateDuration": 60*60*24; // 1 day
+ * } );
+ * } )
+ */
+ "iStateDuration": 7200,
+
+
+ /**
+ * When enabled DataTables will not make a request to the server for the first
+ * page draw - rather it will use the data already on the page (no sorting etc
+ * will be applied to it), thus saving on an XHR at load time. `deferLoading`
+ * is used to indicate that deferred loading is required, but it is also used
+ * to tell DataTables how many records there are in the full table (allowing
+ * the information element and pagination to be displayed correctly). In the case
+ * where a filtering is applied to the table on initial load, this can be
+ * indicated by giving the parameter as an array, where the first element is
+ * the number of records available after filtering and the second element is the
+ * number of records without filtering (allowing the table information element
+ * to be shown correctly).
+ * @type int | array
+ * @default null
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.deferLoading
+ *
+ * @example
+ * // 57 records available in the table, no filtering applied
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "serverSide": true,
+ * "ajax": "scripts/server_processing.php",
+ * "deferLoading": 57
+ * } );
+ * } );
+ *
+ * @example
+ * // 57 records after filtering, 100 without filtering (an initial filter applied)
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "serverSide": true,
+ * "ajax": "scripts/server_processing.php",
+ * "deferLoading": [ 57, 100 ],
+ * "search": {
+ * "search": "my_filter"
+ * }
+ * } );
+ * } );
+ */
+ "iDeferLoading": null,
+
+
+ /**
+ * Number of rows to display on a single page when using pagination. If
+ * feature enabled (`lengthChange`) then the end user will be able to override
+ * this to a custom setting using a pop-up menu.
+ * @type int
+ * @default 10
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.pageLength
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "pageLength": 50
+ * } );
+ * } )
+ */
+ "iDisplayLength": 10,
+
+
+ /**
+ * Define the starting point for data display when using DataTables with
+ * pagination. Note that this parameter is the number of records, rather than
+ * the page number, so if you have 10 records per page and want to start on
+ * the third page, it should be "20".
+ * @type int
+ * @default 0
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.displayStart
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "displayStart": 20
+ * } );
+ * } )
+ */
+ "iDisplayStart": 0,
+
+
+ /**
+ * By default DataTables allows keyboard navigation of the table (sorting, paging,
+ * and filtering) by adding a `tabindex` attribute to the required elements. This
+ * allows you to tab through the controls and press the enter key to activate them.
+ * The tabindex is default 0, meaning that the tab follows the flow of the document.
+ * You can overrule this using this parameter if you wish. Use a value of -1 to
+ * disable built-in keyboard navigation.
+ * @type int
+ * @default 0
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.tabIndex
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "tabIndex": 1
+ * } );
+ * } );
+ */
+ "iTabIndex": 0,
+
+
+ /**
+ * Classes that DataTables assigns to the various components and features
+ * that it adds to the HTML table. This allows classes to be configured
+ * during initialisation in addition to through the static
+ * {@link DataTable.ext.oStdClasses} object).
+ * @namespace
+ * @name DataTable.defaults.classes
+ */
+ "oClasses": {},
+
+
+ /**
+ * All strings that DataTables uses in the user interface that it creates
+ * are defined in this object, allowing you to modified them individually or
+ * completely replace them all as required.
+ * @namespace
+ * @name DataTable.defaults.language
+ */
+ "oLanguage": {
+ /**
+ * Strings that are used for WAI-ARIA labels and controls only (these are not
+ * actually visible on the page, but will be read by screenreaders, and thus
+ * must be internationalised as well).
+ * @namespace
+ * @name DataTable.defaults.language.aria
+ */
+ "oAria": {
+ /**
+ * ARIA label that is added to the table headers when the column may be
+ * sorted ascending by activing the column (click or return when focused).
+ * Note that the column header is prefixed to this string.
+ * @type string
+ * @default : activate to sort column ascending
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.aria.sortAscending
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "aria": {
+ * "sortAscending": " - click/return to sort ascending"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sSortAscending": ": activate to sort column ascending",
+
+ /**
+ * ARIA label that is added to the table headers when the column may be
+ * sorted descending by activing the column (click or return when focused).
+ * Note that the column header is prefixed to this string.
+ * @type string
+ * @default : activate to sort column ascending
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.aria.sortDescending
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "aria": {
+ * "sortDescending": " - click/return to sort descending"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sSortDescending": ": activate to sort column descending"
+ },
+
+ /**
+ * Pagination string used by DataTables for the built-in pagination
+ * control types.
+ * @namespace
+ * @name DataTable.defaults.language.paginate
+ */
+ "oPaginate": {
+ /**
+ * Text to use when using the 'full_numbers' type of pagination for the
+ * button to take the user to the first page.
+ * @type string
+ * @default First
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.paginate.first
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "paginate": {
+ * "first": "First page"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sFirst": "First",
+
+
+ /**
+ * Text to use when using the 'full_numbers' type of pagination for the
+ * button to take the user to the last page.
+ * @type string
+ * @default Last
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.paginate.last
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "paginate": {
+ * "last": "Last page"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sLast": "Last",
+
+
+ /**
+ * Text to use for the 'next' pagination button (to take the user to the
+ * next page).
+ * @type string
+ * @default Next
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.paginate.next
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "paginate": {
+ * "next": "Next page"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sNext": "Next",
+
+
+ /**
+ * Text to use for the 'previous' pagination button (to take the user to
+ * the previous page).
+ * @type string
+ * @default Previous
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.paginate.previous
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "paginate": {
+ * "previous": "Previous page"
+ * }
+ * }
+ * } );
+ * } );
+ */
+ "sPrevious": "Previous"
+ },
+
+ /**
+ * This string is shown in preference to `zeroRecords` when the table is
+ * empty of data (regardless of filtering). Note that this is an optional
+ * parameter - if it is not given, the value of `zeroRecords` will be used
+ * instead (either the default or given value).
+ * @type string
+ * @default No data available in table
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.emptyTable
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "emptyTable": "No data available in table"
+ * }
+ * } );
+ * } );
+ */
+ "sEmptyTable": "No data available in table",
+
+
+ /**
+ * This string gives information to the end user about the information
+ * that is current on display on the page. The following tokens can be
+ * used in the string and will be dynamically replaced as the table
+ * display updates. This tokens can be placed anywhere in the string, or
+ * removed as needed by the language requires:
+ *
+ * * `\_START\_` - Display index of the first record on the current page
+ * * `\_END\_` - Display index of the last record on the current page
+ * * `\_TOTAL\_` - Number of records in the table after filtering
+ * * `\_MAX\_` - Number of records in the table without filtering
+ * * `\_PAGE\_` - Current page number
+ * * `\_PAGES\_` - Total number of pages of data in the table
+ *
+ * @type string
+ * @default Showing _START_ to _END_ of _TOTAL_ entries
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.info
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "info": "Showing page _PAGE_ of _PAGES_"
+ * }
+ * } );
+ * } );
+ */
+ "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
+
+
+ /**
+ * Display information string for when the table is empty. Typically the
+ * format of this string should match `info`.
+ * @type string
+ * @default Showing 0 to 0 of 0 entries
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.infoEmpty
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "infoEmpty": "No entries to show"
+ * }
+ * } );
+ * } );
+ */
+ "sInfoEmpty": "Showing 0 to 0 of 0 entries",
+
+
+ /**
+ * When a user filters the information in a table, this string is appended
+ * to the information (`info`) to give an idea of how strong the filtering
+ * is. The variable _MAX_ is dynamically updated.
+ * @type string
+ * @default (filtered from _MAX_ total entries)
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.infoFiltered
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "infoFiltered": " - filtering from _MAX_ records"
+ * }
+ * } );
+ * } );
+ */
+ "sInfoFiltered": "(filtered from _MAX_ total entries)",
+
+
+ /**
+ * If can be useful to append extra information to the info string at times,
+ * and this variable does exactly that. This information will be appended to
+ * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
+ * being used) at all times.
+ * @type string
+ * @default <i>Empty string</i>
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.infoPostFix
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "infoPostFix": "All records shown are derived from real information."
+ * }
+ * } );
+ * } );
+ */
+ "sInfoPostFix": "",
+
+
+ /**
+ * This decimal place operator is a little different from the other
+ * language options since DataTables doesn't output floating point
+ * numbers, so it won't ever use this for display of a number. Rather,
+ * what this parameter does is modify the sort methods of the table so
+ * that numbers which are in a format which has a character other than
+ * a period (`.`) as a decimal place will be sorted numerically.
+ *
+ * Note that numbers with different decimal places cannot be shown in
+ * the same table and still be sortable, the table must be consistent.
+ * However, multiple different tables on the page can use different
+ * decimal place characters.
+ * @type string
+ * @default
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.decimal
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "decimal": ","
+ * "thousands": "."
+ * }
+ * } );
+ * } );
+ */
+ "sDecimal": "",
+
+
+ /**
+ * DataTables has a build in number formatter (`formatNumber`) which is
+ * used to format large numbers that are used in the table information.
+ * By default a comma is used, but this can be trivially changed to any
+ * character you wish with this parameter.
+ * @type string
+ * @default ,
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.thousands
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "thousands": "'"
+ * }
+ * } );
+ * } );
+ */
+ "sThousands": ",",
+
+
+ /**
+ * Detail the action that will be taken when the drop down menu for the
+ * pagination length option is changed. The '_MENU_' variable is replaced
+ * with a default select list of 10, 25, 50 and 100, and can be replaced
+ * with a custom select box if required.
+ * @type string
+ * @default Show _MENU_ entries
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.lengthMenu
+ *
+ * @example
+ * // Language change only
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "lengthMenu": "Display _MENU_ records"
+ * }
+ * } );
+ * } );
+ *
+ * @example
+ * // Language and options change
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "lengthMenu": 'Display <select>'+
+ * '<option value="10">10</option>'+
+ * '<option value="20">20</option>'+
+ * '<option value="30">30</option>'+
+ * '<option value="40">40</option>'+
+ * '<option value="50">50</option>'+
+ * '<option value="-1">All</option>'+
+ * '</select> records'
+ * }
+ * } );
+ * } );
+ */
+ "sLengthMenu": "Show _MENU_ entries",
+
+
+ /**
+ * When using Ajax sourced data and during the first draw when DataTables is
+ * gathering the data, this message is shown in an empty row in the table to
+ * indicate to the end user the the data is being loaded. Note that this
+ * parameter is not used when loading data by server-side processing, just
+ * Ajax sourced data with client-side processing.
+ * @type string
+ * @default Loading...
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.loadingRecords
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "loadingRecords": "Please wait - loading..."
+ * }
+ * } );
+ * } );
+ */
+ "sLoadingRecords": "Loading...",
+
+
+ /**
+ * Text which is displayed when the table is processing a user action
+ * (usually a sort command or similar).
+ * @type string
+ * @default Processing...
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.processing
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "processing": "DataTables is currently busy"
+ * }
+ * } );
+ * } );
+ */
+ "sProcessing": "Processing...",
+
+
+ /**
+ * Details the actions that will be taken when the user types into the
+ * filtering input text box. The variable "_INPUT_", if used in the string,
+ * is replaced with the HTML text box for the filtering input allowing
+ * control over where it appears in the string. If "_INPUT_" is not given
+ * then the input box is appended to the string automatically.
+ * @type string
+ * @default Search:
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.search
+ *
+ * @example
+ * // Input text box will be appended at the end automatically
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "search": "Filter records:"
+ * }
+ * } );
+ * } );
+ *
+ * @example
+ * // Specify where the filter should appear
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "search": "Apply filter _INPUT_ to table"
+ * }
+ * } );
+ * } );
+ */
+ "sSearch": "Search:",
+
+
+ /**
+ * Assign a `placeholder` attribute to the search `input` element
+ * @type string
+ * @default
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.searchPlaceholder
+ */
+ "sSearchPlaceholder": "",
+
+
+ /**
+ * All of the language information can be stored in a file on the
+ * server-side, which DataTables will look up if this parameter is passed.
+ * It must store the URL of the language file, which is in a JSON format,
+ * and the object has the same properties as the oLanguage object in the
+ * initialiser object (i.e. the above parameters). Please refer to one of
+ * the example language files to see how this works in action.
+ * @type string
+ * @default <i>Empty string - i.e. disabled</i>
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.url
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
+ * }
+ * } );
+ * } );
+ */
+ "sUrl": "",
+
+
+ /**
+ * Text shown inside the table records when the is no information to be
+ * displayed after filtering. `emptyTable` is shown when there is simply no
+ * information in the table at all (regardless of filtering).
+ * @type string
+ * @default No matching records found
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.zeroRecords
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "zeroRecords": "No records to display"
+ * }
+ * } );
+ * } );
+ */
+ "sZeroRecords": "No matching records found"
+ },
+
+
+ /**
+ * This parameter allows you to have define the global filtering state at
+ * initialisation time. As an object the `search` parameter must be
+ * defined, but all other parameters are optional. When `regex` is true,
+ * the search string will be treated as a regular expression, when false
+ * (default) it will be treated as a straight string. When `smart`
+ * DataTables will use it's smart filtering methods (to word match at
+ * any point in the data), when false this will not be done.
+ * @namespace
+ * @extends DataTable.models.oSearch
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.search
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "search": {"search": "Initial search"}
+ * } );
+ * } )
+ */
+ "oSearch": $.extend( {}, DataTable.models.oSearch ),
+
+
+ /**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * By default DataTables will look for the property `data` (or `aaData` for
+ * compatibility with DataTables 1.9-) when obtaining data from an Ajax
+ * source or for server-side processing - this parameter allows that
+ * property to be changed. You can use Javascript dotted object notation to
+ * get a data source for multiple levels of nesting.
+ * @type string
+ * @default data
+ *
+ * @dtopt Options
+ * @dtopt Server-side
+ * @name DataTable.defaults.ajaxDataProp
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "sAjaxDataProp": "data",
+
+
+ /**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * You can instruct DataTables to load data from an external
+ * source using this parameter (use aData if you want to pass data in you
+ * already have). Simply provide a url a JSON object can be obtained from.
+ * @type string
+ * @default null
+ *
+ * @dtopt Options
+ * @dtopt Server-side
+ * @name DataTable.defaults.ajaxSource
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "sAjaxSource": null,
+
+
+ /**
+ * This initialisation variable allows you to specify exactly where in the
+ * DOM you want DataTables to inject the various controls it adds to the page
+ * (for example you might want the pagination controls at the top of the
+ * table). DIV elements (with or without a custom class) can also be added to
+ * aid styling. The follow syntax is used:
+ * <ul>
+ * <li>The following options are allowed:
+ * <ul>
+ * <li>'l' - Length changing</li>
+ * <li>'f' - Filtering input</li>
+ * <li>'t' - The table!</li>
+ * <li>'i' - Information</li>
+ * <li>'p' - Pagination</li>
+ * <li>'r' - pRocessing</li>
+ * </ul>
+ * </li>
+ * <li>The following constants are allowed:
+ * <ul>
+ * <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
+ * <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
+ * </ul>
+ * </li>
+ * <li>The following syntax is expected:
+ * <ul>
+ * <li>'&lt;' and '&gt;' - div elements</li>
+ * <li>'&lt;"class" and '&gt;' - div with a class</li>
+ * <li>'&lt;"#id" and '&gt;' - div with an ID</li>
+ * </ul>
+ * </li>
+ * <li>Examples:
+ * <ul>
+ * <li>'&lt;"wrapper"flipt&gt;'</li>
+ * <li>'&lt;lf&lt;t&gt;ip&gt;'</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * @type string
+ * @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
+ * <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.dom
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
+ * } );
+ * } );
+ */
+ "sDom": "lfrtip",
+
+
+ /**
+ * Search delay option. This will throttle full table searches that use the
+ * DataTables provided search input element (it does not effect calls to
+ * `dt-api search()`, providing a delay before the search is made.
+ * @type integer
+ * @default 0
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.searchDelay
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "searchDelay": 200
+ * } );
+ * } )
+ */
+ "searchDelay": null,
+
+
+ /**
+ * DataTables features four different built-in options for the buttons to
+ * display for pagination control:
+ *
+ * * `simple` - 'Previous' and 'Next' buttons only
+ * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
+ * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
+ * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus
+ * page numbers
+ *
+ * Further methods can be added using {@link DataTable.ext.oPagination}.
+ * @type string
+ * @default simple_numbers
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.pagingType
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "pagingType": "full_numbers"
+ * } );
+ * } )
+ */
+ "sPaginationType": "simple_numbers",
+
+
+ /**
+ * Enable horizontal scrolling. When a table is too wide to fit into a
+ * certain layout, or you have a large number of columns in the table, you
+ * can enable x-scrolling to show the table in a viewport, which can be
+ * scrolled. This property can be `true` which will allow the table to
+ * scroll horizontally when needed, or any CSS unit, or a number (in which
+ * case it will be treated as a pixel measurement). Setting as simply `true`
+ * is recommended.
+ * @type boolean|string
+ * @default <i>blank string - i.e. disabled</i>
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.scrollX
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "scrollX": true,
+ * "scrollCollapse": true
+ * } );
+ * } );
+ */
+ "sScrollX": "",
+
+
+ /**
+ * This property can be used to force a DataTable to use more width than it
+ * might otherwise do when x-scrolling is enabled. For example if you have a
+ * table which requires to be well spaced, this parameter is useful for
+ * "over-sizing" the table, and thus forcing scrolling. This property can by
+ * any CSS unit, or a number (in which case it will be treated as a pixel
+ * measurement).
+ * @type string
+ * @default <i>blank string - i.e. disabled</i>
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.scrollXInner
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "scrollX": "100%",
+ * "scrollXInner": "110%"
+ * } );
+ * } );
+ */
+ "sScrollXInner": "",
+
+
+ /**
+ * Enable vertical scrolling. Vertical scrolling will constrain the DataTable
+ * to the given height, and enable scrolling for any data which overflows the
+ * current viewport. This can be used as an alternative to paging to display
+ * a lot of data in a small area (although paging and scrolling can both be
+ * enabled at the same time). This property can be any CSS unit, or a number
+ * (in which case it will be treated as a pixel measurement).
+ * @type string
+ * @default <i>blank string - i.e. disabled</i>
+ *
+ * @dtopt Features
+ * @name DataTable.defaults.scrollY
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "scrollY": "200px",
+ * "paginate": false
+ * } );
+ * } );
+ */
+ "sScrollY": "",
+
+
+ /**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * Set the HTTP method that is used to make the Ajax call for server-side
+ * processing or Ajax sourced data.
+ * @type string
+ * @default GET
+ *
+ * @dtopt Options
+ * @dtopt Server-side
+ * @name DataTable.defaults.serverMethod
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "sServerMethod": "GET",
+
+
+ /**
+ * DataTables makes use of renderers when displaying HTML elements for
+ * a table. These renderers can be added or modified by plug-ins to
+ * generate suitable mark-up for a site. For example the Bootstrap
+ * integration plug-in for DataTables uses a paging button renderer to
+ * display pagination buttons in the mark-up required by Bootstrap.
+ *
+ * For further information about the renderers available see
+ * DataTable.ext.renderer
+ * @type string|object
+ * @default null
+ *
+ * @name DataTable.defaults.renderer
+ *
+ */
+ "renderer": null,
+
+
+ /**
+ * Set the data property name that DataTables should use to get a row's id
+ * to set as the `id` property in the node.
+ * @type string
+ * @default DT_RowId
+ *
+ * @name DataTable.defaults.rowId
+ */
+ "rowId": "DT_RowId"
+ };
+
+ _fnHungarianMap( DataTable.defaults );
+
+
+
+ /*
+ * Developer note - See note in model.defaults.js about the use of Hungarian
+ * notation and camel case.
+ */
+
+ /**
+ * Column options that can be given to DataTables at initialisation time.
+ * @namespace
+ */
+ DataTable.defaults.column = {
+ /**
+ * Define which column(s) an order will occur on for this column. This
+ * allows a column's ordering to take multiple columns into account when
+ * doing a sort or use the data from a different column. For example first
+ * name / last name columns make sense to do a multi-column sort over the
+ * two columns.
+ * @type array|int
+ * @default null <i>Takes the value of the column index automatically</i>
+ *
+ * @name DataTable.defaults.column.orderData
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "orderData": [ 0, 1 ], "targets": [ 0 ] },
+ * { "orderData": [ 1, 0 ], "targets": [ 1 ] },
+ * { "orderData": 2, "targets": [ 2 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "orderData": [ 0, 1 ] },
+ * { "orderData": [ 1, 0 ] },
+ * { "orderData": 2 },
+ * null,
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "aDataSort": null,
+ "iDataSort": -1,
+
+
+ /**
+ * You can control the default ordering direction, and even alter the
+ * behaviour of the sort handler (i.e. only allow ascending ordering etc)
+ * using this parameter.
+ * @type array
+ * @default [ 'asc', 'desc' ]
+ *
+ * @name DataTable.defaults.column.orderSequence
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "orderSequence": [ "asc" ], "targets": [ 1 ] },
+ * { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
+ * { "orderSequence": [ "desc" ], "targets": [ 3 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * null,
+ * { "orderSequence": [ "asc" ] },
+ * { "orderSequence": [ "desc", "asc", "asc" ] },
+ * { "orderSequence": [ "desc" ] },
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "asSorting": [ 'asc', 'desc' ],
+
+
+ /**
+ * Enable or disable filtering on the data in this column.
+ * @type boolean
+ * @default true
+ *
+ * @name DataTable.defaults.column.searchable
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "searchable": false, "targets": [ 0 ] }
+ * ] } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "searchable": false },
+ * null,
+ * null,
+ * null,
+ * null
+ * ] } );
+ * } );
+ */
+ "bSearchable": true,
+
+
+ /**
+ * Enable or disable ordering on this column.
+ * @type boolean
+ * @default true
+ *
+ * @name DataTable.defaults.column.orderable
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "orderable": false, "targets": [ 0 ] }
+ * ] } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "orderable": false },
+ * null,
+ * null,
+ * null,
+ * null
+ * ] } );
+ * } );
+ */
+ "bSortable": true,
+
+
+ /**
+ * Enable or disable the display of this column.
+ * @type boolean
+ * @default true
+ *
+ * @name DataTable.defaults.column.visible
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "visible": false, "targets": [ 0 ] }
+ * ] } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "visible": false },
+ * null,
+ * null,
+ * null,
+ * null
+ * ] } );
+ * } );
+ */
+ "bVisible": true,
+
+
+ /**
+ * Developer definable function that is called whenever a cell is created (Ajax source,
+ * etc) or processed for input (DOM source). This can be used as a compliment to mRender
+ * allowing you to modify the DOM element (add background colour for example) when the
+ * element is available.
+ * @type function
+ * @param {element} td The TD node that has been created
+ * @param {*} cellData The Data for the cell
+ * @param {array|object} rowData The data for the whole row
+ * @param {int} row The row index for the aoData data store
+ * @param {int} col The column index for aoColumns
+ *
+ * @name DataTable.defaults.column.createdCell
+ * @dtopt Columns
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [3],
+ * "createdCell": function (td, cellData, rowData, row, col) {
+ * if ( cellData == "1.7" ) {
+ * $(td).css('color', 'blue')
+ * }
+ * }
+ * } ]
+ * });
+ * } );
+ */
+ "fnCreatedCell": null,
+
+
+ /**
+ * This parameter has been replaced by `data` in DataTables to ensure naming
+ * consistency. `dataProp` can still be used, as there is backwards
+ * compatibility in DataTables for this option, but it is strongly
+ * recommended that you use `data` in preference to `dataProp`.
+ * @name DataTable.defaults.column.dataProp
+ */
+
+
+ /**
+ * This property can be used to read data from any data source property,
+ * including deeply nested objects / properties. `data` can be given in a
+ * number of different ways which effect its behaviour:
+ *
+ * * `integer` - treated as an array index for the data source. This is the
+ * default that DataTables uses (incrementally increased for each column).
+ * * `string` - read an object property from the data source. There are
+ * three 'special' options that can be used in the string to alter how
+ * DataTables reads the data from the source object:
+ * * `.` - Dotted Javascript notation. Just as you use a `.` in
+ * Javascript to read from nested objects, so to can the options
+ * specified in `data`. For example: `browser.version` or
+ * `browser.name`. If your object parameter name contains a period, use
+ * `\\` to escape it - i.e. `first\\.name`.
+ * * `[]` - Array notation. DataTables can automatically combine data
+ * from and array source, joining the data with the characters provided
+ * between the two brackets. For example: `name[, ]` would provide a
+ * comma-space separated list from the source array. If no characters
+ * are provided between the brackets, the original array source is
+ * returned.
+ * * `()` - Function notation. Adding `()` to the end of a parameter will
+ * execute a function of the name given. For example: `browser()` for a
+ * simple function on the data source, `browser.version()` for a
+ * function in a nested property or even `browser().version` to get an
+ * object property if the function called returns an object. Note that
+ * function notation is recommended for use in `render` rather than
+ * `data` as it is much simpler to use as a renderer.
+ * * `null` - use the original data source for the row rather than plucking
+ * data directly from it. This action has effects on two other
+ * initialisation options:
+ * * `defaultContent` - When null is given as the `data` option and
+ * `defaultContent` is specified for the column, the value defined by
+ * `defaultContent` will be used for the cell.
+ * * `render` - When null is used for the `data` option and the `render`
+ * option is specified for the column, the whole data source for the
+ * row is used for the renderer.
+ * * `function` - the function given will be executed whenever DataTables
+ * needs to set or get the data for a cell in the column. The function
+ * takes three parameters:
+ * * Parameters:
+ * * `{array|object}` The data source for the row
+ * * `{string}` The type call data requested - this will be 'set' when
+ * setting data or 'filter', 'display', 'type', 'sort' or undefined
+ * when gathering data. Note that when `undefined` is given for the
+ * type DataTables expects to get the raw data for the object back<
+ * * `{*}` Data to set when the second parameter is 'set'.
+ * * Return:
+ * * The return value from the function is not required when 'set' is
+ * the type of call, but otherwise the return is what will be used
+ * for the data requested.
+ *
+ * Note that `data` is a getter and setter option. If you just require
+ * formatting of data for output, you will likely want to use `render` which
+ * is simply a getter and thus simpler to use.
+ *
+ * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
+ * name change reflects the flexibility of this property and is consistent
+ * with the naming of mRender. If 'mDataProp' is given, then it will still
+ * be used by DataTables, as it automatically maps the old name to the new
+ * if required.
+ *
+ * @type string|int|function|null
+ * @default null <i>Use automatically calculated column index</i>
+ *
+ * @name DataTable.defaults.column.data
+ * @dtopt Columns
+ *
+ * @example
+ * // Read table data from objects
+ * // JSON structure for each row:
+ * // {
+ * // "engine": {value},
+ * // "browser": {value},
+ * // "platform": {value},
+ * // "version": {value},
+ * // "grade": {value}
+ * // }
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "ajaxSource": "sources/objects.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
+ * { "data": "platform" },
+ * { "data": "version" },
+ * { "data": "grade" }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Read information from deeply nested objects
+ * // JSON structure for each row:
+ * // {
+ * // "engine": {value},
+ * // "browser": {value},
+ * // "platform": {
+ * // "inner": {value}
+ * // },
+ * // "details": [
+ * // {value}, {value}
+ * // ]
+ * // }
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "ajaxSource": "sources/deep.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
+ * { "data": "platform.inner" },
+ * { "data": "platform.details.0" },
+ * { "data": "platform.details.1" }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `data` as a function to provide different information for
+ * // sorting, filtering and display. In this case, currency (price)
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": function ( source, type, val ) {
+ * if (type === 'set') {
+ * source.price = val;
+ * // Store the computed dislay and filter values for efficiency
+ * source.price_display = val=="" ? "" : "$"+numberFormat(val);
+ * source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val;
+ * return;
+ * }
+ * else if (type === 'display') {
+ * return source.price_display;
+ * }
+ * else if (type === 'filter') {
+ * return source.price_filter;
+ * }
+ * // 'sort', 'type' and undefined all just use the integer
+ * return source.price;
+ * }
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using default content
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null,
+ * "defaultContent": "Click to edit"
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using array notation - outputting a list from an array
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": "name[, ]"
+ * } ]
+ * } );
+ * } );
+ *
+ */
+ "mData": null,
+
+
+ /**
+ * This property is the rendering partner to `data` and it is suggested that
+ * when you want to manipulate data for display (including filtering,
+ * sorting etc) without altering the underlying data for the table, use this
+ * property. `render` can be considered to be the the read only companion to
+ * `data` which is read / write (then as such more complex). Like `data`
+ * this option can be given in a number of different ways to effect its
+ * behaviour:
+ *
+ * * `integer` - treated as an array index for the data source. This is the
+ * default that DataTables uses (incrementally increased for each column).
+ * * `string` - read an object property from the data source. There are
+ * three 'special' options that can be used in the string to alter how
+ * DataTables reads the data from the source object:
+ * * `.` - Dotted Javascript notation. Just as you use a `.` in
+ * Javascript to read from nested objects, so to can the options
+ * specified in `data`. For example: `browser.version` or
+ * `browser.name`. If your object parameter name contains a period, use
+ * `\\` to escape it - i.e. `first\\.name`.
+ * * `[]` - Array notation. DataTables can automatically combine data
+ * from and array source, joining the data with the characters provided
+ * between the two brackets. For example: `name[, ]` would provide a
+ * comma-space separated list from the source array. If no characters
+ * are provided between the brackets, the original array source is
+ * returned.
+ * * `()` - Function notation. Adding `()` to the end of a parameter will
+ * execute a function of the name given. For example: `browser()` for a
+ * simple function on the data source, `browser.version()` for a
+ * function in a nested property or even `browser().version` to get an
+ * object property if the function called returns an object.
+ * * `object` - use different data for the different data types requested by
+ * DataTables ('filter', 'display', 'type' or 'sort'). The property names
+ * of the object is the data type the property refers to and the value can
+ * defined using an integer, string or function using the same rules as
+ * `render` normally does. Note that an `_` option _must_ be specified.
+ * This is the default value to use if you haven't specified a value for
+ * the data type requested by DataTables.
+ * * `function` - the function given will be executed whenever DataTables
+ * needs to set or get the data for a cell in the column. The function
+ * takes three parameters:
+ * * Parameters:
+ * * {array|object} The data source for the row (based on `data`)
+ * * {string} The type call data requested - this will be 'filter',
+ * 'display', 'type' or 'sort'.
+ * * {array|object} The full data source for the row (not based on
+ * `data`)
+ * * Return:
+ * * The return value from the function is what will be used for the
+ * data requested.
+ *
+ * @type string|int|function|object|null
+ * @default null Use the data source value.
+ *
+ * @name DataTable.defaults.column.render
+ * @dtopt Columns
+ *
+ * @example
+ * // Create a comma separated list from an array of objects
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "ajaxSource": "sources/deep.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
+ * {
+ * "data": "platform",
+ * "render": "[, ].name"
+ * }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Execute a function to obtain data
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null, // Use the full data source object for the renderer's source
+ * "render": "browserName()"
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // As an object, extracting different data for the different types
+ * // This would be used with a data source such as:
+ * // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
+ * // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
+ * // (which has both forms) is used for filtering for if a user inputs either format, while
+ * // the formatted phone number is the one that is shown in the table.
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null, // Use the full data source object for the renderer's source
+ * "render": {
+ * "_": "phone",
+ * "filter": "phone_filter",
+ * "display": "phone_display"
+ * }
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Use as a function to create a link from the data source
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": "download_link",
+ * "render": function ( data, type, full ) {
+ * return '<a href="'+data+'">Download</a>';
+ * }
+ * } ]
+ * } );
+ * } );
+ */
+ "mRender": null,
+
+
+ /**
+ * Change the cell type created for the column - either TD cells or TH cells. This
+ * can be useful as TH cells have semantic meaning in the table body, allowing them
+ * to act as a header for a row (you may wish to add scope='row' to the TH elements).
+ * @type string
+ * @default td
+ *
+ * @name DataTable.defaults.column.cellType
+ * @dtopt Columns
+ *
+ * @example
+ * // Make the first column use TH cells
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "cellType": "th"
+ * } ]
+ * } );
+ * } );
+ */
+ "sCellType": "td",
+
+
+ /**
+ * Class to give to each cell in this column.
+ * @type string
+ * @default <i>Empty string</i>
+ *
+ * @name DataTable.defaults.column.class
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "class": "my_class", "targets": [ 0 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "class": "my_class" },
+ * null,
+ * null,
+ * null,
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "sClass": "",
+
+ /**
+ * When DataTables calculates the column widths to assign to each column,
+ * it finds the longest string in each column and then constructs a
+ * temporary table and reads the widths from that. The problem with this
+ * is that "mmm" is much wider then "iiii", but the latter is a longer
+ * string - thus the calculation can go wrong (doing it properly and putting
+ * it into an DOM object and measuring that is horribly(!) slow). Thus as
+ * a "work around" we provide this option. It will append its value to the
+ * text that is found to be the longest string for the column - i.e. padding.
+ * Generally you shouldn't need this!
+ * @type string
+ * @default <i>Empty string<i>
+ *
+ * @name DataTable.defaults.column.contentPadding
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * null,
+ * null,
+ * null,
+ * {
+ * "contentPadding": "mmm"
+ * }
+ * ]
+ * } );
+ * } );
+ */
+ "sContentPadding": "",
+
+
+ /**
+ * Allows a default value to be given for a column's data, and will be used
+ * whenever a null data source is encountered (this can be because `data`
+ * is set to null, or because the data source itself is null).
+ * @type string
+ * @default null
+ *
+ * @name DataTable.defaults.column.defaultContent
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * {
+ * "data": null,
+ * "defaultContent": "Edit",
+ * "targets": [ -1 ]
+ * }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * null,
+ * null,
+ * null,
+ * {
+ * "data": null,
+ * "defaultContent": "Edit"
+ * }
+ * ]
+ * } );
+ * } );
+ */
+ "sDefaultContent": null,
+
+
+ /**
+ * This parameter is only used in DataTables' server-side processing. It can
+ * be exceptionally useful to know what columns are being displayed on the
+ * client side, and to map these to database fields. When defined, the names
+ * also allow DataTables to reorder information from the server if it comes
+ * back in an unexpected order (i.e. if you switch your columns around on the
+ * client-side, your server-side code does not also need updating).
+ * @type string
+ * @default <i>Empty string</i>
+ *
+ * @name DataTable.defaults.column.name
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "name": "engine", "targets": [ 0 ] },
+ * { "name": "browser", "targets": [ 1 ] },
+ * { "name": "platform", "targets": [ 2 ] },
+ * { "name": "version", "targets": [ 3 ] },
+ * { "name": "grade", "targets": [ 4 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "name": "engine" },
+ * { "name": "browser" },
+ * { "name": "platform" },
+ * { "name": "version" },
+ * { "name": "grade" }
+ * ]
+ * } );
+ * } );
+ */
+ "sName": "",
+
+
+ /**
+ * Defines a data source type for the ordering which can be used to read
+ * real-time information from the table (updating the internally cached
+ * version) prior to ordering. This allows ordering to occur on user
+ * editable elements such as form inputs.
+ * @type string
+ * @default std
+ *
+ * @name DataTable.defaults.column.orderDataType
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
+ * { "type": "numeric", "targets": [ 3 ] },
+ * { "orderDataType": "dom-select", "targets": [ 4 ] },
+ * { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * null,
+ * null,
+ * { "orderDataType": "dom-text" },
+ * { "orderDataType": "dom-text", "type": "numeric" },
+ * { "orderDataType": "dom-select" },
+ * { "orderDataType": "dom-checkbox" }
+ * ]
+ * } );
+ * } );
+ */
+ "sSortDataType": "std",
+
+
+ /**
+ * The title of this column.
+ * @type string
+ * @default null <i>Derived from the 'TH' value for this column in the
+ * original HTML table.</i>
+ *
+ * @name DataTable.defaults.column.title
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "title": "My column title", "targets": [ 0 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "title": "My column title" },
+ * null,
+ * null,
+ * null,
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "sTitle": null,
+
+
+ /**
+ * The type allows you to specify how the data for this column will be
+ * ordered. Four types (string, numeric, date and html (which will strip
+ * HTML tags before ordering)) are currently available. Note that only date
+ * formats understood by Javascript's Date() object will be accepted as type
+ * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
+ * 'numeric', 'date' or 'html' (by default). Further types can be adding
+ * through plug-ins.
+ * @type string
+ * @default null <i>Auto-detected from raw data</i>
+ *
+ * @name DataTable.defaults.column.type
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "type": "html", "targets": [ 0 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "type": "html" },
+ * null,
+ * null,
+ * null,
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "sType": null,
+
+
+ /**
+ * Defining the width of the column, this parameter may take any CSS value
+ * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
+ * been given a specific width through this interface ensuring that the table
+ * remains readable.
+ * @type string
+ * @default null <i>Automatic</i>
+ *
+ * @name DataTable.defaults.column.width
+ * @dtopt Columns
+ *
+ * @example
+ * // Using `columnDefs`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [
+ * { "width": "20%", "targets": [ 0 ] }
+ * ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using `columns`
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columns": [
+ * { "width": "20%" },
+ * null,
+ * null,
+ * null,
+ * null
+ * ]
+ * } );
+ * } );
+ */
+ "sWidth": null
+ };
+
+ _fnHungarianMap( DataTable.defaults.column );
+
+
+
+ /**
+ * DataTables settings object - this holds all the information needed for a
+ * given table, including configuration, data and current application of the
+ * table options. DataTables does not have a single instance for each DataTable
+ * with the settings attached to that instance, but rather instances of the
+ * DataTable "class" are created on-the-fly as needed (typically by a
+ * $().dataTable() call) and the settings object is then applied to that
+ * instance.
+ *
+ * Note that this object is related to {@link DataTable.defaults} but this
+ * one is the internal data store for DataTables's cache of columns. It should
+ * NOT be manipulated outside of DataTables. Any configuration should be done
+ * through the initialisation options.
+ * @namespace
+ * @todo Really should attach the settings object to individual instances so we
+ * don't need to create new instances on each $().dataTable() call (if the
+ * table already exists). It would also save passing oSettings around and
+ * into every single function. However, this is a very significant
+ * architecture change for DataTables and will almost certainly break
+ * backwards compatibility with older installations. This is something that
+ * will be done in 2.0.
+ */
+ DataTable.models.oSettings = {
+ /**
+ * Primary features of DataTables and their enablement state.
+ * @namespace
+ */
+ "oFeatures": {
+
+ /**
+ * Flag to say if DataTables should automatically try to calculate the
+ * optimum table and columns widths (true) or not (false).
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bAutoWidth": null,
+
+ /**
+ * Delay the creation of TR and TD elements until they are actually
+ * needed by a driven page draw. This can give a significant speed
+ * increase for Ajax source and Javascript source data, but makes no
+ * difference at all fro DOM and server-side processing tables.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bDeferRender": null,
+
+ /**
+ * Enable filtering on the table or not. Note that if this is disabled
+ * then there is no filtering at all on the table, including fnFilter.
+ * To just remove the filtering input use sDom and remove the 'f' option.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bFilter": null,
+
+ /**
+ * Table information element (the 'Showing x of y records' div) enable
+ * flag.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bInfo": null,
+
+ /**
+ * Present a user control allowing the end user to change the page size
+ * when pagination is enabled.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bLengthChange": null,
+
+ /**
+ * Pagination enabled or not. Note that if this is disabled then length
+ * changing must also be disabled.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bPaginate": null,
+
+ /**
+ * Processing indicator enable flag whenever DataTables is enacting a
+ * user request - typically an Ajax request for server-side processing.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bProcessing": null,
+
+ /**
+ * Server-side processing enabled flag - when enabled DataTables will
+ * get all data from the server for every draw - there is no filtering,
+ * sorting or paging done on the client-side.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bServerSide": null,
+
+ /**
+ * Sorting enablement flag.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bSort": null,
+
+ /**
+ * Multi-column sorting
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bSortMulti": null,
+
+ /**
+ * Apply a class to the columns which are being sorted to provide a
+ * visual highlight or not. This can slow things down when enabled since
+ * there is a lot of DOM interaction.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bSortClasses": null,
+
+ /**
+ * State saving enablement flag.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bStateSave": null
+ },
+
+
+ /**
+ * Scrolling settings for a table.
+ * @namespace
+ */
+ "oScroll": {
+ /**
+ * When the table is shorter in height than sScrollY, collapse the
+ * table container down to the height of the table (when true).
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bCollapse": null,
+
+ /**
+ * Width of the scrollbar for the web-browser's platform. Calculated
+ * during table initialisation.
+ * @type int
+ * @default 0
+ */
+ "iBarWidth": 0,
+
+ /**
+ * Viewport width for horizontal scrolling. Horizontal scrolling is
+ * disabled if an empty string.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ */
+ "sX": null,
+
+ /**
+ * Width to expand the table to when using x-scrolling. Typically you
+ * should not need to use this.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ * @deprecated
+ */
+ "sXInner": null,
+
+ /**
+ * Viewport height for vertical scrolling. Vertical scrolling is disabled
+ * if an empty string.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ */
+ "sY": null
+ },
+
+ /**
+ * Language information for the table.
+ * @namespace
+ * @extends DataTable.defaults.oLanguage
+ */
+ "oLanguage": {
+ /**
+ * Information callback function. See
+ * {@link DataTable.defaults.fnInfoCallback}
+ * @type function
+ * @default null
+ */
+ "fnInfoCallback": null
+ },
+
+ /**
+ * Browser support parameters
+ * @namespace
+ */
+ "oBrowser": {
+ /**
+ * Indicate if the browser incorrectly calculates width:100% inside a
+ * scrolling element (IE6/7)
+ * @type boolean
+ * @default false
+ */
+ "bScrollOversize": false,
+
+ /**
+ * Determine if the vertical scrollbar is on the right or left of the
+ * scrolling container - needed for rtl language layout, although not
+ * all browsers move the scrollbar (Safari).
+ * @type boolean
+ * @default false
+ */
+ "bScrollbarLeft": false,
+
+ /**
+ * Flag for if `getBoundingClientRect` is fully supported or not
+ * @type boolean
+ * @default false
+ */
+ "bBounding": false,
+
+ /**
+ * Browser scrollbar width
+ * @type integer
+ * @default 0
+ */
+ "barWidth": 0
+ },
+
+
+ "ajax": null,
+
+
+ /**
+ * Array referencing the nodes which are used for the features. The
+ * parameters of this object match what is allowed by sDom - i.e.
+ * <ul>
+ * <li>'l' - Length changing</li>
+ * <li>'f' - Filtering input</li>
+ * <li>'t' - The table!</li>
+ * <li>'i' - Information</li>
+ * <li>'p' - Pagination</li>
+ * <li>'r' - pRocessing</li>
+ * </ul>
+ * @type array
+ * @default []
+ */
+ "aanFeatures": [],
+
+ /**
+ * Store data information - see {@link DataTable.models.oRow} for detailed
+ * information.
+ * @type array
+ * @default []
+ */
+ "aoData": [],
+
+ /**
+ * Array of indexes which are in the current display (after filtering etc)
+ * @type array
+ * @default []
+ */
+ "aiDisplay": [],
+
+ /**
+ * Array of indexes for display - no filtering
+ * @type array
+ * @default []
+ */
+ "aiDisplayMaster": [],
+
+ /**
+ * Map of row ids to data indexes
+ * @type object
+ * @default {}
+ */
+ "aIds": {},
+
+ /**
+ * Store information about each column that is in use
+ * @type array
+ * @default []
+ */
+ "aoColumns": [],
+
+ /**
+ * Store information about the table's header
+ * @type array
+ * @default []
+ */
+ "aoHeader": [],
+
+ /**
+ * Store information about the table's footer
+ * @type array
+ * @default []
+ */
+ "aoFooter": [],
+
+ /**
+ * Store the applied global search information in case we want to force a
+ * research or compare the old search to a new one.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @namespace
+ * @extends DataTable.models.oSearch
+ */
+ "oPreviousSearch": {},
+
+ /**
+ * Store the applied search for each column - see
+ * {@link DataTable.models.oSearch} for the format that is used for the
+ * filtering information for each column.
+ * @type array
+ * @default []
+ */
+ "aoPreSearchCols": [],
+
+ /**
+ * Sorting that is applied to the table. Note that the inner arrays are
+ * used in the following manner:
+ * <ul>
+ * <li>Index 0 - column number</li>
+ * <li>Index 1 - current sorting direction</li>
+ * </ul>
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type array
+ * @todo These inner arrays should really be objects
+ */
+ "aaSorting": null,
+
+ /**
+ * Sorting that is always applied to the table (i.e. prefixed in front of
+ * aaSorting).
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type array
+ * @default []
+ */
+ "aaSortingFixed": [],
+
+ /**
+ * Classes to use for the striping of a table.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type array
+ * @default []
+ */
+ "asStripeClasses": null,
+
+ /**
+ * If restoring a table - we should restore its striping classes as well
+ * @type array
+ * @default []
+ */
+ "asDestroyStripes": [],
+
+ /**
+ * If restoring a table - we should restore its width
+ * @type int
+ * @default 0
+ */
+ "sDestroyWidth": 0,
+
+ /**
+ * Callback functions array for every time a row is inserted (i.e. on a draw).
+ * @type array
+ * @default []
+ */
+ "aoRowCallback": [],
+
+ /**
+ * Callback functions for the header on each draw.
+ * @type array
+ * @default []
+ */
+ "aoHeaderCallback": [],
+
+ /**
+ * Callback function for the footer on each draw.
+ * @type array
+ * @default []
+ */
+ "aoFooterCallback": [],
+
+ /**
+ * Array of callback functions for draw callback functions
+ * @type array
+ * @default []
+ */
+ "aoDrawCallback": [],
+
+ /**
+ * Array of callback functions for row created function
+ * @type array
+ * @default []
+ */
+ "aoRowCreatedCallback": [],
+
+ /**
+ * Callback functions for just before the table is redrawn. A return of
+ * false will be used to cancel the draw.
+ * @type array
+ * @default []
+ */
+ "aoPreDrawCallback": [],
+
+ /**
+ * Callback functions for when the table has been initialised.
+ * @type array
+ * @default []
+ */
+ "aoInitComplete": [],
+
+
+ /**
+ * Callbacks for modifying the settings to be stored for state saving, prior to
+ * saving state.
+ * @type array
+ * @default []
+ */
+ "aoStateSaveParams": [],
+
+ /**
+ * Callbacks for modifying the settings that have been stored for state saving
+ * prior to using the stored values to restore the state.
+ * @type array
+ * @default []
+ */
+ "aoStateLoadParams": [],
+
+ /**
+ * Callbacks for operating on the settings object once the saved state has been
+ * loaded
+ * @type array
+ * @default []
+ */
+ "aoStateLoaded": [],
+
+ /**
+ * Cache the table ID for quick access
+ * @type string
+ * @default <i>Empty string</i>
+ */
+ "sTableId": "",
+
+ /**
+ * The TABLE node for the main table
+ * @type node
+ * @default null
+ */
+ "nTable": null,
+
+ /**
+ * Permanent ref to the thead element
+ * @type node
+ * @default null
+ */
+ "nTHead": null,
+
+ /**
+ * Permanent ref to the tfoot element - if it exists
+ * @type node
+ * @default null
+ */
+ "nTFoot": null,
+
+ /**
+ * Permanent ref to the tbody element
+ * @type node
+ * @default null
+ */
+ "nTBody": null,
+
+ /**
+ * Cache the wrapper node (contains all DataTables controlled elements)
+ * @type node
+ * @default null
+ */
+ "nTableWrapper": null,
+
+ /**
+ * Indicate if when using server-side processing the loading of data
+ * should be deferred until the second draw.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ * @default false
+ */
+ "bDeferLoading": false,
+
+ /**
+ * Indicate if all required information has been read in
+ * @type boolean
+ * @default false
+ */
+ "bInitialised": false,
+
+ /**
+ * Information about open rows. Each object in the array has the parameters
+ * 'nTr' and 'nParent'
+ * @type array
+ * @default []
+ */
+ "aoOpenRows": [],
+
+ /**
+ * Dictate the positioning of DataTables' control elements - see
+ * {@link DataTable.model.oInit.sDom}.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ * @default null
+ */
+ "sDom": null,
+
+ /**
+ * Search delay (in mS)
+ * @type integer
+ * @default null
+ */
+ "searchDelay": null,
+
+ /**
+ * Which type of pagination should be used.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ * @default two_button
+ */
+ "sPaginationType": "two_button",
+
+ /**
+ * The state duration (for `stateSave`) in seconds.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type int
+ * @default 0
+ */
+ "iStateDuration": 0,
+
+ /**
+ * Array of callback functions for state saving. Each array element is an
+ * object with the following parameters:
+ * <ul>
+ * <li>function:fn - function to call. Takes two parameters, oSettings
+ * and the JSON string to save that has been thus far created. Returns
+ * a JSON string to be inserted into a json object
+ * (i.e. '"param": [ 0, 1, 2]')</li>
+ * <li>string:sName - name of callback</li>
+ * </ul>
+ * @type array
+ * @default []
+ */
+ "aoStateSave": [],
+
+ /**
+ * Array of callback functions for state loading. Each array element is an
+ * object with the following parameters:
+ * <ul>
+ * <li>function:fn - function to call. Takes two parameters, oSettings
+ * and the object stored. May return false to cancel state loading</li>
+ * <li>string:sName - name of callback</li>
+ * </ul>
+ * @type array
+ * @default []
+ */
+ "aoStateLoad": [],
+
+ /**
+ * State that was saved. Useful for back reference
+ * @type object
+ * @default null
+ */
+ "oSavedState": null,
+
+ /**
+ * State that was loaded. Useful for back reference
+ * @type object
+ * @default null
+ */
+ "oLoadedState": null,
+
+ /**
+ * Source url for AJAX data for the table.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ * @default null
+ */
+ "sAjaxSource": null,
+
+ /**
+ * Property from a given object from which to read the table data from. This
+ * can be an empty string (when not server-side processing), in which case
+ * it is assumed an an array is given directly.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ */
+ "sAjaxDataProp": null,
+
+ /**
+ * Note if draw should be blocked while getting data
+ * @type boolean
+ * @default true
+ */
+ "bAjaxDataGet": true,
+
+ /**
+ * The last jQuery XHR object that was used for server-side data gathering.
+ * This can be used for working with the XHR information in one of the
+ * callbacks
+ * @type object
+ * @default null
+ */
+ "jqXHR": null,
+
+ /**
+ * JSON returned from the server in the last Ajax request
+ * @type object
+ * @default undefined
+ */
+ "json": undefined,
+
+ /**
+ * Data submitted as part of the last Ajax request
+ * @type object
+ * @default undefined
+ */
+ "oAjaxData": undefined,
+
+ /**
+ * Function to get the server-side data.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type function
+ */
+ "fnServerData": null,
+
+ /**
+ * Functions which are called prior to sending an Ajax request so extra
+ * parameters can easily be sent to the server
+ * @type array
+ * @default []
+ */
+ "aoServerParams": [],
+
+ /**
+ * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
+ * required).
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type string
+ */
+ "sServerMethod": null,
+
+ /**
+ * Format numbers for display.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type function
+ */
+ "fnFormatNumber": null,
+
+ /**
+ * List of options that can be used for the user selectable length menu.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type array
+ * @default []
+ */
+ "aLengthMenu": null,
+
+ /**
+ * Counter for the draws that the table does. Also used as a tracker for
+ * server-side processing
+ * @type int
+ * @default 0
+ */
+ "iDraw": 0,
+
+ /**
+ * Indicate if a redraw is being done - useful for Ajax
+ * @type boolean
+ * @default false
+ */
+ "bDrawing": false,
+
+ /**
+ * Draw index (iDraw) of the last error when parsing the returned data
+ * @type int
+ * @default -1
+ */
+ "iDrawError": -1,
+
+ /**
+ * Paging display length
+ * @type int
+ * @default 10
+ */
+ "_iDisplayLength": 10,
+
+ /**
+ * Paging start point - aiDisplay index
+ * @type int
+ * @default 0
+ */
+ "_iDisplayStart": 0,
+
+ /**
+ * Server-side processing - number of records in the result set
+ * (i.e. before filtering), Use fnRecordsTotal rather than
+ * this property to get the value of the number of records, regardless of
+ * the server-side processing setting.
+ * @type int
+ * @default 0
+ * @private
+ */
+ "_iRecordsTotal": 0,
+
+ /**
+ * Server-side processing - number of records in the current display set
+ * (i.e. after filtering). Use fnRecordsDisplay rather than
+ * this property to get the value of the number of records, regardless of
+ * the server-side processing setting.
+ * @type boolean
+ * @default 0
+ * @private
+ */
+ "_iRecordsDisplay": 0,
+
+ /**
+ * Flag to indicate if jQuery UI marking and classes should be used.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bJUI": null,
+
+ /**
+ * The classes to use for the table
+ * @type object
+ * @default {}
+ */
+ "oClasses": {},
+
+ /**
+ * Flag attached to the settings object so you can check in the draw
+ * callback if filtering has been done in the draw. Deprecated in favour of
+ * events.
+ * @type boolean
+ * @default false
+ * @deprecated
+ */
+ "bFiltered": false,
+
+ /**
+ * Flag attached to the settings object so you can check in the draw
+ * callback if sorting has been done in the draw. Deprecated in favour of
+ * events.
+ * @type boolean
+ * @default false
+ * @deprecated
+ */
+ "bSorted": false,
+
+ /**
+ * Indicate that if multiple rows are in the header and there is more than
+ * one unique cell per column, if the top one (true) or bottom one (false)
+ * should be used for sorting / title by DataTables.
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bSortCellsTop": null,
+
+ /**
+ * Initialisation object that is used for the table
+ * @type object
+ * @default null
+ */
+ "oInit": null,
+
+ /**
+ * Destroy callback functions - for plug-ins to attach themselves to the
+ * destroy so they can clean up markup and events.
+ * @type array
+ * @default []
+ */
+ "aoDestroyCallback": [],
+
+
+ /**
+ * Get the number of records in the current record set, before filtering
+ * @type function
+ */
+ "fnRecordsTotal": function ()
+ {
+ return _fnDataSource( this ) == 'ssp' ?
+ this._iRecordsTotal * 1 :
+ this.aiDisplayMaster.length;
+ },
+
+ /**
+ * Get the number of records in the current record set, after filtering
+ * @type function
+ */
+ "fnRecordsDisplay": function ()
+ {
+ return _fnDataSource( this ) == 'ssp' ?
+ this._iRecordsDisplay * 1 :
+ this.aiDisplay.length;
+ },
+
+ /**
+ * Get the display end point - aiDisplay index
+ * @type function
+ */
+ "fnDisplayEnd": function ()
+ {
+ var
+ len = this._iDisplayLength,
+ start = this._iDisplayStart,
+ calc = start + len,
+ records = this.aiDisplay.length,
+ features = this.oFeatures,
+ paginate = features.bPaginate;
+
+ if ( features.bServerSide ) {
+ return paginate === false || len === -1 ?
+ start + records :
+ Math.min( start+len, this._iRecordsDisplay );
+ }
+ else {
+ return ! paginate || calc>records || len===-1 ?
+ records :
+ calc;
+ }
+ },
+
+ /**
+ * The DataTables object for this table
+ * @type object
+ * @default null
+ */
+ "oInstance": null,
+
+ /**
+ * Unique identifier for each instance of the DataTables object. If there
+ * is an ID on the table node, then it takes that value, otherwise an
+ * incrementing internal counter is used.
+ * @type string
+ * @default null
+ */
+ "sInstance": null,
+
+ /**
+ * tabindex attribute value that is added to DataTables control elements, allowing
+ * keyboard navigation of the table and its controls.
+ */
+ "iTabIndex": 0,
+
+ /**
+ * DIV container for the footer scrolling table if scrolling
+ */
+ "nScrollHead": null,
+
+ /**
+ * DIV container for the footer scrolling table if scrolling
+ */
+ "nScrollFoot": null,
+
+ /**
+ * Last applied sort
+ * @type array
+ * @default []
+ */
+ "aLastSort": [],
+
+ /**
+ * Stored plug-in instances
+ * @type object
+ * @default {}
+ */
+ "oPlugins": {},
+
+ /**
+ * Function used to get a row's id from the row's data
+ * @type function
+ * @default null
+ */
+ "rowIdFn": null,
+
+ /**
+ * Data location where to store a row's id
+ * @type string
+ * @default null
+ */
+ "rowId": null
+ };
+
+ /**
+ * Extension object for DataTables that is used to provide all extension
+ * options.
+ *
+ * Note that the `DataTable.ext` object is available through
+ * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
+ * also aliased to `jQuery.fn.dataTableExt` for historic reasons.
+ * @namespace
+ * @extends DataTable.models.ext
+ */
+
+
+ /**
+ * DataTables extensions
+ *
+ * This namespace acts as a collection area for plug-ins that can be used to
+ * extend DataTables capabilities. Indeed many of the build in methods
+ * use this method to provide their own capabilities (sorting methods for
+ * example).
+ *
+ * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
+ * reasons
+ *
+ * @namespace
+ */
+ DataTable.ext = _ext = {
+ /**
+ * Buttons. For use with the Buttons extension for DataTables. This is
+ * defined here so other extensions can define buttons regardless of load
+ * order. It is _not_ used by DataTables core.
+ *
+ * @type object
+ * @default {}
+ */
+ buttons: {},
+
+
+ /**
+ * Element class names
+ *
+ * @type object
+ * @default {}
+ */
+ classes: {},
+
+
+ /**
+ * DataTables build type (expanded by the download builder)
+ *
+ * @type string
+ */
+ builder: "-source-",
+
+
+ /**
+ * Error reporting.
+ *
+ * How should DataTables report an error. Can take the value 'alert',
+ * 'throw', 'none' or a function.
+ *
+ * @type string|function
+ * @default alert
+ */
+ errMode: "alert",
+
+
+ /**
+ * Feature plug-ins.
+ *
+ * This is an array of objects which describe the feature plug-ins that are
+ * available to DataTables. These feature plug-ins are then available for
+ * use through the `dom` initialisation option.
+ *
+ * Each feature plug-in is described by an object which must have the
+ * following properties:
+ *
+ * * `fnInit` - function that is used to initialise the plug-in,
+ * * `cFeature` - a character so the feature can be enabled by the `dom`
+ * instillation option. This is case sensitive.
+ *
+ * The `fnInit` function has the following input parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ *
+ * And the following return is expected:
+ *
+ * * {node|null} The element which contains your feature. Note that the
+ * return may also be void if your plug-in does not require to inject any
+ * DOM elements into DataTables control (`dom`) - for example this might
+ * be useful when developing a plug-in which allows table control via
+ * keyboard entry
+ *
+ * @type array
+ *
+ * @example
+ * $.fn.dataTable.ext.features.push( {
+ * "fnInit": function( oSettings ) {
+ * return new TableTools( { "oDTSettings": oSettings } );
+ * },
+ * "cFeature": "T"
+ * } );
+ */
+ feature: [],
+
+
+ /**
+ * Row searching.
+ *
+ * This method of searching is complimentary to the default type based
+ * searching, and a lot more comprehensive as it allows you complete control
+ * over the searching logic. Each element in this array is a function
+ * (parameters described below) that is called for every row in the table,
+ * and your logic decides if it should be included in the searching data set
+ * or not.
+ *
+ * Searching functions have the following input parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ * 2. `{array|object}` Data for the row to be processed (same as the
+ * original format that was passed in as the data source, or an array
+ * from a DOM data source
+ * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
+ * can be useful to retrieve the `TR` element if you need DOM interaction.
+ *
+ * And the following return is expected:
+ *
+ * * {boolean} Include the row in the searched result set (true) or not
+ * (false)
+ *
+ * Note that as with the main search ability in DataTables, technically this
+ * is "filtering", since it is subtractive. However, for consistency in
+ * naming we call it searching here.
+ *
+ * @type array
+ * @default []
+ *
+ * @example
+ * // The following example shows custom search being applied to the
+ * // fourth column (i.e. the data[3] index) based on two input values
+ * // from the end-user, matching the data in a certain range.
+ * $.fn.dataTable.ext.search.push(
+ * function( settings, data, dataIndex ) {
+ * var min = document.getElementById('min').value * 1;
+ * var max = document.getElementById('max').value * 1;
+ * var version = data[3] == "-" ? 0 : data[3]*1;
+ *
+ * if ( min == "" && max == "" ) {
+ * return true;
+ * }
+ * else if ( min == "" && version < max ) {
+ * return true;
+ * }
+ * else if ( min < version && "" == max ) {
+ * return true;
+ * }
+ * else if ( min < version && version < max ) {
+ * return true;
+ * }
+ * return false;
+ * }
+ * );
+ */
+ search: [],
+
+
+ /**
+ * Selector extensions
+ *
+ * The `selector` option can be used to extend the options available for the
+ * selector modifier options (`selector-modifier` object data type) that
+ * each of the three built in selector types offer (row, column and cell +
+ * their plural counterparts). For example the Select extension uses this
+ * mechanism to provide an option to select only rows, columns and cells
+ * that have been marked as selected by the end user (`{selected: true}`),
+ * which can be used in conjunction with the existing built in selector
+ * options.
+ *
+ * Each property is an array to which functions can be pushed. The functions
+ * take three attributes:
+ *
+ * * Settings object for the host table
+ * * Options object (`selector-modifier` object type)
+ * * Array of selected item indexes
+ *
+ * The return is an array of the resulting item indexes after the custom
+ * selector has been applied.
+ *
+ * @type object
+ */
+ selector: {
+ cell: [],
+ column: [],
+ row: []
+ },
+
+
+ /**
+ * Internal functions, exposed for used in plug-ins.
+ *
+ * Please note that you should not need to use the internal methods for
+ * anything other than a plug-in (and even then, try to avoid if possible).
+ * The internal function may change between releases.
+ *
+ * @type object
+ * @default {}
+ */
+ internal: {},
+
+
+ /**
+ * Legacy configuration options. Enable and disable legacy options that
+ * are available in DataTables.
+ *
+ * @type object
+ */
+ legacy: {
+ /**
+ * Enable / disable DataTables 1.9 compatible server-side processing
+ * requests
+ *
+ * @type boolean
+ * @default null
+ */
+ ajax: null
+ },
+
+
+ /**
+ * Pagination plug-in methods.
+ *
+ * Each entry in this object is a function and defines which buttons should
+ * be shown by the pagination rendering method that is used for the table:
+ * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
+ * buttons are displayed in the document, while the functions here tell it
+ * what buttons to display. This is done by returning an array of button
+ * descriptions (what each button will do).
+ *
+ * Pagination types (the four built in options and any additional plug-in
+ * options defined here) can be used through the `paginationType`
+ * initialisation parameter.
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{int} page` The current page index
+ * 2. `{int} pages` The number of pages in the table
+ *
+ * Each function is expected to return an array where each element of the
+ * array can be one of:
+ *
+ * * `first` - Jump to first page when activated
+ * * `last` - Jump to last page when activated
+ * * `previous` - Show previous page when activated
+ * * `next` - Show next page when activated
+ * * `{int}` - Show page of the index given
+ * * `{array}` - A nested array containing the above elements to add a
+ * containing 'DIV' element (might be useful for styling).
+ *
+ * Note that DataTables v1.9- used this object slightly differently whereby
+ * an object with two functions would be defined for each plug-in. That
+ * ability is still supported by DataTables 1.10+ to provide backwards
+ * compatibility, but this option of use is now decremented and no longer
+ * documented in DataTables 1.10+.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * // Show previous, next and current page buttons only
+ * $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
+ * return [ 'previous', page, 'next' ];
+ * };
+ */
+ pager: {},
+
+
+ renderer: {
+ pageButton: {},
+ header: {}
+ },
+
+
+ /**
+ * Ordering plug-ins - custom data source
+ *
+ * The extension options for ordering of data available here is complimentary
+ * to the default type based ordering that DataTables typically uses. It
+ * allows much greater control over the the data that is being used to
+ * order a column, but is necessarily therefore more complex.
+ *
+ * This type of ordering is useful if you want to do ordering based on data
+ * live from the DOM (for example the contents of an 'input' element) rather
+ * than just the static string that DataTables knows of.
+ *
+ * The way these plug-ins work is that you create an array of the values you
+ * wish to be ordering for the column in question and then return that
+ * array. The data in the array much be in the index order of the rows in
+ * the table (not the currently ordering order!). Which order data gathering
+ * function is run here depends on the `dt-init columns.orderDataType`
+ * parameter that is used for the column (if any).
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ * 2. `{int}` Target column index
+ *
+ * Each function is expected to return an array:
+ *
+ * * `{array}` Data for the column to be ordering upon
+ *
+ * @type array
+ *
+ * @example
+ * // Ordering using `input` node values
+ * $.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
+ * {
+ * return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
+ * return $('input', td).val();
+ * } );
+ * }
+ */
+ order: {},
+
+
+ /**
+ * Type based plug-ins.
+ *
+ * Each column in DataTables has a type assigned to it, either by automatic
+ * detection or by direct assignment using the `type` option for the column.
+ * The type of a column will effect how it is ordering and search (plug-ins
+ * can also make use of the column type if required).
+ *
+ * @namespace
+ */
+ type: {
+ /**
+ * Type detection functions.
+ *
+ * The functions defined in this object are used to automatically detect
+ * a column's type, making initialisation of DataTables super easy, even
+ * when complex data is in the table.
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{*}` Data from the column cell to be analysed
+ * 2. `{settings}` DataTables settings object. This can be used to
+ * perform context specific type detection - for example detection
+ * based on language settings such as using a comma for a decimal
+ * place. Generally speaking the options from the settings will not
+ * be required
+ *
+ * Each function is expected to return:
+ *
+ * * `{string|null}` Data type detected, or null if unknown (and thus
+ * pass it on to the other type detection functions.
+ *
+ * @type array
+ *
+ * @example
+ * // Currency type detection plug-in:
+ * $.fn.dataTable.ext.type.detect.push(
+ * function ( data, settings ) {
+ * // Check the numeric part
+ * if ( ! $.isNumeric( data.substring(1) ) ) {
+ * return null;
+ * }
+ *
+ * // Check prefixed by currency
+ * if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) {
+ * return 'currency';
+ * }
+ * return null;
+ * }
+ * );
+ */
+ detect: [],
+
+
+ /**
+ * Type based search formatting.
+ *
+ * The type based searching functions can be used to pre-format the
+ * data to be search on. For example, it can be used to strip HTML
+ * tags or to de-format telephone numbers for numeric only searching.
+ *
+ * Note that is a search is not defined for a column of a given type,
+ * no search formatting will be performed.
+ *
+ * Pre-processing of searching data plug-ins - When you assign the sType
+ * for a column (or have it automatically detected for you by DataTables
+ * or a type detection plug-in), you will typically be using this for
+ * custom sorting, but it can also be used to provide custom searching
+ * by allowing you to pre-processing the data and returning the data in
+ * the format that should be searched upon. This is done by adding
+ * functions this object with a parameter name which matches the sType
+ * for that target column. This is the corollary of <i>afnSortData</i>
+ * for searching data.
+ *
+ * The functions defined take a single parameter:
+ *
+ * 1. `{*}` Data from the column cell to be prepared for searching
+ *
+ * Each function is expected to return:
+ *
+ * * `{string|null}` Formatted string that will be used for the searching.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
+ * return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
+ * }
+ */
+ search: {},
+
+
+ /**
+ * Type based ordering.
+ *
+ * The column type tells DataTables what ordering to apply to the table
+ * when a column is sorted upon. The order for each type that is defined,
+ * is defined by the functions available in this object.
+ *
+ * Each ordering option can be described by three properties added to
+ * this object:
+ *
+ * * `{type}-pre` - Pre-formatting function
+ * * `{type}-asc` - Ascending order function
+ * * `{type}-desc` - Descending order function
+ *
+ * All three can be used together, only `{type}-pre` or only
+ * `{type}-asc` and `{type}-desc` together. It is generally recommended
+ * that only `{type}-pre` is used, as this provides the optimal
+ * implementation in terms of speed, although the others are provided
+ * for compatibility with existing Javascript sort functions.
+ *
+ * `{type}-pre`: Functions defined take a single parameter:
+ *
+ * 1. `{*}` Data from the column cell to be prepared for ordering
+ *
+ * And return:
+ *
+ * * `{*}` Data to be sorted upon
+ *
+ * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
+ * functions, taking two parameters:
+ *
+ * 1. `{*}` Data to compare to the second parameter
+ * 2. `{*}` Data to compare to the first parameter
+ *
+ * And returning:
+ *
+ * * `{*}` Ordering match: <0 if first parameter should be sorted lower
+ * than the second parameter, ===0 if the two parameters are equal and
+ * >0 if the first parameter should be sorted height than the second
+ * parameter.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * // Numeric ordering of formatted numbers with a pre-formatter
+ * $.extend( $.fn.dataTable.ext.type.order, {
+ * "string-pre": function(x) {
+ * a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
+ * return parseFloat( a );
+ * }
+ * } );
+ *
+ * @example
+ * // Case-sensitive string ordering, with no pre-formatting method
+ * $.extend( $.fn.dataTable.ext.order, {
+ * "string-case-asc": function(x,y) {
+ * return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ * },
+ * "string-case-desc": function(x,y) {
+ * return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ * }
+ * } );
+ */
+ order: {}
+ },
+
+ /**
+ * Unique DataTables instance counter
+ *
+ * @type int
+ * @private
+ */
+ _unique: 0,
+
+
+ //
+ // Depreciated
+ // The following properties are retained for backwards compatiblity only.
+ // The should not be used in new projects and will be removed in a future
+ // version
+ //
+
+ /**
+ * Version check function.
+ * @type function
+ * @depreciated Since 1.10
+ */
+ fnVersionCheck: DataTable.fnVersionCheck,
+
+
+ /**
+ * Index for what 'this' index API functions should use
+ * @type int
+ * @deprecated Since v1.10
+ */
+ iApiIndex: 0,
+
+
+ /**
+ * jQuery UI class container
+ * @type object
+ * @deprecated Since v1.10
+ */
+ oJUIClasses: {},
+
+
+ /**
+ * Software version
+ * @type string
+ * @deprecated Since v1.10
+ */
+ sVersion: DataTable.version
+ };
+
+
+ //
+ // Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
+ //
+ $.extend( _ext, {
+ afnFiltering: _ext.search,
+ aTypes: _ext.type.detect,
+ ofnSearch: _ext.type.search,
+ oSort: _ext.type.order,
+ afnSortData: _ext.order,
+ aoFeatures: _ext.feature,
+ oApi: _ext.internal,
+ oStdClasses: _ext.classes,
+ oPagination: _ext.pager
+ } );
+
+
+ $.extend( DataTable.ext.classes, {
+ "sTable": "dataTable",
+ "sNoFooter": "no-footer",
+
+ /* Paging buttons */
+ "sPageButton": "paginate_button",
+ "sPageButtonActive": "current",
+ "sPageButtonDisabled": "disabled",
+
+ /* Striping classes */
+ "sStripeOdd": "odd",
+ "sStripeEven": "even",
+
+ /* Empty row */
+ "sRowEmpty": "dataTables_empty",
+
+ /* Features */
+ "sWrapper": "dataTables_wrapper",
+ "sFilter": "dataTables_filter",
+ "sInfo": "dataTables_info",
+ "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
+ "sLength": "dataTables_length",
+ "sProcessing": "dataTables_processing",
+
+ /* Sorting */
+ "sSortAsc": "sorting_asc",
+ "sSortDesc": "sorting_desc",
+ "sSortable": "sorting", /* Sortable in both directions */
+ "sSortableAsc": "sorting_asc_disabled",
+ "sSortableDesc": "sorting_desc_disabled",
+ "sSortableNone": "sorting_disabled",
+ "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
+
+ /* Filtering */
+ "sFilterInput": "",
+
+ /* Page length */
+ "sLengthSelect": "",
+
+ /* Scrolling */
+ "sScrollWrapper": "dataTables_scroll",
+ "sScrollHead": "dataTables_scrollHead",
+ "sScrollHeadInner": "dataTables_scrollHeadInner",
+ "sScrollBody": "dataTables_scrollBody",
+ "sScrollFoot": "dataTables_scrollFoot",
+ "sScrollFootInner": "dataTables_scrollFootInner",
+
+ /* Misc */
+ "sHeaderTH": "",
+ "sFooterTH": "",
+
+ // Deprecated
+ "sSortJUIAsc": "",
+ "sSortJUIDesc": "",
+ "sSortJUI": "",
+ "sSortJUIAscAllowed": "",
+ "sSortJUIDescAllowed": "",
+ "sSortJUIWrapper": "",
+ "sSortIcon": "",
+ "sJUIHeader": "",
+ "sJUIFooter": ""
+ } );
+
+
+ (function() {
+
+ // Reused strings for better compression. Closure compiler appears to have a
+ // weird edge case where it is trying to expand strings rather than use the
+ // variable version. This results in about 200 bytes being added, for very
+ // little preference benefit since it this run on script load only.
+ var _empty = '';
+ _empty = '';
+
+ var _stateDefault = _empty + 'ui-state-default';
+ var _sortIcon = _empty + 'css_right ui-icon ui-icon-';
+ var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';
+
+ $.extend( DataTable.ext.oJUIClasses, DataTable.ext.classes, {
+ /* Full numbers paging buttons */
+ "sPageButton": "fg-button ui-button "+_stateDefault,
+ "sPageButtonActive": "ui-state-disabled",
+ "sPageButtonDisabled": "ui-state-disabled",
+
+ /* Features */
+ "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+
+ "ui-buttonset-multi paging_", /* Note that the type is postfixed */
+
+ /* Sorting */
+ "sSortAsc": _stateDefault+" sorting_asc",
+ "sSortDesc": _stateDefault+" sorting_desc",
+ "sSortable": _stateDefault+" sorting",
+ "sSortableAsc": _stateDefault+" sorting_asc_disabled",
+ "sSortableDesc": _stateDefault+" sorting_desc_disabled",
+ "sSortableNone": _stateDefault+" sorting_disabled",
+ "sSortJUIAsc": _sortIcon+"triangle-1-n",
+ "sSortJUIDesc": _sortIcon+"triangle-1-s",
+ "sSortJUI": _sortIcon+"carat-2-n-s",
+ "sSortJUIAscAllowed": _sortIcon+"carat-1-n",
+ "sSortJUIDescAllowed": _sortIcon+"carat-1-s",
+ "sSortJUIWrapper": "DataTables_sort_wrapper",
+ "sSortIcon": "DataTables_sort_icon",
+
+ /* Scrolling */
+ "sScrollHead": "dataTables_scrollHead "+_stateDefault,
+ "sScrollFoot": "dataTables_scrollFoot "+_stateDefault,
+
+ /* Misc */
+ "sHeaderTH": _stateDefault,
+ "sFooterTH": _stateDefault,
+ "sJUIHeader": _headerFooter+" ui-corner-tl ui-corner-tr",
+ "sJUIFooter": _headerFooter+" ui-corner-bl ui-corner-br"
+ } );
+
+ }());
+
+
+
+ var extPagination = DataTable.ext.pager;
+
+ function _numbers ( page, pages ) {
+ var
+ numbers = [],
+ buttons = extPagination.numbers_length,
+ half = Math.floor( buttons / 2 ),
+ i = 1;
+
+ if ( pages <= buttons ) {
+ numbers = _range( 0, pages );
+ }
+ else if ( page <= half ) {
+ numbers = _range( 0, buttons-2 );
+ numbers.push( 'ellipsis' );
+ numbers.push( pages-1 );
+ }
+ else if ( page >= pages - 1 - half ) {
+ numbers = _range( pages-(buttons-2), pages );
+ numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6
+ numbers.splice( 0, 0, 0 );
+ }
+ else {
+ numbers = _range( page-half+2, page+half-1 );
+ numbers.push( 'ellipsis' );
+ numbers.push( pages-1 );
+ numbers.splice( 0, 0, 'ellipsis' );
+ numbers.splice( 0, 0, 0 );
+ }
+
+ numbers.DT_el = 'span';
+ return numbers;
+ }
+
+
+ $.extend( extPagination, {
+ simple: function ( page, pages ) {
+ return [ 'previous', 'next' ];
+ },
+
+ full: function ( page, pages ) {
+ return [ 'first', 'previous', 'next', 'last' ];
+ },
+
+ numbers: function ( page, pages ) {
+ return [ _numbers(page, pages) ];
+ },
+
+ simple_numbers: function ( page, pages ) {
+ return [ 'previous', _numbers(page, pages), 'next' ];
+ },
+
+ full_numbers: function ( page, pages ) {
+ return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ];
+ },
+
+ // For testing and plug-ins to use
+ _numbers: _numbers,
+
+ // Number of number buttons (including ellipsis) to show. _Must be odd!_
+ numbers_length: 7
+ } );
+
+
+ $.extend( true, DataTable.ext.renderer, {
+ pageButton: {
+ _: function ( settings, host, idx, buttons, page, pages ) {
+ var classes = settings.oClasses;
+ var lang = settings.oLanguage.oPaginate;
+ var aria = settings.oLanguage.oAria.paginate || {};
+ var btnDisplay, btnClass, counter=0;
+
+ var attach = function( container, buttons ) {
+ var i, ien, node, button;
+ var clickHandler = function ( e ) {
+ _fnPageChange( settings, e.data.action, true );
+ };
+
+ for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
+ button = buttons[i];
+
+ if ( $.isArray( button ) ) {
+ var inner = $( '<'+(button.DT_el || 'div')+'/>' )
+ .appendTo( container );
+ attach( inner, button );
+ }
+ else {
+ btnDisplay = null;
+ btnClass = '';
+
+ switch ( button ) {
+ case 'ellipsis':
+ container.append('<span class="ellipsis">&#x2026;</span>');
+ break;
+
+ case 'first':
+ btnDisplay = lang.sFirst;
+ btnClass = button + (page > 0 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'previous':
+ btnDisplay = lang.sPrevious;
+ btnClass = button + (page > 0 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'next':
+ btnDisplay = lang.sNext;
+ btnClass = button + (page < pages-1 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'last':
+ btnDisplay = lang.sLast;
+ btnClass = button + (page < pages-1 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ default:
+ btnDisplay = button + 1;
+ btnClass = page === button ?
+ classes.sPageButtonActive : '';
+ break;
+ }
+
+ if ( btnDisplay !== null ) {
+ node = $('<a>', {
+ 'class': classes.sPageButton+' '+btnClass,
+ 'aria-controls': settings.sTableId,
+ 'aria-label': aria[ button ],
+ 'data-dt-idx': counter,
+ 'tabindex': settings.iTabIndex,
+ 'id': idx === 0 && typeof button === 'string' ?
+ settings.sTableId +'_'+ button :
+ null
+ } )
+ .html( btnDisplay )
+ .appendTo( container );
+
+ _fnBindAction(
+ node, {action: button}, clickHandler
+ );
+
+ counter++;
+ }
+ }
+ }
+ };
+
+ // IE9 throws an 'unknown error' if document.activeElement is used
+ // inside an iframe or frame. Try / catch the error. Not good for
+ // accessibility, but neither are frames.
+ var activeEl;
+
+ try {
+ // Because this approach is destroying and recreating the paging
+ // elements, focus is lost on the select button which is bad for
+ // accessibility. So we want to restore focus once the draw has
+ // completed
+ activeEl = $(host).find(document.activeElement).data('dt-idx');
+ }
+ catch (e) {}
+
+ attach( $(host).empty(), buttons );
+
+ if ( activeEl ) {
+ $(host).find( '[data-dt-idx='+activeEl+']' ).focus();
+ }
+ }
+ }
+ } );
+
+
+
+ // Built in type detection. See model.ext.aTypes for information about
+ // what is required from this methods.
+ $.extend( DataTable.ext.type.detect, [
+ // Plain numbers - first since V8 detects some plain numbers as dates
+ // e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
+ function ( d, settings )
+ {
+ var decimal = settings.oLanguage.sDecimal;
+ return _isNumber( d, decimal ) ? 'num'+decimal : null;
+ },
+
+ // Dates (only those recognised by the browser's Date.parse)
+ function ( d, settings )
+ {
+ // V8 will remove any unknown characters at the start and end of the
+ // expression, leading to false matches such as `$245.12` or `10%` being
+ // a valid date. See forum thread 18941 for detail.
+ if ( d && !(d instanceof Date) && ( ! _re_date_start.test(d) || ! _re_date_end.test(d) ) ) {
+ return null;
+ }
+ var parsed = Date.parse(d);
+ return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
+ },
+
+ // Formatted numbers
+ function ( d, settings )
+ {
+ var decimal = settings.oLanguage.sDecimal;
+ return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null;
+ },
+
+ // HTML numeric
+ function ( d, settings )
+ {
+ var decimal = settings.oLanguage.sDecimal;
+ return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null;
+ },
+
+ // HTML numeric, formatted
+ function ( d, settings )
+ {
+ var decimal = settings.oLanguage.sDecimal;
+ return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null;
+ },
+
+ // HTML (this is strict checking - there must be html)
+ function ( d, settings )
+ {
+ return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
+ 'html' : null;
+ }
+ ] );
+
+
+
+ // Filter formatting functions. See model.ext.ofnSearch for information about
+ // what is required from these methods.
+ //
+ // Note that additional search methods are added for the html numbers and
+ // html formatted numbers by `_addNumericSort()` when we know what the decimal
+ // place is
+
+
+ $.extend( DataTable.ext.type.search, {
+ html: function ( data ) {
+ return _empty(data) ?
+ data :
+ typeof data === 'string' ?
+ data
+ .replace( _re_new_lines, " " )
+ .replace( _re_html, "" ) :
+ '';
+ },
+
+ string: function ( data ) {
+ return _empty(data) ?
+ data :
+ typeof data === 'string' ?
+ data.replace( _re_new_lines, " " ) :
+ data;
+ }
+ } );
+
+
+
+ var __numericReplace = function ( d, decimalPlace, re1, re2 ) {
+ if ( d !== 0 && (!d || d === '-') ) {
+ return -Infinity;
+ }
+
+ // If a decimal place other than `.` is used, it needs to be given to the
+ // function so we can detect it and replace with a `.` which is the only
+ // decimal place Javascript recognises - it is not locale aware.
+ if ( decimalPlace ) {
+ d = _numToDecimal( d, decimalPlace );
+ }
+
+ if ( d.replace ) {
+ if ( re1 ) {
+ d = d.replace( re1, '' );
+ }
+
+ if ( re2 ) {
+ d = d.replace( re2, '' );
+ }
+ }
+
+ return d * 1;
+ };
+
+
+ // Add the numeric 'deformatting' functions for sorting and search. This is done
+ // in a function to provide an easy ability for the language options to add
+ // additional methods if a non-period decimal place is used.
+ function _addNumericSort ( decimalPlace ) {
+ $.each(
+ {
+ // Plain numbers
+ "num": function ( d ) {
+ return __numericReplace( d, decimalPlace );
+ },
+
+ // Formatted numbers
+ "num-fmt": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_formatted_numeric );
+ },
+
+ // HTML numeric
+ "html-num": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_html );
+ },
+
+ // HTML numeric, formatted
+ "html-num-fmt": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric );
+ }
+ },
+ function ( key, fn ) {
+ // Add the ordering method
+ _ext.type.order[ key+decimalPlace+'-pre' ] = fn;
+
+ // For HTML types add a search formatter that will strip the HTML
+ if ( key.match(/^html\-/) ) {
+ _ext.type.search[ key+decimalPlace ] = _ext.type.search.html;
+ }
+ }
+ );
+ }
+
+
+ // Default sort methods
+ $.extend( _ext.type.order, {
+ // Dates
+ "date-pre": function ( d ) {
+ return Date.parse( d ) || 0;
+ },
+
+ // html
+ "html-pre": function ( a ) {
+ return _empty(a) ?
+ '' :
+ a.replace ?
+ a.replace( /<.*?>/g, "" ).toLowerCase() :
+ a+'';
+ },
+
+ // string
+ "string-pre": function ( a ) {
+ // This is a little complex, but faster than always calling toString,
+ // http://jsperf.com/tostring-v-check
+ return _empty(a) ?
+ '' :
+ typeof a === 'string' ?
+ a.toLowerCase() :
+ ! a.toString ?
+ '' :
+ a.toString();
+ },
+
+ // string-asc and -desc are retained only for compatibility with the old
+ // sort methods
+ "string-asc": function ( x, y ) {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ },
+
+ "string-desc": function ( x, y ) {
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ }
+ } );
+
+
+ // Numeric sorting types - order doesn't matter here
+ _addNumericSort( '' );
+
+
+ $.extend( true, DataTable.ext.renderer, {
+ header: {
+ _: function ( settings, cell, column, classes ) {
+ // No additional mark-up required
+ // Attach a sort listener to update on sort - note that using the
+ // `DT` namespace will allow the event to be removed automatically
+ // on destroy, while the `dt` namespaced event is the one we are
+ // listening for
+ $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
+ if ( settings !== ctx ) { // need to check this this is the host
+ return; // table, not a nested one
+ }
+
+ var colIdx = column.idx;
+
+ cell
+ .removeClass(
+ column.sSortingClass +' '+
+ classes.sSortAsc +' '+
+ classes.sSortDesc
+ )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortDesc :
+ column.sSortingClass
+ );
+ } );
+ },
+
+ jqueryui: function ( settings, cell, column, classes ) {
+ $('<div/>')
+ .addClass( classes.sSortJUIWrapper )
+ .append( cell.contents() )
+ .append( $('<span/>')
+ .addClass( classes.sSortIcon+' '+column.sSortingClassJUI )
+ )
+ .appendTo( cell );
+
+ // Attach a sort listener to update on sort
+ $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ var colIdx = column.idx;
+
+ cell
+ .removeClass( classes.sSortAsc +" "+classes.sSortDesc )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortDesc :
+ column.sSortingClass
+ );
+
+ cell
+ .find( 'span.'+classes.sSortIcon )
+ .removeClass(
+ classes.sSortJUIAsc +" "+
+ classes.sSortJUIDesc +" "+
+ classes.sSortJUI +" "+
+ classes.sSortJUIAscAllowed +" "+
+ classes.sSortJUIDescAllowed
+ )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortJUIDesc :
+ column.sSortingClassJUI
+ );
+ } );
+ }
+ }
+ } );
+
+ /*
+ * Public helper functions. These aren't used internally by DataTables, or
+ * called by any of the options passed into DataTables, but they can be used
+ * externally by developers working with DataTables. They are helper functions
+ * to make working with DataTables a little bit easier.
+ */
+
+ /**
+ * Helpers for `columns.render`.
+ *
+ * The options defined here can be used with the `columns.render` initialisation
+ * option to provide a display renderer. The following functions are defined:
+ *
+ * * `number` - Will format numeric data (defined by `columns.data`) for
+ * display, retaining the original unformatted data for sorting and filtering.
+ * It takes 5 parameters:
+ * * `string` - Thousands grouping separator
+ * * `string` - Decimal point indicator
+ * * `integer` - Number of decimal points to show
+ * * `string` (optional) - Prefix.
+ * * `string` (optional) - Postfix (/suffix).
+ * * `text` - Escape HTML to help prevent XSS attacks. It has no optional
+ * parameters.
+ *
+ * @example
+ * // Column definition using the number renderer
+ * {
+ * data: "salary",
+ * render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
+ * }
+ *
+ * @namespace
+ */
+ DataTable.render = {
+ number: function ( thousands, decimal, precision, prefix, postfix ) {
+ return {
+ display: function ( d ) {
+ if ( typeof d !== 'number' && typeof d !== 'string' ) {
+ return d;
+ }
+
+ var negative = d < 0 ? '-' : '';
+ var flo = parseFloat( d );
+
+ // If NaN then there isn't much formatting that we can do - just
+ // return immediately
+ if ( isNaN( flo ) ) {
+ return d;
+ }
+
+ d = Math.abs( flo );
+
+ var intPart = parseInt( d, 10 );
+ var floatPart = precision ?
+ decimal+(d - intPart).toFixed( precision ).substring( 2 ):
+ '';
+
+ return negative + (prefix||'') +
+ intPart.toString().replace(
+ /\B(?=(\d{3})+(?!\d))/g, thousands
+ ) +
+ floatPart +
+ (postfix||'');
+ }
+ };
+ },
+
+ text: function () {
+ return {
+ display: function ( d ) {
+ return typeof d === 'string' ?
+ d.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') :
+ d;
+ }
+ };
+ }
+ };
+
+
+ /*
+ * This is really a good bit rubbish this method of exposing the internal methods
+ * publicly... - To be fixed in 2.0 using methods on the prototype
+ */
+
+
+ /**
+ * Create a wrapper function for exporting an internal functions to an external API.
+ * @param {string} fn API function name
+ * @returns {function} wrapped function
+ * @memberof DataTable#internal
+ */
+ function _fnExternApiFunc (fn)
+ {
+ return function() {
+ var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat(
+ Array.prototype.slice.call(arguments)
+ );
+ return DataTable.ext.internal[fn].apply( this, args );
+ };
+ }
+
+
+ /**
+ * Reference to internal functions for use by plug-in developers. Note that
+ * these methods are references to internal functions and are considered to be
+ * private. If you use these methods, be aware that they are liable to change
+ * between versions.
+ * @namespace
+ */
+ $.extend( DataTable.ext.internal, {
+ _fnExternApiFunc: _fnExternApiFunc,
+ _fnBuildAjax: _fnBuildAjax,
+ _fnAjaxUpdate: _fnAjaxUpdate,
+ _fnAjaxParameters: _fnAjaxParameters,
+ _fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
+ _fnAjaxDataSrc: _fnAjaxDataSrc,
+ _fnAddColumn: _fnAddColumn,
+ _fnColumnOptions: _fnColumnOptions,
+ _fnAdjustColumnSizing: _fnAdjustColumnSizing,
+ _fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
+ _fnColumnIndexToVisible: _fnColumnIndexToVisible,
+ _fnVisbleColumns: _fnVisbleColumns,
+ _fnGetColumns: _fnGetColumns,
+ _fnColumnTypes: _fnColumnTypes,
+ _fnApplyColumnDefs: _fnApplyColumnDefs,
+ _fnHungarianMap: _fnHungarianMap,
+ _fnCamelToHungarian: _fnCamelToHungarian,
+ _fnLanguageCompat: _fnLanguageCompat,
+ _fnBrowserDetect: _fnBrowserDetect,
+ _fnAddData: _fnAddData,
+ _fnAddTr: _fnAddTr,
+ _fnNodeToDataIndex: _fnNodeToDataIndex,
+ _fnNodeToColumnIndex: _fnNodeToColumnIndex,
+ _fnGetCellData: _fnGetCellData,
+ _fnSetCellData: _fnSetCellData,
+ _fnSplitObjNotation: _fnSplitObjNotation,
+ _fnGetObjectDataFn: _fnGetObjectDataFn,
+ _fnSetObjectDataFn: _fnSetObjectDataFn,
+ _fnGetDataMaster: _fnGetDataMaster,
+ _fnClearTable: _fnClearTable,
+ _fnDeleteIndex: _fnDeleteIndex,
+ _fnInvalidate: _fnInvalidate,
+ _fnGetRowElements: _fnGetRowElements,
+ _fnCreateTr: _fnCreateTr,
+ _fnBuildHead: _fnBuildHead,
+ _fnDrawHead: _fnDrawHead,
+ _fnDraw: _fnDraw,
+ _fnReDraw: _fnReDraw,
+ _fnAddOptionsHtml: _fnAddOptionsHtml,
+ _fnDetectHeader: _fnDetectHeader,
+ _fnGetUniqueThs: _fnGetUniqueThs,
+ _fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
+ _fnFilterComplete: _fnFilterComplete,
+ _fnFilterCustom: _fnFilterCustom,
+ _fnFilterColumn: _fnFilterColumn,
+ _fnFilter: _fnFilter,
+ _fnFilterCreateSearch: _fnFilterCreateSearch,
+ _fnEscapeRegex: _fnEscapeRegex,
+ _fnFilterData: _fnFilterData,
+ _fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
+ _fnUpdateInfo: _fnUpdateInfo,
+ _fnInfoMacros: _fnInfoMacros,
+ _fnInitialise: _fnInitialise,
+ _fnInitComplete: _fnInitComplete,
+ _fnLengthChange: _fnLengthChange,
+ _fnFeatureHtmlLength: _fnFeatureHtmlLength,
+ _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
+ _fnPageChange: _fnPageChange,
+ _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
+ _fnProcessingDisplay: _fnProcessingDisplay,
+ _fnFeatureHtmlTable: _fnFeatureHtmlTable,
+ _fnScrollDraw: _fnScrollDraw,
+ _fnApplyToChildren: _fnApplyToChildren,
+ _fnCalculateColumnWidths: _fnCalculateColumnWidths,
+ _fnThrottle: _fnThrottle,
+ _fnConvertToWidth: _fnConvertToWidth,
+ _fnGetWidestNode: _fnGetWidestNode,
+ _fnGetMaxLenString: _fnGetMaxLenString,
+ _fnStringToCss: _fnStringToCss,
+ _fnSortFlatten: _fnSortFlatten,
+ _fnSort: _fnSort,
+ _fnSortAria: _fnSortAria,
+ _fnSortListener: _fnSortListener,
+ _fnSortAttachListener: _fnSortAttachListener,
+ _fnSortingClasses: _fnSortingClasses,
+ _fnSortData: _fnSortData,
+ _fnSaveState: _fnSaveState,
+ _fnLoadState: _fnLoadState,
+ _fnSettingsFromNode: _fnSettingsFromNode,
+ _fnLog: _fnLog,
+ _fnMap: _fnMap,
+ _fnBindAction: _fnBindAction,
+ _fnCallbackReg: _fnCallbackReg,
+ _fnCallbackFire: _fnCallbackFire,
+ _fnLengthOverflow: _fnLengthOverflow,
+ _fnRenderer: _fnRenderer,
+ _fnDataSource: _fnDataSource,
+ _fnRowAttributes: _fnRowAttributes,
+ _fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant
+ // in 1.10, so this dead-end function is
+ // added to prevent errors
+ } );
+
+
+ // jQuery access
+ $.fn.dataTable = DataTable;
+
+ // Provide access to the host jQuery object (circular reference)
+ DataTable.$ = $;
+
+ // Legacy aliases
+ $.fn.dataTableSettings = DataTable.settings;
+ $.fn.dataTableExt = DataTable.ext;
+
+ // With a capital `D` we return a DataTables API instance rather than a
+ // jQuery object
+ $.fn.DataTable = function ( opts ) {
+ return $(this).dataTable( opts ).api();
+ };
+
+ // All properties that are available to $.fn.dataTable should also be
+ // available on $.fn.DataTable
+ $.each( DataTable, function ( prop, val ) {
+ $.fn.DataTable[ prop ] = val;
+ } );
+
+
+ // Information about events fired by DataTables - for documentation.
+ /**
+ * Draw event, fired whenever the table is redrawn on the page, at the same
+ * point as fnDrawCallback. This may be useful for binding events or
+ * performing calculations when the table is altered at all.
+ * @name DataTable#draw.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Search event, fired when the searching applied to the table (using the
+ * built-in global search, or column filters) is altered.
+ * @name DataTable#search.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Page change event, fired when the paging of the table is altered.
+ * @name DataTable#page.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Order event, fired when the ordering applied to the table is altered.
+ * @name DataTable#order.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * DataTables initialisation complete event, fired when the table is fully
+ * drawn, including Ajax data loaded, if Ajax data is required.
+ * @name DataTable#init.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} oSettings DataTables settings object
+ * @param {object} json The JSON object request from the server - only
+ * present if client-side Ajax sourced data is used</li></ol>
+ */
+
+ /**
+ * State save event, fired when the table has changed state a new state save
+ * is required. This event allows modification of the state saving object
+ * prior to actually doing the save, including addition or other state
+ * properties (for plug-ins) or modification of a DataTables core property.
+ * @name DataTable#stateSaveParams.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} oSettings DataTables settings object
+ * @param {object} json The state information to be saved
+ */
+
+ /**
+ * State load event, fired when the table is loading state from the stored
+ * data, but prior to the settings object being modified by the saved state
+ * - allowing modification of the saved state is required or loading of
+ * state for a plug-in.
+ * @name DataTable#stateLoadParams.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} oSettings DataTables settings object
+ * @param {object} json The saved state information
+ */
+
+ /**
+ * State loaded event, fired when state has been loaded from stored data and
+ * the settings object has been modified by the loaded data.
+ * @name DataTable#stateLoaded.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} oSettings DataTables settings object
+ * @param {object} json The saved state information
+ */
+
+ /**
+ * Processing event, fired when DataTables is doing some kind of processing
+ * (be it, order, searcg or anything else). It can be used to indicate to
+ * the end user that there is something happening, or that something has
+ * finished.
+ * @name DataTable#processing.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} oSettings DataTables settings object
+ * @param {boolean} bShow Flag for if DataTables is doing processing or not
+ */
+
+ /**
+ * Ajax (XHR) event, fired whenever an Ajax request is completed from a
+ * request to made to the server for new data. This event is called before
+ * DataTables processed the returned data, so it can also be used to pre-
+ * process the data returned from the server, if needed.
+ *
+ * Note that this trigger is called in `fnServerData`, if you override
+ * `fnServerData` and which to use this event, you need to trigger it in you
+ * success function.
+ * @name DataTable#xhr.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ * @param {object} json JSON returned from the server
+ *
+ * @example
+ * // Use a custom property returned from the server in another DOM element
+ * $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
+ * $('#status').html( json.status );
+ * } );
+ *
+ * @example
+ * // Pre-process the data returned from the server
+ * $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
+ * for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
+ * json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
+ * }
+ * // Note no return - manipulate the data directly in the JSON object.
+ * } );
+ */
+
+ /**
+ * Destroy event, fired when the DataTable is destroyed by calling fnDestroy
+ * or passing the bDestroy:true parameter in the initialisation object. This
+ * can be used to remove bound events, added DOM nodes, etc.
+ * @name DataTable#destroy.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Page length change event, fired when number of records to show on each
+ * page (the length) is changed.
+ * @name DataTable#length.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ * @param {integer} len New length
+ */
+
+ /**
+ * Column sizing has changed.
+ * @name DataTable#column-sizing.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Column visibility has changed.
+ * @name DataTable#column-visibility.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ * @param {int} column Column index
+ * @param {bool} vis `false` if column now hidden, or `true` if visible
+ */
+
+ return $.fn.dataTable;
+})); \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/js/op25.js b/op25/gr-op25_repeater/apps/oplog/op25/static/js/op25.js
new file mode 100644
index 0000000..8a6faf3
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/js/op25.js
@@ -0,0 +1,227 @@
+// Copyright 2017, 2018, 2019, 2020, 2021 Max H. Parke KA1RBI
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+//
+// OP25 Logs
+
+$(window).load(function() {
+ $('#loading').hide();
+});
+
+$(document).ready(function() {
+ $('#startDate').val(localStorage.logStart);
+ $('#endDate').val(localStorage.logEnd);
+ randCss(); // force css reload each time for dev
+ $('#records').text(comma(parseInt(($('#records').text()))));
+ $('#systems').text(comma(parseInt(($('#systems').text()))));
+ $('#talkgroups').text(comma(parseInt(($('#talkgroups').text()))));
+ $('#subs').text(comma(parseInt(($('#subs').text()))));
+ if (localStorage.systemSelect) {
+ $('#systemSelect').val(localStorage.systemSelect);
+ }
+ if (localStorage.systemSelect4) {
+ $('#systemSelect4').val(localStorage.systemSelect4);
+ }
+});
+
+$(window).load(function() {
+ $('#loading').hide();
+});
+
+function resetDates() {
+ $('#startDate').val('');
+ $('#endDate').val('');
+ $('#systemSelect').val('0');
+ window.localStorage.removeItem('logStart');
+ window.localStorage.removeItem('logEnd');
+ window.localStorage.removeItem('systemSelect');
+}
+
+$('#navSelect').change(function(){
+ console.log("shit");
+ var ns = $('#navSelect').val();
+ if (ns == '0')
+ return;
+ console.log(ns);
+ load_new_page1(ns);
+});
+
+// forces css to reload - helpful during dev
+function randCss() {
+ var h, a, f;
+ a = document.getElementsByTagName('link');
+ for (h = 0; h < a.length; h++) {
+ f = a[h];
+ if (f.rel.toLowerCase().match(/stylesheet/) && f.href) {
+ var g = f.href.replace(/(&|\?)rnd=\d+/, '');
+ f.href = g + (g.match(/\?/) ? '&' : '?');
+ f.href += 'rnd=' + (new Date().valueOf());
+ }
+ }
+}
+
+
+function load_new_page1(request,param) {
+ var v1 = $('#resource_id').val();
+ tgid = $('#cc_filter_tgid').val();
+ suid = $('#cc_filter_suid').val();
+ tgid = (Number.isInteger(parseInt(tgid)) == true) ? parseInt(tgid) : 0;
+ suid = (Number.isInteger(parseInt(suid)) == true) ? parseInt(suid) : 0;
+ load_new_page('/logs', 'q=' + v1 + '&r=' + request + '&p=' + param + '&tgid=' + tgid + '&suid=' + suid);
+}
+
+
+//SUID and TGID 'specified' buttons!
+function load_new_page0(request) {
+ var v1 = $('#resource_id').val();
+ var sysid = $('#systemSelect').val();
+ if (v1 == '') {
+ alert("Subscriber unit ID or talkgroup ID is required!");
+ return;
+ }
+ if (v1.split('-').length > 2) {
+ alert("Too many values for a range.");
+ return;
+ }
+
+ load_new_page('/logs', 'q=' + v1 + '&r=' + request + '&sysid=' + sysid);
+}
+
+function load_new_page(url, arg) {
+ var u = url;
+ if (arg)
+ u = u + "?" + arg;
+ window.open(u, "_self", "resizable,location,menubar,toolbar,scrollbars,status")
+}
+
+function sdate() {
+ var s = $('#startDate').val() ? new Date($('#startDate').val()) : new Date("2001/01/01 01:00");
+ var stime = s.getTime() / 1000;
+ return stime | 0;
+}
+
+function edate() {
+ var e = $('#endDate').val() ? new Date($('#endDate').val()) : new Date();
+ var etime = e.getTime() / 1000;
+ return etime | 0;
+}
+
+function comma(x) {
+ // add comma formatting to whatever you give it (xx,xxxx,xxxx)
+ return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
+function doPurge(sim) {
+ var kv = $('#keepVoice').prop('checked');
+ var bu = $('#createBackup').prop('checked');
+ if ($('#startDate').val() == '' || $('#endDate').val() == '') {
+ alert('Start date and end date are required.');
+ return;
+ }
+ var sd = sdate();
+ var ed = edate();
+ var sysid = $('#systemSelect').val();
+ window.location.href='/purge?action=purge&sd=' + sd + '&ed=' + ed + '&sysid=' + sysid + '&simulate=' + sim + '&kv=' + kv + '&bu=' + bu;
+
+}
+
+function addNewSystemTag() {
+ if ($('#newSysId').val() == '' || $('#newSysTag').val() == '') {
+ alert('System ID (dec) and System Tag are required.');
+ return;
+ }
+ var hexId = $('#newSysId').val();
+ var newId = parseInt(dec(hexId));
+ var newTag = $('#newSysTag').val()
+ if (! Number.isInteger(newId)) {
+ alert('Invalid system ID.');
+ return;
+ }
+ window.location.href='/asd?id=' + newId + '&tag=' + newTag;
+}
+
+function importTalkgroupTsv(cmd) {
+ $('#impProc').show()
+ if ($('#selTsv').val() == '0' || $('#systemSelect2').val() == '0') {
+ alert('TSV file selection and System selection are required.');
+ $('#impProc').hide()
+ return;
+ }
+
+ if ($('#invtsv').length){
+ $('#impProc').hide()
+ alert('The TSV is invalid!');
+ return;
+ }
+
+ var sysid = $('#systemSelect2').val();
+ var tsvfile = $('#selTsv').val();
+ window.location.href='/itt?sysid=' + sysid + '&file=' + tsvfile + '&cmd=' + cmd;
+}
+
+function deleteTags(cmd) {
+ if ($('#systemSelect3').val() == '0') {
+ alert('System selection is required.');
+ return;
+ }
+ sysid = $('#systemSelect3').val();
+ window.location.href='/delTags?sysid=' + sysid + '&cmd=' + cmd;
+}
+
+function hex(dec) {
+ if (!dec) return;
+ return dec.toString(16);
+}
+
+function dec(hex) {
+ if (!hex) return;
+ return parseInt(hex, 16);
+}
+
+function csvTable(table_id, separator = ',') { // Quick and simple export target #table_id into a csv
+ var rows = document.querySelectorAll('table#' + table_id + ' tr');
+ // Construct csv
+ var csv = [];
+ for (var i = 0; i < rows.length; i++) {
+ var row = [],
+ cols = rows[i].querySelectorAll('td, th');
+ for (var j = 0; j < cols.length; j++) {
+ // Clean innertext to remove multiple spaces and jumpline (break csv)
+ var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ');
+ // Escape double-quote with double-double-quote
+ data = data.replace(/"/g, '""');
+ // Push escaped string
+ row.push('"' + data + '"');
+ }
+ csv.push(row.join(separator));
+ }
+ var csv_string = csv.join('\n');
+ // Download it
+ var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
+ var link = document.createElement('a');
+ link.style.display = 'none';
+ link.setAttribute('target', '_blank');
+ link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
+ link.setAttribute('download', filename);
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+}
+
+
+
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/loading.gif b/op25/gr-op25_repeater/apps/oplog/op25/static/loading.gif
new file mode 100644
index 0000000..c1d8473
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/loading.gif
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark-h.png b/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark-h.png
new file mode 100644
index 0000000..73d771a
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark-h.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark.png b/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark.png
new file mode 100644
index 0000000..4847302
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/op25-dark.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/static/op25.png b/op25/gr-op25_repeater/apps/oplog/op25/static/op25.png
new file mode 100644
index 0000000..a549857
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/static/op25.png
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/about.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/about.html
new file mode 100644
index 0000000..88d0878
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/about.html
@@ -0,0 +1,144 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+{% block extra_stylesheets %}
+<link href="static/css/datatables/jquery.dataTables-dark.css" rel="stylesheet">
+{% endblock %}
+
+{% block content %}
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header">About OP25 Logs</h4>
+ <div class="card-body">
+ <p class="card-text">
+
+ <div align="center">
+ <div class="card border-secondary mb-3" style="max-width: 40rem; text-align: left;">
+ <div class="card-body">
+ <p class="card-text">
+ OP25 Logs (aka Oplog) is the OP25 sqlite3 logs database viewer.
+ </p>
+
+ <p class="card-text">
+ Copyright &copy; 2020, 2021 Max H. Parke KA1RBI<br>
+ Copyright &copy; 2020, 2021 Michael Rose
+ </p>
+ <p class="card-text">
+ OP25 Logs is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+ </p>
+ <p class="card-text">
+ OP25 Logs is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
+{% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+
+<!-- end secondary -->
+</div>
+<!-- end content -->
+
+
+</div>
+<br>
+
+{% endblock %}
+
+<!-- js moved to op25.js -->
+
+{% block extra_javascripts %}
+<script src="static/js/datatables/jquery.dataTables.js"></script>
+<script>
+ $(document).ready(function () {
+ $('#startDate').prop('disabled', true );
+ $('#endDate').prop('disabled', true );
+ $('#op25_esd').DataTable({
+ "processing": true,
+ "serverSide": true,
+ 'bFilter': false,
+ 'paging': false,
+ "ajax": '/esd',
+ "columns": [
+ null,
+ {
+ "data": [1],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = data + ' - ' + hex(data).toUpperCase();
+ }
+ return data;
+ }
+ },
+ null,
+
+ {
+ "data": [3],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = '<button type="button" class="btn btn-primary btn-sm" onclick="this.blur(); editTagName(' + data + ', \'' + row[2] + '\')">Edit Tag</button>&nbsp;\
+ <button type="button" class="btn btn-primary btn-sm" onclick="window.location.href=\'\/dsd?id=' + data + '\'">Delete</button>';
+
+ }
+ return data;
+ },
+ "width": "150px"
+ }
+ ]
+
+ });
+ });
+
+function editTagName(id, t) {
+ var tag = prompt("Enter new system tag:", t);
+ if (tag == null || tag == '') {
+ return;
+ }
+ window.location.href='/usd?id=' + id + '&tag=' + tag;
+
+}
+</script>
+
+
+{% endblock %}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/base.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/base.html
new file mode 100644
index 0000000..257318b
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/base.html
@@ -0,0 +1,167 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+-->
+
+<!DOCTYPE html>
+<html lang="{{ request.locale_name }}">
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="description" content="pyramid web application">
+ <meta name="author" content="Pylons Project">
+ <title>OP25 - Logs</title>
+ <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
+ <link rel="stylesheet" type="text/css" href="static/css/op25.css">
+ <link href="static/css/bootstrap/bootstrap-darkly.css" rel="stylesheet">
+ <link rel="stylesheet" type="text/css" href="static/dtpick/jquery.datetimepicker.css">
+ <style>
+ </style>
+ {% block extra_stylesheets %} {% endblock %}
+ <script src="static/jquery/jquery-2.2.4.min.js"></script>
+ <script src="static/js/bootstrap/bootstrap.bundle.min.js"></script>
+ <script src="static/dtpick/dtpick2.js"></script>
+ <script src="static/js/op25.js"></script>
+ </head>
+
+<body>
+ <div class="card text-white bg-primary mb-3">
+ <div class="card-body">
+ <table style="width: 100%;">
+ <tr>
+ <td>
+ <a style="width: 200px;" class="nav-link dropdown-toggle navbar-brand text-white" data-bs-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"><b>OP25 - Logs</b></a>
+ <div class="dropdown-menu">
+ <a class="dropdown-item" href="{{ url_for('home') }}">Home</a>
+ <div class="dropdown-divider"></div>
+ <a class="dropdown-item" href="{{ url_for('logs') }}?r=total_tgid">Total Talkgroup Voice Activity</a>
+ <a class="dropdown-item" href="{{ url_for('logs') }}?r=call_detail">Call Detail</a>
+ <a class="dropdown-item" href="{{ url_for('logs') }}?r=joins">Join Activity</a>
+ <div class="dropdown-divider"></div>
+ {% for s in params['ekeys'] %}
+ <a class="dropdown-item" href="#" onclick="javascript:load_new_page1('cc_event', '{{ s }}');"> {{ s|replace("_", " ") }}</a> {% endfor %}
+ <div class="dropdown-divider"></div>
+ <a class="dropdown-item" href="{{ url_for('editsys') }}">Edit System Tags</a>
+ <a class="dropdown-item" href="{{ url_for('edit_tags') }}?cmd=tgid">Update Talkgroup Tags</a>
+ <a class="dropdown-item" href="{{ url_for('edit_tags') }}?cmd=unit">Update Subscriber Tags</a>
+ <a class="dropdown-item" href="{{ url_for('switch_db') }}">Backup & Switch Database</a>
+ <a class="dropdown-item text-danger" href="{{ url_for('purge') }}">Purge Database</a>
+ <div class="dropdown-divider"></div>
+ <a class="dropdown-item" href="{{ url_for('about') }}">About</a>
+ </div>
+ </td>
+ <td>
+ <div style="float: right;">
+ <b>System</b>
+ <select id="systemSelect" style="">
+ <option value="0" selected>All</option>
+ </select>
+ &nbsp;&nbsp;&nbsp;&nbsp;
+ <span>Start <input class="sel-date" type="text" id="startDate"></span>
+ <span>End <input class="sel-date" type="text" id="endDate">&nbsp;&nbsp;&nbsp;</span>
+ <button style="width: 75px;" class="btn btn-info btn-sm" id="btnReset" onclick="location.reload();">Refresh</button>&nbsp;&nbsp;
+ <button style="width: 75px;" class="btn btn-info btn-sm" id="btnClear" onclick="resetDates();">Clear</button>
+ </div>
+ </td>
+ </tr>
+ </table>
+ </div>
+ </div>
+
+ <div class="container" style="margin-top: 0px; margin-bottom: 15px;">
+ <div align="center">
+ <a href="/"><img src="static/op25-dark-h.png" title="OP25"></a>
+ </div>
+ {% block content %} {% endblock %}
+ </div>
+
+ {% block extra_javascripts %}
+
+ <script>
+ $('#startDate').datetimepicker({
+ inline:false,
+ });
+
+ $('#endDate').datetimepicker({
+ inline:false,
+ });
+
+ $('#startDate').change( function(){
+ localStorage.logStart = $('#startDate').val();
+ });
+
+ $('#endDate').change( function(){
+ localStorage.logEnd = $('#endDate').val();
+ });
+
+ {% if sysList is not none %}
+ {% for i in sysList %}
+ {% if i.tag is not none %}
+ $('#systemSelect').append(new Option('{{ i.tag }} - {{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }}', '{{ i.sysid }}'));
+ {% else %}
+ $('#systemSelect').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }}', '{{ i.sysid }}'));
+ {% endif %}
+ {% endfor %}
+ {% endif %}
+
+ $('#systemSelect').change( function(){
+ localStorage.systemSelect = $('#systemSelect').val();
+ });
+
+ $('#navSelect').append(new Option('Home', '4'));
+ $('#navSelect').append(new Option('Total Talkgroup Voice Activity', '1'));
+ $('#navSelect').append(new Option('Call Detail', '2'));
+ $('#navSelect').append(new Option('Join Activity', '3'));
+
+ {% for s in params['ekeys'] %}
+ $('#navSelect').append(new Option( '{{ s }}', '{{ s }}' ));
+ {% endfor %}
+
+ // pretty sure this is not used anymore 7/2
+ $('#navSelect').change(function(){
+ var ns = $('#navSelect').val();
+ if (ns == '0')
+ return;
+ if (ns == '1') {
+ window.location.href='/logs?r=total_tgid';
+ return;
+ }
+ if (ns == '2'){
+ window.location.href='/logs?r=call_detail';
+ return;
+ }
+ if (ns == '3'){
+ window.location.href='/logs?r=joins';
+ return;
+ }
+ if (ns == '4'){
+ window.location.href='/';
+ return;
+ }
+ load_new_page1('cc_event', ns);
+ });
+ </script>
+
+ {% endblock %}
+
+ </body>
+</html> \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/dbstats.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/dbstats.html
new file mode 100644
index 0000000..4f4ee2d
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/dbstats.html
@@ -0,0 +1,53 @@
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header">Database Statistics</h4>
+ <div class="card-body">
+ <div class="card mb-3 bg-dark border-primary">
+ <table border="0" style="width: 100%;" class="border-primary">
+ <tr>
+ <td style="vertical-align: top; padding: 0px;">
+ <div class="card mb-3 bg-dark border-dark">
+ <span class="card-header">Records</span>
+ <div class="card-body">
+ <table style="padding: 5px; width: 100%; border="0">
+ <tr><td>Total Records: <b><span id="records">{{ dbstats[0] }}</span></b>
+ &nbsp;&nbsp;&nbsp;&nbsp;
+ Talkgroups: <b><span id="talkgroups">{{ dbstats[2] }}</span></b>
+ &nbsp;&nbsp;&nbsp;&nbsp;
+ Subscribers: <b><span id="subs">{{ dbstats[3] }}</span></b>
+ </td></tr>
+ <tr>
+ <td>First: <b><span id="firstDate"> {{ dbstats[4] }} </b></span></td>
+ </tr><tr>
+ <td>Last: <b><span id="lastDate"> {{ dbstats[5] }} </b></span></td>
+ </tr><tr>
+ <td>Database Size: <b><span id="dbSize"> {{ dbstats[6] }} </b></span></td>
+ </tr><tr>
+ {% set fn = dbstats[7].split('/') %}
+ <td>Database File: <b><span id="dbFile"> {{ fn|last }} </b> <a href="#" title=" {{ dbstats[7] }}">?</a></span></td>
+ </tr>
+ </table>
+ </div>
+ </div>
+ </td>
+ <td style="vertical-align: top; padding: 0px;">
+ <div class="card mb-3 bg-dark border-dark">
+ <span class="card-header">Logged Systems: <b><span id="systems">{{ dbstats[1] }}</span></b><br></span>
+ <div class="card-body">
+ <table style="padding: 5px; width: 100%;" class="table table-hover">
+ {% for i in sysList %}
+ <tr>
+ {% if i.tag is not none %}
+ <td style="padding: 2px;"> {{ i.sysid }} </td><td style="padding: 2px;"> 0x{{ ( '%0x' % i.sysid ).upper() }} </td><td style="padding: 2px;"> {{ i.tag }} </td>
+ {% else %}
+ <td style="padding: 2px;"> {{ i.sysid }}</td><td style="padding: 2px;"> 0x{{ ( '%0x' % i.sysid ).upper() }} </td><td style="padding: 2px;"> &mdash; </td>
+ {% endif %}
+ </tr>
+ {% endfor %}
+ </table>
+ </div>
+ </div>
+ </td></tr></table>
+ </div>
+ </div>
+ </div>
+ \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/edit_tags.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/edit_tags.html
new file mode 100644
index 0000000..5045916
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/edit_tags.html
@@ -0,0 +1,293 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+{% block extra_stylesheets %}
+<link href="static/css/datatables/jquery.dataTables-dark.css" rel="stylesheet">
+{% endblock %}
+
+{% block content %}
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+ <div class="card mb-3 border-primary">
+ {% if cmd == 'tgid' %}
+ <h4 class="card-header">Talkgroup Tags</h4>
+ {% elif cmd == 'unit' %}
+ <h4 class="card-header">Subscriber Tags</h4>
+ {% endif %}
+ <div class="card-body">
+
+ <div class="card mb-3 border-secondary">
+ <h5 class="card-header">Import Tool</h4>
+ <div class="card-body">
+ <p class="card-text">
+ This tool imports tags from the selected TSV and associates them with the
+ selected system. Existing System ID and Talkgroup or Subscriber ID combinations will be overwritten by the tag values in the TSV file.
+ To add new tags: Add in OP25 Web UI, then import them here. Wildcard entries are not imported.
+ </p>
+<label for="selTsv">Choose TSV file:</label>
+ <select name="selTsv" id="selTsv">
+ <option value='0' >Select...</option>
+ {% for i in tsvs %}
+ {% if '.tsv' in i and '._' not in i %}
+ <option value="{{ i.split('/../')[-1] }}">{{ i.split('/../')[-1] }}</option>
+ {% endif %}
+ {% endfor %}
+ </select>
+&nbsp;&nbsp;&nbsp;
+<label for="systemSelect2">Choose System: </label>
+<select id="systemSelect2">
+<option value="0" selected>Select...</option>
+</select>
+<br><br>
+
+<button class="btn btn-primary" onclick="this.blur(); inspectTsv();">Inspect TSV</button>
+<br>
+<div id="inspect" style="display: none;">
+ <br>
+ <div id="inspectText" style="width: 100%; height: 225px; overflow: auto;"></div>
+ <br>
+ <button class="btn btn-primary" onclick="this.blur(); importTalkgroupTsv('{{ cmd }}');">Import TSV</button>
+ &nbsp;&nbsp;<img id="impProc" src="static/loading.gif" style="height: 20px; display: none;" alt="loading">
+</div>
+
+ {% if session['sm'] == 3 %}
+ <br>
+ <div class="alert alert-dismissible alert-success">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Import completed.</strong><br><br>
+ Existing records updated:<b> {{ session['imp_results'][0] }}</b> &nbsp;&nbsp;&nbsp;&nbsp;
+ New records added:<b> {{ session['imp_results'][1] }} </b> &nbsp;&nbsp;&nbsp;&nbsp;
+ Duplicate records corrected:<b> {{ session['imp_results'][2] }} </b>
+ </div>
+ {{ clear_sm() }}
+ {% endif %}
+
+ {% if session['sm'] == 4 %}
+ <br>
+ <div class="alert alert-dismissible alert-primary">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Tags deleted.</strong><br><br>
+ </div>
+ {{ clear_sm() }}
+ {% endif %}
+
+</div>
+</div>
+<hr>
+
+<div class="card mb-3 border-secondary">
+ <h5 class="card-header">Editor</h4>
+ <div class="card-body">
+<div align="right">
+ <label for="systemSelect4">Filter by system: </label>
+<select id="systemSelect4">
+<option value="0" selected>All</option>
+</select><br><br>
+<button style="width: 75px;" class="btn btn-primary btn-sm" id="applyFilter" onclick="location.reload();">Apply</button>
+<br><br></div>
+
+ {% if session['sm'] == 1 %}
+ <div class="alert alert-dismissible alert-success">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Edit completed.</strong>
+ </div>
+ {{ clear_sm() }}
+ {% endif %}
+
+ {% if session['sm'] == 2 %}
+ <div class="alert alert-dismissible alert-warning">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Record deleted.</strong>
+ </div>
+ {{ clear_sm() }}
+ {% endif %}
+
+ <table id="op25_esd" class="display" cellspacing="0" width="100%">
+ <thead>
+ <tr>
+ {% if cmd == 'tgid' %}
+ <th>Record ID</th>
+ <th>System ID</th>
+ <th>Talkgroup ID</th>
+ <th>Talkgroup Tag</th>
+ <th>Actions</th>
+ {% elif cmd == 'unit' %}
+ <th>Record ID</th>
+ <th>System ID</th>
+ <th>Subscriber ID</th>
+ <th>Subscriber Tag</th>
+ <th>Actions</th>
+ {% endif %}
+ </thead>
+ <tbody></tbody>
+ </table>
+ </div>
+ </div>
+</div>
+</div>
+
+<div class="card mb-3 border-danger">
+<h5 class="card-header">Delete Tags</h4>
+ <div class="card-body">
+ Delete all
+ {% if cmd == 'tgid' %}
+ talkgroup
+ {% elif cmd == 'unit' %}
+ subscriber
+ {% endif %}
+ tags associated with a system. You cannot undo this action!
+ <br><br>
+<label for="systemSelect3">Choose System: </label>
+<select id="systemSelect3">
+<option value="0" selected>Select...</option>
+</select>
+<br><br>
+ <div align="center">
+ <button id="btnPurge" class="btn btn-danger" onclick="this.blur(); deleteTags('{{ cmd }}');">Delete
+ {% if cmd == 'tgid' %}
+ Talkgroup
+ {% elif cmd == 'unit' %}
+ Subscriber
+ {% endif %}
+ Tags
+ </button>
+ </div>
+ </div>
+ </div>
+{% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+<br>
+
+{% endblock %}
+
+{% block extra_javascripts %}
+
+<script src="static/js/datatables/jquery.dataTables.js"></script>
+
+<script>
+ $(document).ready(function () {
+ $('#startDate').prop('disabled', true );
+ $('#endDate').prop('disabled', true );
+ var sysid = $('#systemSelect4').val();
+ $('#op25_esd').DataTable({
+ "processing": true,
+ "serverSide": true,
+ 'bFilter': true,
+ 'paging': true,
+
+ "ajax": {
+ "url": '/edittg',
+ "data": { "sysid": sysid,
+ "cmd": '{{ cmd }}',
+ }
+ },
+
+ "columns": [
+ { "visible": false },
+ {
+ "data": [1],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = data + ' - ' + hex(data).toUpperCase();
+ }
+ return data;
+ }
+ },
+ null,
+ null,
+ {
+ "data": [3],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = '<button type="button" class="btn btn-primary btn-sm" onclick="this.blur(); editTagName(' + row[0] + ', \'' + row[3] + '\')">Edit Tag</button>&nbsp;\
+ <button type="button" class="btn btn-primary btn-sm" onclick="window.location.href=\'\/dtd?cmd={{ cmd }}&id=' + row[0] + '\'">Delete</button>';
+ }
+ return data;
+ },
+ "width": "150px"
+ }
+ ]
+
+ });
+ });
+
+function editTagName(id, t) {
+ var tag = prompt("Enter new tag:", t);
+ if (tag == null || tag == '')
+ return;
+ window.location.href='/utd?id=' + id + '&tag=' + tag + '&cmd={{ cmd }}';
+}
+
+function inspectTsv() {
+ var file = $('#selTsv').val();
+ if (file == '0')
+ return;
+
+ f = '/inspect?file=' + file;
+ $.ajax({
+ url : f,
+ type : 'GET',
+ success : popInsp,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('Error: \n\nFile:' + f + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+function popInsp(h) {
+ $('#inspect').show();
+ $('#inspectText').html(h).scrollTop(0);
+}
+
+ {% if systems is not none %}
+ {% for i in systems %}
+ {% if i.tag is not none %}
+ $('#systemSelect2').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }} - {{ i.tag }}', '{{ i.sysid }}'));
+ $('#systemSelect3').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }} - {{ i.tag }}', '{{ i.sysid }}'));
+ $('#systemSelect4').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }} - {{ i.tag }}', '{{ i.sysid }}'));
+ {% else %}
+ $('#systemSelect2').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }}', '{{ i.sysid }}'));
+ $('#systemSelect3').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }}', '{{ i.sysid }}'));
+ $('#systemSelect4').append(new Option('{{ i.sysid }} - 0x{{ ( '%0x' % i.sysid ).upper() }}', '{{ i.sysid }}'));
+ {% endif %}
+ {% endfor %}
+ {% endif %}
+
+ $('#systemSelect4').change( function(){
+ localStorage.systemSelect4 = $('#systemSelect4').val();
+ });
+
+</script>
+
+
+{% endblock %}
+
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/editsys.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/editsys.html
new file mode 100644
index 0000000..4fe288d
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/editsys.html
@@ -0,0 +1,151 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+{% block extra_stylesheets %}
+<link href="static/css/datatables/jquery.dataTables-dark.css" rel="stylesheet">
+{% endblock %}
+
+{% block content %}
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header">System Tags</h4>
+ <div class="card-body">
+ <p class="card-text">
+ </p>
+
+ <table id="op25_esd" class="display" cellspacing="0" width="100%">
+ <thead>
+ <tr>
+ <th>Record ID</th>
+ <th>System ID</th>
+ <th>System Name</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody></tbody>
+ </table>
+ <br><br>
+ <table style="width: 65%; padding: 0px;" class="border-primary">
+ <tr>
+ <td style="vertical-align: top;">
+ <div class="form-floating mb-3 primary">
+ <input type="text" width="10" class="form-control" id="newSysId" placeholder="">
+ <label for="floatingInput">System ID (hex)</label>
+ </div>
+ </td>
+ <td>
+ <div class="form-floating mb-3">
+ <input type="text" class="form-control" size="25" id="newSysTag" placeholder="">
+ <label for="floatingInput">System Tag</label>
+ </div>
+ </td>
+ </tr>
+ <tr>
+ <td style="text-align: left; vertical-align: top;">
+ <button class="btn btn-primary" onclick="this.blur; addNewSystemTag();">Add New</button>
+ </td>
+ </table>
+ </div>
+</div>
+{% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+
+<!-- end secondary -->
+</div>
+<!-- end content -->
+
+
+</div>
+<br>
+
+{% endblock %}
+
+<!-- js moved to op25.js -->
+
+{% block extra_javascripts %}
+<script src="static/js/datatables/jquery.dataTables.js"></script>
+<script>
+ $(document).ready(function () {
+ $('#startDate').prop('disabled', true );
+ $('#endDate').prop('disabled', true );
+ $('#op25_esd').DataTable({
+ "processing": true,
+ "serverSide": true,
+ 'bFilter': false,
+ 'paging': false,
+ "ajax": '/esd',
+ "columns": [
+ null,
+ {
+ "data": [1],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = data + ' - ' + hex(data).toUpperCase();
+ }
+ return data;
+ }
+ },
+ null,
+
+ {
+ "data": [3],
+ "render": function(data, type, row, meta){
+ if(type === 'display'){
+ data = '<button type="button" class="btn btn-primary btn-sm" onclick="this.blur(); editTagName(' + data + ', \'' + row[2] + '\')">Edit Tag</button>&nbsp;\
+ <button type="button" class="btn btn-primary btn-sm" onclick="window.location.href=\'\/dsd?id=' + data + '\'">Delete</button>';
+
+ }
+ return data;
+ },
+ "width": "150px"
+ }
+ ]
+
+ });
+ });
+
+function editTagName(id, t) {
+ var tag = prompt("Enter new system tag:", t);
+ if (tag == null || tag == '') {
+ return;
+ }
+ window.location.href='/usd?id=' + id + '&tag=' + tag;
+
+}
+</script>
+
+
+{% endblock %}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/error.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/error.html
new file mode 100644
index 0000000..257b985
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/error.html
@@ -0,0 +1,191 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+
+{% block content %}
+
+<html lang="{{ request.locale_name }}">
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="description" content="pyramid web application">
+ <meta name="author" content="Pylons Project">
+ <title>OP25 - Logs</title>
+ <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
+ <link rel="stylesheet" type="text/css" href="static/css/op25.css">
+ <link href="static/css/bootstrap/bootstrap-darkly.css" rel="stylesheet">
+ <link rel="stylesheet" type="text/css" href="static/dtpick/jquery.datetimepicker.css">
+ <style>
+ </style>
+ {% block extra_stylesheets %} {% endblock %}
+ <script src="static/jquery/jquery-2.2.4.min.js"></script>
+ <script src="static/js/bootstrap/bootstrap.bundle.min.js"></script>
+ <script src="static/dtpick/dtpick2.js"></script>
+ <script src="static/js/op25.js"></script>
+ </head>
+<div id="container">
+ <div id="header">
+ <p>&nbsp;</p>
+ </div>
+ <div id="primary">
+ &nbsp;
+ </div>
+<div id="content" align="center">
+ <div class="card mb-3 border-primary" style="max-width: 60rem; text-align: left;">
+ <h4 class="card-header bg-danger">OP25 Logs - Database Error (Code {{ code }})</h4>
+ <div class="card-body">
+
+ {% if code == 1 %}
+ <div class="alert alert-dismissible">
+ <strong>Database file does not exist.</strong> <br><br> {{ file }}</span> <Br><Br>File not found.
+ </div>
+ {% endif %}
+
+ {% if code == 2 %}
+ <div class="alert alert-dismissible">
+ <strong>Database file is too small. </strong> <br><Br> {{ file }} <br><br>Attributes do not conform.
+ </div>
+ {% endif %}
+
+ {% if code == 4 %}
+ <div class="alert alert-dismissible">
+ <strong>Database contains no data. </strong> <br><Br> {{ file }} <br><br> Database structure is good, but no data was found. <br><br>0 rows in table 'data_store'.
+ </div>
+ {% endif %}
+
+ {% if code == 5 %}
+ <div class="alert alert-dismissible">
+ <strong>Database access error. </strong> <br><Br> {{ file }} <br><br> Database might be locked or in use by another process (OP25). <br><br>
+ Source: {{ source }}
+ </div>
+ {% endif %}
+
+ </div>
+ </div>
+
+
+
+ <div align="center">
+ <button class="btnMain btn btn-outline-info" onclick="window.location.href='/'">Try Again</button>
+ <br><br>
+ </div>
+
+ {% if code == 5 %}
+ <div class="card mb-3 border-primary" style="max-width: 60rem; text-align: left;">
+ <h4 class="card-header bg-secondary">Traceback</h4>
+ <div class="card-body">
+
+ {{ e }} <br><br>
+ {{ err }}
+ </div></div>
+ {% endif %}
+
+ {% if code != 5 %}
+
+ <div class="card mb-3 border-primary" style="max-width: 60rem;">
+ <h4 class="card-header bg-primary">../op25/gr-op25_repeater/apps/README</h4>
+ <div class="card-body" style="text-align: left;">
+
+ <h4>Setup SQL Log Database (Optional)</h4>
+ <p>
+
+ This addition provides a permanent server-side log of control channel
+ activity via logging to an SQL database. See the next section for details
+ on installing and using the log viewer.
+ </p>
+ <p>
+ 1. Make sure that sqlite3 is installed in python
+ </p>
+ <p>
+ 2. Initialize DB (any existing DB data will be destroyed)
+ </p>
+ <p>
+ WARNING: OP25 MUST NOT BE RUNNING DURING THIS STEP
+ </p>
+ <p>
+ op25/.../apps$ python sql_dbi.py reset_db
+ </p>
+ <p>
+ 3. Import talkgroups tags file
+ </p>
+ <p>
+ op25/.../apps$ python sql_dbi.py import_tgid tags.tsv
+ </p>
+ <p>
+ also, import the radio ID tags file (optional)
+ </p>
+ <p>
+ op25/.../apps$ python sql_dbi.py import_unit radio-tags.tsv
+ </p>
+ <p>
+ import the System ID tags file (see below)
+ </p>
+ <p>
+ op25/.../apps$ python sql_dbi.py import_sysid sysid-tags.tsv
+ </p>
+ <p>
+ The sysid tags must be a TSV file containing two columns
+ column 1 is the P25 trunked sysid (int, decimal)
+ colunn 2 is the System Name (text)
+ (Note: there is no header row line in this TSV file).
+ </p>
+ <p>
+ 4. Run op25 as usual. Logfile data should be inserted into DB in real time
+ and you should be able to view activity via the OP25 http console (once
+ the flask/datatables app has been set up; see next section).
+ </p>
+ </div>
+ </div>
+
+ {% endif %}
+ </div>
+</div>
+
+
+</div>
+
+<div id="secondary">
+ &nbsp;
+ </div>
+</div>
+</div>
+<!-- end secondary -->
+
+</div>
+<!-- end content -->
+
+</div>
+<br>
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block extra_javascripts %}
+
+{% endblock %} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/footer-links.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/footer-links.html
new file mode 100644
index 0000000..630c2af
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/footer-links.html
@@ -0,0 +1,17 @@
+<!-- footer links -->
+<div class="card border-primary mb-3">
+ <div class="card-body">
+ <div align="center">
+ <a href="{{ url_for('home') }}">Home</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('editsys') }}">System Tags</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('edit_tags') }}?cmd=tgid">Talkgroup Tags</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('edit_tags') }}?cmd=unit">Unit Tags</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('purge') }}">Purge</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('switch_db') }}">Backup & Switch</a>&nbsp;&nbsp;&nbsp;
+ <a href="{{ url_for('about') }}">About</a>
+ <br>
+ Server time: {{ t_loc() }} <br>
+ 08.29.2021
+ </div>
+ </div>
+</div> \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/home.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/home.html
new file mode 100644
index 0000000..64c7e91
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/home.html
@@ -0,0 +1,129 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+
+{% block content %}
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+
+ {% include "dbstats.html" %}
+
+
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header">Activity and Counts by Subscriber or Talkgroup</h4>
+ <div class="card-body">
+ <p class="card-text">
+ <button class="btnMain btn btn-outline-info" onclick="window.location.href='/logs?r=total_tgid'">Total Talkgroup<br>Voice Activity</button>
+ &nbsp;&nbsp;
+ <button class="btnMain btn btn-outline-info" onclick="window.location.href='/logs?r=call_detail'">Call<br>Detail</button>
+ &nbsp;&nbsp;
+ <button class="btnMain btn btn-outline-info" onclick="window.location.href='/logs?r=joins'">Join<br>Activity</button>
+ <hr style="height: 2px;">
+<!-- <input class="op-input" style="height: 62px; text-align: center; width: 210px; border: 1px solid orange; background-color: #333; color:#ccc;" placeholder="Enter SU or Talkgroup ID" type="text" id="resource_id"</input> -->
+
+ <div class="form-floating mb-3 primary" style="width: 215px;">
+ <input type="text" width="10" class="form-control" style="height: 62px;" id="resource_id" placeholder="">
+ <label for="floatingInput">TGID or SUID</label>
+ </div>
+
+ <button class="btnMain btn btn-outline-warning" onclick="this.blur(); load_new_page0('tgid');">SU ID Activity for Specified TGID</button>
+ &nbsp;&nbsp;
+ <button class="btnMain btn btn-outline-warning" onclick="this.blur(); load_new_page0('su');">Count of Calls by TGID for Specified SU ID</button>
+ <p><br>Note: The ID you enter can define a range of IDs to search, for example:
+ <br>
+ <ul>
+ <li>1234000-1234599 to search specified range</li>
+ </li>
+ <li>1234??? Search for matches between 1234000 and 1234999</li>
+ </ul>
+ </p>
+ </div>
+ </div>
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header">Control Channel Events</h4>
+ <div class="card-body">
+ Filter by talkgroup ID, subscriber ID, or both (optional):
+ <table style="width: 400px; padding: 0px;">
+ <tr>
+ <td style="vertical-align: top;">
+ <div class="form-floating mb-3 primary">
+ <input type="text" width="10" class="form-control" id="cc_filter_tgid" style="width: 150px;" placeholder="">
+ <label for="floatingInput">Talkgroup ID</label>
+ </div>
+ </td>
+ <td>
+ <div class="form-floating mb-3">
+ <input type="text" class="form-control" size="25" id="cc_filter_suid" style="width: 150px;" placeholder="">
+ <label for="floatingInput">Subscriber ID</label>
+ </div>
+ </td>
+ <td>&nbsp;&nbsp;
+ <button class="btn btn-primary" onclick="this.blur(); clrcc();">Clear</button>
+ </td>
+ </tr>
+ </table>
+<br>
+ <table>
+ {% for i in params['ekeys'] %}
+ <tr>
+ <td><button class="btnMain btn btn-outline-info" style="height: 38px;" onclick="this.blur(); load_new_page1('cc_event', '{{ i }}');">{{ i|replace("_", " ") }}</button></td>
+ <td>&nbsp;{{ params['cc_desc'][i] }} </td>
+ </tr>
+ {% endfor %}
+ </table>
+ </div>
+ </div>
+ {% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+
+
+
+
+<br>
+
+{% endblock %}
+
+<!-- js moved to op25.js -->
+
+{% block extra_javascripts %}
+
+<script>
+
+function clrcc() {
+ $('#cc_filter_tgid').val('');
+ $('#cc_filter_suid').val('');
+}
+</script>
+
+{% endblock %}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/inspect.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/inspect.html
new file mode 100644
index 0000000..72f6ad8
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/inspect.html
@@ -0,0 +1,18 @@
+<!-- Import TSV inspection -->
+{% if i|length == 0 %}
+<div class="alert alert-dismissible alert-danger" id="invtsv">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Invalid TSV</strong><br><br> The TSV is not valid for import.
+</div>
+{% else %}
+<div class="text-warning">Records: <b> {{ i|length }} </b></div><br>
+<table class="table table-hover">
+<th>ID</th>
+<th>Tag</th>
+<th>Priority/Color</th>
+{% for s in i %}
+<tr><td style="padding 2px; width: 150px;"> {{ s[0] }} </td><td style="padding 2px; width: 350px;"> {{ s[1] }} </td><td style="padding 2px;"> {{ s[2] }}</td></tr>
+{% endfor %}
+</table>
+<br>
+{% endif %} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/logs.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/logs.html
new file mode 100644
index 0000000..d4caf65
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/logs.html
@@ -0,0 +1,212 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+{% include 'base.html' %}
+{% block extra_stylesheets %}
+<link href="static/css/datatables/jquery.dataTables-dark.css" rel="stylesheet">
+{% endblock %}
+{% block content %}
+<div class="row-main">
+ <div class="main">
+<br>
+
+<br>
+ {% if params['r'] == 'su' %}
+ <h3>Count by Unit for SU ID {{ params['q'] }} {{ tag }}</h3>
+ {% elif params['r'] == 'joins' %}
+ <h3>Group Join Detail</h3>
+ {% elif params['r'] == 'cc_event' %}
+ <h3>CC Event Type: {{ params['cc_desc'][ params['p']] }}</h3>
+ {% if params['tgid'] != '0' or params['suid'] != '0' %}
+ Filtered by:
+ {% endif %}
+
+ {% if params['tgid'] != '0' %}
+ Talkgroup ID = {{ params['tgid'] }} &nbsp;&nbsp;
+ {% endif %}
+
+ {% if params['suid'] != '0' %}
+ Source ID = {{ params['suid'] }}
+ {% endif %}
+ {% elif params['r'] == 'total_tgid' %}
+ <h3>Total Talkgroup Voice Activity</h3>
+ {% elif params['r'] == 'call_detail' %}
+ <h3>Call Detail</h3>
+ Includes opcodes 0x00 and 0x02
+ {% else %}
+ <h3>Count by Unit for Talkgroup ID {{ params['q'] }} {{ tag }}</h3>
+ {% endif %}
+ <hr>
+ <table id="op25_logs" class="display" cellspacing="0" width="100%">
+ <thead>
+ <tr>
+ {% if params['r'] == 'tgid' %}
+ <th>Subscriber ID</th>
+ <th>Subscriber Tag</th>
+ <th>Count</th>
+ <th>Last Seen</th>
+ {% elif params['r'] == 'total_tgid' %}
+ <th>System ID</th>
+ <th>System</th>
+ <th>Talkgroup ID</th>
+ <th>Talkgroup</th>
+ <th>Count</th>
+ {% elif params['r'] == 'call_detail' %}
+ <th>Time</th>
+ <th>Opcode</th>
+ <th>System ID</th>
+ <th>System</th>
+ <th>Talkgrou ID</th>
+ <th>Talkgroup</th>
+ <th>Source ID</th>
+ <th>Source</th>
+ <th>Frequency</th>
+ {% elif params['r'] == 'joins' %}
+ <th>Time</th>
+ <th>Opcode</th>
+ <th>System ID</th>
+ <th>System</th>
+ <th>RV</th>
+ <th>Talkgrou ID</th>
+ <th>Talkgroup</th>
+ <th>Source ID</th>
+ <th>Source</th>
+ {% elif params['r'] == 'calls' %}
+ <th>Time</th>
+ <th>Sysid</th>
+ <th>Tgid</th>
+ <th>Talkgroup</th>
+ <th>Frequency</th>
+ <th>SU ID</th>
+
+ {% elif params['r'] == 'cc_event' %}
+ {% for i in params['ckeys'] %}
+ <th> {{ i }} </th>
+ {% endfor %}
+
+ {% else %}
+ <th>Talkgroup</th>
+ <th>TGID</th>
+ <th>Count</th>
+ {% endif %}
+ </tr>
+ </thead>
+ <tbody></tbody>
+ </table>
+
+<button onclick="this.blur(); csvTable('op25_logs')" class="btn btn-light btn-sm" title="Export current view to CSV.">Export CSV</button>
+
+</div>
+</div>
+
+{% endblock %}
+{% block extra_javascripts %}
+<!-- <script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script> -->
+<script src="static/js/datatables/jquery.dataTables.js"></script>
+<script type="text/javascript" charset="utf-8">
+ $(document).ready(function () {
+ var sd = sdate();
+ var ed = edate();
+ var sysid = $('#systemSelect').val();
+
+ var filter_tgid = {% if params['tgid'] is defined %}
+ {{ params['tgid'] }};
+ {% else %}
+ 0;
+ {% endif %}
+ var filter_suid = {% if params['suid'] is defined %}
+ {{ params['suid'] }};
+ {% else %}
+ 0;
+ {% endif %}
+
+ console.log('filter_tgid=' + filter_tgid);
+ console.log(typeof filter_tgid);
+ console.log('filter_suid=' + filter_suid);
+ console.log(typeof filter_suid);
+
+ var table = $('#op25_logs').DataTable({
+ "lengthMenu": [[10, 25, 50, 100, 500, 1000, 2500], [10, 25, 50, 100, 500, '1,000', '2,500']],
+ "processing": true,
+ "serverSide": true,
+
+ {% if params['p'] == 'grp_v_ch_grant' %}
+ "columns": [
+ null,
+ null,
+ null,
+ null,
+ { render: function(data){ return data / 1000000; }},
+ null,
+ null,
+ null,
+ null
+ ],
+ {% endif %}
+
+ {% if params['p'] == 'mot_grg_cn_grant' %}
+ "columns": [
+ null,
+ null,
+ null,
+ { render: function(data){ return data / 1000000; }},
+ null,
+ null,
+ null,
+ null
+ ],
+ {% endif %}
+
+ {% if params['r'] == 'call_detail' %}
+ "columns": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ { render: function(data){ return data / 1000000; } },
+ ],
+ {% endif %}
+
+
+ "ajax": {
+ "url": "{{ url_for('data') }}",
+ "data": {
+ "host_rid": "{{ params['q'] }}",
+ "host_function_type": "{{ params['r'] }}",
+ "host_function_param": "{{ params['p'] }}",
+ "sdate": sd,
+ "edate": ed,
+ "sysid": sysid,
+ "tgid": filter_tgid,
+ "suid": filter_suid
+ }
+ }
+ });
+ });
+</script>
+{% endblock %}
+<br><br><br>
+{% include 'footer-links.html' %} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/purge.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/purge.html
new file mode 100644
index 0000000..1a1f906
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/purge.html
@@ -0,0 +1,123 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+
+{% block content %}
+
+<div id="loading">
+ <img id="loading-image" src="static/loading.gif" height="35px" alt="Loading..." />
+ <br>Processing...
+</div>
+
+
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+
+ {% include "dbstats.html" %}
+
+
+ <div class="card mb-3 border-primary">
+ <h4 class="card-header bg-danger">Purge Database</h4>
+ <div class="card-body">
+ {% if successMessage == 1 %}
+ <div class="alert alert-dismissible alert-primary">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Operation completed.</strong> <span id="recCount">{{ recCount }}</span> records have been deleted.<br><br>Executed query:<br><br> {{ dispQuery }}</a>
+ {% if params['bu'] == 'true' %}
+ <br><br>Backup file created: {{ destfile }}
+ {% endif %}
+ </div>
+ {% endif %}
+ {% if successMessage == 2 %}
+ <div class="alert alert-dismissible alert-info">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Simulated operation completed.</strong> <span id="recCount">{{ recCount }}</span> records will be deleted.<br><br>Simulated query:<br><br> {{ dispQuery }}</a>
+ {% if params['bu'] == 'true' %}
+ <br><br>Simulated backup file created: {{ destfile }}
+ {% endif %}
+ </div>
+ {% endif %}
+ To purge records from the database, select the system, start date and end date above, then click Purge Database. Talkgroup and subscriber tags are not affected.
+ <Br><Br>
+ To prevent accidental data loss, a start date and end date are required.
+ <Br><Br>
+ <div class="form-check form-switch">
+ <input class="form-check-input" type="checkbox" id="keepVoice" checked="checked">
+ <label class="form-check-label" for="keepVoice"><b>Keep Voice Channel Grant Data</b></label>&nbsp;&nbsp;
+ When selected, all voice channel grant data will be saved.
+ <br>
+ <input class="form-check-input" type="checkbox" id="createBackup">
+ <label class="form-check-label" for="createBackup"><b>Create Database Backup File</b></label>&nbsp;&nbsp;
+ Create a backup of the database before purging.
+ </div>
+ <br>
+ <span class="text-danger"><b>FINAL WARNING:</b></span> Once you click "Purge Database", the action cannot be undone.</span></b><br><br>
+ <div align="center">
+ <button id="btnPurge" class="btnMain btn btn-danger" onclick="$('#processing').show(); purgeBtn(); this.blur; doPurge(false);">Purge<br>Database</button>
+ <button class="btnMain btn btn-warning" onclick="this.blur; doPurge(true);">Simulate Purge and<br>Display Query</button>
+ <button class="btnMain btn btn-success" onclick="this.blur; window.location.href='/'">Cancel<br>Purge</button>
+ </div><br>
+ <div align="center" id="processing" style="display: none;">
+ <img src="static/loading.gif" style="height: 20px;" alt="loading">
+ <br>Processing...<br>
+ </div>
+ </div>
+ </div>
+
+{% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+
+{% endblock %}
+
+<!-- js moved to op25.js -->
+
+<script>
+
+function purgeBtn() {
+ // full page modal while loading, or the little Processing icon below the buttons??
+ // $('#loading').show();
+}
+
+</script>
+
+
+
+
+{% block extra_javascripts %}
+
+<script>
+ x = $('#recCount').html();
+ $('#recCount').html(comma(x));
+</script>
+{% endblock %}
diff --git a/op25/gr-op25_repeater/apps/oplog/op25/templates/switch_db.html b/op25/gr-op25_repeater/apps/oplog/op25/templates/switch_db.html
new file mode 100644
index 0000000..a655757
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/op25/templates/switch_db.html
@@ -0,0 +1,129 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+
+{% include 'base.html' %}
+{% block extra_stylesheets %}
+<link href="static/css/datatables/jquery.dataTables-dark.css" rel="stylesheet">
+{% endblock %}
+
+{% block content %}
+
+<div class="row-main">
+ <div class="side">
+ &nbsp;
+ </div> <!-- end side -->
+
+ <div class="main">
+ <div class="card mb-3 border-primary">
+ <div class="card-body">
+
+ <div class="card mb-3 border-secondary">
+ <h5 class="card-header">Switch Database</h4>
+ <div class="card-body">
+ <p class="card-text">
+ Switch OP25 Logs database. This does not affect live sql logging in OP25. Database selection will persist with Flask session.<br>
+ </p>
+<br><div align="center">
+
+ Current database: {{ curr_file }}<br><br>
+
+<label for="selTsv">Choose db file:</label>
+ <select name="seldb" id="seldb">
+ <option value='0' >Select...</option>
+ {% for i in files %}
+ {% if '.db' in i and '._' not in i %}
+ <option value="{{ i }}">{{ i }}</option>
+ {% endif %}
+ {% endfor %}
+ </select>
+<br><br>
+<Br>
+<button class="btn btn-primary" onclick="this.blur(); switch_database();">Swtich Database</button>
+<button class="btn btn-primary" onclick="this.blur(); window.location.href='/'">Cancel</button>
+</div>
+
+</div>
+</div>
+ <div class="card mb-3 border-secondary">
+ <h5 class="card-header">Create Backup of Current Database</h4>
+ <div class="card-body">
+ <p class="card-text">
+ <div align="center">
+ Current database: {{ curr_file }}<br><br>
+ <button class="btn btn-primary" onclick="this.blur(); create_backup();">Create Backup Now</button>
+ </div>
+ <br>
+ {% if sm == 1 %}
+ <br>
+ <div class="alert alert-dismissible alert-success">
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ <strong>Backup Created.</strong><br><br>
+ New backup: <b> {{ destfile }}</b>
+ </div>
+ {{ clear_sm() }}
+ {% endif %}
+
+</div>
+</div>
+
+</div>
+</div>
+
+{% include 'footer-links.html' %}
+</div> <!-- end main -->
+
+ <div class="side">
+ &nbsp;
+ </div>
+</div> <!-- end row -->
+
+
+
+<script>
+
+ $(document).ready(function () {
+ $('#startDate').prop('disabled', true );
+ $('#endDate').prop('disabled', true );
+ $('#systemSelect').prop('disabled', true );
+ var sysid = $('#systemSelect4').val();
+ });
+
+ function switch_database() {
+ var file = $('#seldb').val();
+ if (file == '0')
+ return;
+ window.location.href='/switch_db?cmd=switch&file=' + file;
+ }
+
+
+ function create_backup() {
+ window.location.href='/switch_db?cmd=backup';
+ }
+
+</script>
+
+{% endblock %}
+
+{% block extra_javascripts %}
+{% endblock %}
+
diff --git a/op25/gr-op25_repeater/apps/oplog/oplog.sh b/op25/gr-op25_repeater/apps/oplog/oplog.sh
new file mode 100755
index 0000000..90d18c8
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/oplog.sh
@@ -0,0 +1,4 @@
+#! /bin/sh
+
+export FLASK_APP=op25
+FLASK_DEBUG=1 flask run --host=0.0.0.0
diff --git a/op25/gr-op25_repeater/apps/oplog/setup.py b/op25/gr-op25_repeater/apps/oplog/setup.py
new file mode 100644
index 0000000..491a5a6
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/oplog/setup.py
@@ -0,0 +1,30 @@
+import os
+
+from setuptools import find_packages, setup
+
+here = os.path.abspath(os.path.dirname(__file__))
+
+with open(os.path.join(here, "README.rst")) as f:
+ README = f.read()
+
+setup(
+ name="flask_tut",
+ version="0.0",
+ description="flask_tut",
+ long_description=README,
+ classifiers=[
+ "Programming Language :: Python",
+ "Framework :: Pyramid",
+ "Topic :: Internet :: WWW/HTTP",
+ "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
+ ],
+ author="",
+ author_email="",
+ url="",
+ keywords="web wsgi bfg flask",
+ packages=find_packages(),
+ include_package_data=True,
+ zip_safe=False,
+ test_suite="flask_tut",
+ install_requires=[],
+)
diff --git a/op25/gr-op25_repeater/apps/p25_decoder.py b/op25/gr-op25_repeater/apps/p25_decoder.py
index bb7dc51..c15b94f 100644
--- a/op25/gr-op25_repeater/apps/p25_decoder.py
+++ b/op25/gr-op25_repeater/apps/p25_decoder.py
@@ -27,7 +27,7 @@ P25 decoding block.
"""
import time
-from gnuradio import gr, gru, eng_notation
+from gnuradio import gr, eng_notation
from gnuradio import blocks, audio
from gnuradio.eng_option import eng_option
import op25
@@ -59,7 +59,8 @@ class p25_decoder_sink_b(gr.hier_block2):
do_msgq = False,
msgq = None,
audio_output = _def_audio_output,
- debug = _def_debug):
+ debug = _def_debug,
+ msgq_id = 0):
"""
Hierarchical block for P25 decoding.
@@ -67,7 +68,7 @@ class p25_decoder_sink_b(gr.hier_block2):
@type debug: int
"""
- gr.hier_block2.__init__(self, "p25_demod_c",
+ gr.hier_block2.__init__(self, "p25_demod_c",
gr.io_signature(1, 1, gr.sizeof_char), # Input signature
gr.io_signature(0, 0, 0)) # Output signature
@@ -77,9 +78,16 @@ class p25_decoder_sink_b(gr.hier_block2):
self.debug = debug
self.dest = dest
do_output = False
+ do_audio_output = False
+ do_phase2_tdma = False
if dest == 'wav':
do_output = True
- do_audio_output = True
+
+ if do_imbe:
+ do_audio_output = True
+
+ if num_ambe > 0:
+ do_phase2_tdma = True
if msgq is None:
msgq = gr.msg_queue(1)
@@ -92,8 +100,8 @@ class p25_decoder_sink_b(gr.hier_block2):
num_decoders = 1
if num_ambe > 1:
num_decoders += num_ambe - 1
- for slot in xrange(num_decoders):
- self.p25_decoders.append(op25_repeater.p25_frame_assembler(wireshark_host, udp_port, debug, do_imbe, do_output, do_msgq, msgq, do_audio_output, True))
+ for slot in range(num_decoders):
+ self.p25_decoders.append(op25_repeater.p25_frame_assembler(wireshark_host, udp_port, debug, do_imbe, do_output, do_msgq, msgq, do_audio_output, do_phase2_tdma, msgq_id+slot))
self.p25_decoders[slot].set_slotid(slot)
self.xorhash.append('')
@@ -123,6 +131,9 @@ class p25_decoder_sink_b(gr.hier_block2):
return
self.audio_sink[index].open(filename)
+ def set_nac(self, nac, index=0):
+ self.p25_decoders[index].set_nac(nac)
+
def set_xormask(self, xormask, xorhash, index=0):
if self.xorhash[index] == xorhash:
return
diff --git a/op25/gr-op25_repeater/apps/p25_demodulator.py b/op25/gr-op25_repeater/apps/p25_demodulator.py
index 646d621..046aaaf 100644
--- a/op25/gr-op25_repeater/apps/p25_demodulator.py
+++ b/op25/gr-op25_repeater/apps/p25_demodulator.py
@@ -2,7 +2,7 @@
# Copyright 2005,2006,2007 Free Software Foundation, Inc.
#
# OP25 Demodulator Block
-# Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015 Max H. Parke KA1RBI
+# Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
#
# This file is part of GNU Radio and part of OP25
#
@@ -27,8 +27,8 @@ P25 C4FM/CQPSK demodulation block.
"""
import sys
-from gnuradio import gr, gru, eng_notation
-from gnuradio import filter, analog, digital, blocks
+from gnuradio import gr, eng_notation
+from gnuradio import filter, analog, digital, blocks, fft
from gnuradio.eng_option import eng_option
import op25
import op25_repeater
@@ -45,14 +45,40 @@ _def_costas_alpha = 0.04
_def_symbol_rate = 4800
_def_symbol_deviation = 600.0
_def_bb_gain = 1.0
+_def_excess_bw = 0.2
+
+_def_gmsk_mu = None
+_def_mu = 0.5
+_def_freq_error = 0.0
+_def_omega_relative_limit = 0.005
# /////////////////////////////////////////////////////////////////////////////
# demodulator
# /////////////////////////////////////////////////////////////////////////////
+def get_decim(speed):
+ s = int(speed)
+ if_freqs = [24000, 25000, 32000]
+ for i_f in if_freqs:
+ if s % i_f != 0:
+ continue
+ q = s // i_f
+ if q & 1:
+ continue
+ if q >= 40 and q & 3 == 0:
+ decim = q//4
+ decim2 = 4
+ else:
+ decim = q//2
+ decim2 = 2
+ return decim, decim2
+ return None
+
class p25_demod_base(gr.hier_block2):
def __init__(self,
if_rate = None,
+ filter_type = None,
+ excess_bw = _def_excess_bw,
symbol_rate = _def_symbol_rate):
"""
Hierarchical block for P25 demodulation base class
@@ -62,41 +88,86 @@ class p25_demod_base(gr.hier_block2):
"""
self.if_rate = if_rate
self.symbol_rate = symbol_rate
- self.bb_sink = None
+ self.bb_sinks = []
self.baseband_amp = blocks.multiply_const_ff(_def_bb_gain)
coeffs = op25_c4fm_mod.c4fm_taps(sample_rate=self.if_rate, span=9, generator=op25_c4fm_mod.transfer_function_rx).generate()
- self.symbol_filter = filter.fir_filter_fff(1, coeffs)
- autotuneq = gr.msg_queue(2)
- self.fsk4_demod = op25.fsk4_demod_ff(autotuneq, self.if_rate, self.symbol_rate)
+ sps = self.if_rate // self.symbol_rate
+ if filter_type == 'rrc':
+ ntaps = 7 * sps
+ if ntaps & 1 == 0:
+ ntaps += 1
+ coeffs = filter.firdes.root_raised_cosine(1.0, if_rate, symbol_rate, excess_bw, ntaps)
+ coeffs = [x*1.5 for x in coeffs]
+ if filter_type == 'nxdn':
+ coeffs = op25_c4fm_mod.c4fm_taps(sample_rate=self.if_rate, span=9, generator=op25_c4fm_mod.transfer_function_nxdn, symbol_rate=self.symbol_rate).generate()
+ gain_adj = 1.8 # for nxdn48 6.25 KHz
+ if self.symbol_rate == 4800:
+ gain_adj = 0.77 # nxdn96 12.5 KHz
+ coeffs = coeffs * gain_adj
+ if filter_type == 'gmsk':
+ # lifted from gmsk.py
+ _omega = sps
+ _gain_mu = _def_gmsk_mu
+ _mu = _def_mu
+ if not _gain_mu:
+ _gain_mu = 0.175
+ _gain_omega = .25 * _gain_mu * _gain_mu # critically damped
+ self.symbol_filter = blocks.multiply_const_ff(1.0)
+ self.fsk4_demod = digital.clock_recovery_mm_ff(_omega, _gain_omega,
+ _mu, _gain_mu,
+ _def_omega_relative_limit)
+ self.slicer = digital.binary_slicer_fb()
+ elif filter_type == 'fsk4mm':
+ self.symbol_filter = filter.fir_filter_fff(1, coeffs)
+ _omega = sps
+ _gain_mu = _def_gmsk_mu
+ _mu = _def_mu
+ if not _gain_mu:
+ _gain_mu = 0.0175
+ _gain_omega = .25 * _gain_mu * _gain_mu # critically damped
+ self.fsk4_demod = digital.clock_recovery_mm_ff(_omega, _gain_omega,
+ _mu, _gain_mu,
+ _def_omega_relative_limit)
+ levels = [ -2.0, 0.0, 2.0, 4.0 ]
+ self.slicer = op25_repeater.fsk4_slicer_fb(levels)
+ else:
+ self.symbol_filter = filter.fir_filter_fff(1, coeffs)
+ autotuneq = gr.msg_queue(2)
+ self.fsk4_demod = op25.fsk4_demod_ff(autotuneq, self.if_rate, self.symbol_rate)
+ levels = [ -2.0, 0.0, 2.0, 4.0 ]
+ self.slicer = op25_repeater.fsk4_slicer_fb(levels)
- levels = [ -2.0, 0.0, 2.0, 4.0 ]
- self.slicer = op25_repeater.fsk4_slicer_fb(levels)
+ def set_symbol_rate(self, rate):
+ self.symbol_rate = rate
def set_baseband_gain(self, k):
self.baseband_amp.set_k(k)
def disconnect_bb(self):
# assumes lock held or init
- if not self.bb_sink:
+ if not len(self.bb_sinks):
return
- self.disconnect(self.bb_sink[0], self.bb_sink[1])
- self.bb_sink = None
+ for t in self.bb_sinks:
+ self.disconnect(t[0], t[1])
+ self.bb_sinks = []
def connect_bb(self, src, sink):
# assumes lock held or init
- self.disconnect_bb()
if src == 'symbol_filter':
- self.connect(self.symbol_filter, sink)
- self.bb_sink = [self.symbol_filter, sink]
+ b = self.symbol_filter
elif src == 'baseband_amp':
- self.connect(self.baseband_amp, sink)
- self.bb_sink = [self.baseband_amp, sink]
+ b = self.baseband_amp
+ self.connect(b, sink)
+ self.bb_sinks.append([b, sink])
class p25_demod_fb(p25_demod_base):
def __init__(self,
input_rate = None,
+ filter_type = None,
+ excess_bw = _def_excess_bw,
+ if_rate = _def_if_rate,
symbol_rate = _def_symbol_rate):
"""
Hierarchical block for P25 demodulation.
@@ -106,16 +177,25 @@ class p25_demod_fb(p25_demod_base):
@type input_rate: int
"""
- gr.hier_block2.__init__(self, "p25_demod_fb",
+ gr.hier_block2.__init__(self, "p25_demod_fb",
gr.io_signature(1, 1, gr.sizeof_float), # Input signature
gr.io_signature(1, 1, gr.sizeof_char)) # Output signature
- p25_demod_base.__init__(self, if_rate=input_rate, symbol_rate=symbol_rate)
+ p25_demod_base.__init__(self, if_rate=if_rate, symbol_rate=symbol_rate, filter_type=filter_type)
self.input_rate = input_rate
+ self.if_rate = if_rate
self.float_sink = None
-
- self.connect(self, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer, self)
+ if input_rate != if_rate:
+ assert if_rate < input_rate
+ assert input_rate % if_rate == 0 ### input rate must be multiple of if rate
+ decim = input_rate // if_rate
+ maxf = min(if_rate // 2, 6000) ### lpf cutoff at most 6 KHz
+ lpf_coeffs = filter.firdes.low_pass(1.0, input_rate, maxf, maxf//8, filter.firdes.WIN_HAMMING)
+ self.bb_decim = filter.fir_filter_fff(decim, lpf_coeffs)
+ self.connect(self, self.bb_decim, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer, self)
+ else:
+ self.connect(self, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer, self)
def disconnect_float(self):
# assumes lock held or init
@@ -135,12 +215,15 @@ class p25_demod_cb(p25_demod_base):
def __init__(self,
input_rate = None,
demod_type = 'cqpsk',
+ filter_type = None,
+ excess_bw = _def_excess_bw,
relative_freq = 0,
offset = 0,
if_rate = _def_if_rate,
gain_mu = _def_gain_mu,
costas_alpha = _def_costas_alpha,
- symbol_rate = _def_symbol_rate):
+ symbol_rate = _def_symbol_rate,
+ use_old_decim = False):
"""
Hierarchical block for P25 demodulation.
@@ -149,11 +232,11 @@ class p25_demod_cb(p25_demod_base):
@type input_rate: int
"""
- gr.hier_block2.__init__(self, "p25_demod_cb",
+ gr.hier_block2.__init__(self, "p25_demod_cb",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_char)) # Output signature
# gr.io_signature(0, 0, 0)) # Output signature
- p25_demod_base.__init__(self, if_rate=if_rate, symbol_rate=symbol_rate)
+ p25_demod_base.__init__(self, if_rate=if_rate, symbol_rate=symbol_rate, filter_type=filter_type)
self.input_rate = input_rate
self.if_rate = if_rate
@@ -164,25 +247,65 @@ class p25_demod_cb(p25_demod_base):
self.lo_freq = 0
self.float_sink = None
self.complex_sink = None
+ self.if1 = 0
+ self.if2 = 0
+ self.t_cache = {}
+ if filter_type == 'rrc':
+ self.set_baseband_gain(0.61)
- # local osc
- self.lo = analog.sig_source_c (input_rate, analog.GR_SIN_WAVE, 0, 1.0, 0)
self.mixer = blocks.multiply_cc()
- lpf_coeffs = filter.firdes.low_pass(1.0, input_rate, 7250, 725, filter.firdes.WIN_HANN)
- decimation = int(input_rate / if_rate)
- self.lpf = filter.fir_filter_ccf(decimation, lpf_coeffs)
-
- resampled_rate = float(input_rate) / float(decimation) # rate at output of self.lpf
-
- self.arb_resampler = filter.pfb.arb_resampler_ccf(
- float(self.if_rate) / resampled_rate)
-
- self.connect(self, (self.mixer, 0))
- self.connect(self.lo, (self.mixer, 1))
- self.connect(self.mixer, self.lpf, self.arb_resampler)
+ if use_old_decim:
+ decimator_values = None # disable two stage decimator
+ else:
+ decimator_values = get_decim(input_rate)
+ if decimator_values:
+ self.decim, self.decim2 = decimator_values
+ self.if1 = input_rate / self.decim
+ self.if2 = self.if1 / self.decim2
+ sys.stderr.write( 'Using two-stage decimator for speed=%d, decim=%d/%d if1=%d if2=%d\n' % (input_rate, self.decim, self.decim2, self.if1, self.if2))
+ bpf_coeffs = filter.firdes.complex_band_pass(1.0, input_rate, -self.if1/2, self.if1/2, self.if1/2, filter.firdes.WIN_HAMMING)
+ self.t_cache[0] = bpf_coeffs
+ fa = 6250
+ fb = self.if2 / 2
+ if filter_type == 'nxdn' and self.symbol_rate == 2400: # nxdn48 6.25 KHz
+ fa = 3125
+ lpf_coeffs = filter.firdes.low_pass(1.0, self.if1, (fb+fa)/2, fb-fa, filter.firdes.WIN_HAMMING)
+ self.bpf = filter.fir_filter_ccc(self.decim, bpf_coeffs)
+ self.lpf = filter.fir_filter_ccf(self.decim2, lpf_coeffs)
+ resampled_rate = self.if2
+ self.relative_limit = (input_rate // 2) - (self.if1 // 2)
+ self.bfo = analog.sig_source_c (self.if1, analog.GR_SIN_WAVE, 0, 1.0, 0)
+ self.connect(self, self.bpf, (self.mixer, 0))
+ self.connect(self.bfo, (self.mixer, 1))
+ else:
+ sys.stderr.write( 'Unable to use two-stage decimator for speed=%d\n' % (input_rate))
+ # local osc
+ self.lo = analog.sig_source_c (input_rate, analog.GR_SIN_WAVE, 0, 1.0, 0)
+ f1 = 7250
+ f2 = 1450
+ if filter_type == 'nxdn' and self.symbol_rate == 2400: # nxdn48 6.25 KHz
+ f1 = 3125
+ f2 = 625
+ lpf_coeffs = filter.firdes.low_pass(1.0, input_rate, f1, f2, filter.firdes.WIN_HANN)
+ decimation = int(input_rate / if_rate)
+ self.lpf = filter.fir_filter_ccf(decimation, lpf_coeffs)
+ resampled_rate = float(input_rate) / float(decimation) # rate at output of self.lpf
+ self.relative_limit = (input_rate // 2) - f1
+ self.connect(self, (self.mixer, 0))
+ self.connect(self.lo, (self.mixer, 1))
+ self.connect(self.mixer, self.lpf)
+
+
+ if self.if_rate != resampled_rate:
+ self.if_out = filter.pfb.arb_resampler_ccf(float(self.if_rate) / resampled_rate)
+ self.connect(self.lpf, self.if_out)
+ else:
+ self.if_out = self.lpf
- levels = [ -2.0, 0.0, 2.0, 4.0 ]
- self.slicer = op25_repeater.fsk4_slicer_fb(levels)
+ fa = 6250
+ fb = fa + 625
+ cutoff_coeffs = filter.firdes.low_pass(1.0, self.if_rate, (fb+fa)/2, fb-fa, filter.firdes.WIN_HANN)
+ self.cutoff = filter.fir_filter_ccf(1, cutoff_coeffs)
omega = float(self.if_rate) / float(self.symbol_rate)
gain_omega = 0.1 * gain_mu * gain_mu
@@ -214,31 +337,62 @@ class p25_demod_cb(p25_demod_base):
self.set_relative_frequency(relative_freq)
+ def get_error_band(self):
+ return int(self.clock.get_error_band())
+
+ def get_freq_error(self): # get error in Hz (approx).
+ return int(self.clock.get_freq_error() * self.symbol_rate)
+
+ def is_muted(self):
+ return self.clock.is_muted()
+
+ def set_muted(self, v):
+ self.clock.set_muted(v)
+
def set_omega(self, omega):
sps = self.if_rate / float(omega)
if sps == self.sps:
return
self.sps = sps
- print 'set_omega %d %f' % (omega, sps)
+ print ('set_omega %d %f' % (omega, sps))
self.clock.set_omega(self.sps)
def set_relative_frequency(self, freq):
- if abs(freq) > self.input_rate/2:
+ N = 500 # Hz, we tune the bpf in discrete steps of size N
+ if abs(freq) > self.relative_limit:
#print 'set_relative_frequency: error, relative frequency %d exceeds limit %d' % (freq, self.input_rate/2)
return False
if freq == self.lo_freq:
return True
- #print 'set_relative_frequency', freq
self.lo_freq = freq
- self.lo.set_frequency(self.lo_freq)
+ if self.if1:
+ r = freq % N
+ bpf_freq = freq - r
+ if r > N//2:
+ bpf_freq += N # round to nearest N Hz
+ if bpf_freq not in self.t_cache.keys():
+ if abs(bpf_freq) > self.relative_limit:
+ sys.stderr.write( 'set_relative_frequency: error, relative frequency %d(%d) exceeds limit %d\n' % (bpf_freq, freq, self.relative_limit))
+ return False
+ self.t_cache[bpf_freq] = filter.firdes.complex_band_pass(1.0, self.input_rate, -bpf_freq - self.if1/2, -bpf_freq + self.if1/2, self.if1/2, filter.firdes.WIN_HAMMING)
+ self.bpf.set_taps(self.t_cache[bpf_freq])
+ bfo_f = self.decim * -freq / float(self.input_rate)
+ bfo_f -= int(bfo_f)
+ while bfo_f < -0.5:
+ bfo_f += 1.0
+ while bfo_f > 0.5:
+ bfo_f -= 1.0
+ self.bfo.set_frequency(-bfo_f * self.if1)
+ else:
+ self.lo.set_frequency(self.lo_freq)
return True
# assumes lock held or init
def disconnect_chain(self):
if self.connect_state == 'cqpsk':
- self.disconnect(self.arb_resampler, self.agc, self.clock, self.diffdec, self.to_float, self.rescale, self.slicer)
+ self.disconnect(self.if_out, self.cutoff, self.agc, self.clock, self.diffdec, self.to_float, self.rescale, self.slicer)
elif self.connect_state == 'fsk4':
- self.disconnect(self.arb_resampler, self.fm_demod, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer)
+ self.disconnect(self.if_out, self.cutoff, self.fm_demod, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer)
self.connect_state = None
# assumes lock held or init
@@ -248,11 +402,11 @@ class p25_demod_cb(p25_demod_base):
self.disconnect_chain()
self.connect_state = demod_type
if demod_type == 'fsk4':
- self.connect(self.arb_resampler, self.fm_demod, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer)
+ self.connect(self.if_out, self.cutoff, self.fm_demod, self.baseband_amp, self.symbol_filter, self.fsk4_demod, self.slicer)
elif demod_type == 'cqpsk':
- self.connect(self.arb_resampler, self.agc, self.clock, self.diffdec, self.to_float, self.rescale, self.slicer)
+ self.connect(self.if_out, self.cutoff, self.agc, self.clock, self.diffdec, self.to_float, self.rescale, self.slicer)
else:
- print 'connect_chain failed, type: %s' % demod_type
+ print ('connect_chain failed, type: %s' % demod_type)
assert 0 == 1
if self.float_sink is not None:
self.connect_float(self.float_sink[1])
@@ -274,28 +428,24 @@ class p25_demod_cb(p25_demod_base):
self.connect(self.fsk4_demod, sink)
self.float_sink = [self.fsk4_demod, sink]
else:
- print 'connect_float: state error', self.connect_state
+ print ('connect_float: state error', self.connect_state)
assert 0 == 1
- def disconnect_complex(self):
- # assumes lock held or init
- if not self.complex_sink:
- return
- self.disconnect(self.complex_sink[0], self.complex_sink[1])
- self.complex_sink = None
-
def connect_complex(self, src, sink):
# assumes lock held or init
- self.disconnect_complex()
if src == 'clock':
self.connect(self.clock, sink)
- self.complex_sink = [self.clock, sink]
elif src == 'diffdec':
self.connect(self.diffdec, sink)
- self.complex_sink = [self.diffdec, sink]
elif src == 'mixer':
- self.connect(self.mixer, sink)
- self.complex_sink = [self.mixer, sink]
+ self.connect(self.agc, sink)
elif src == 'src':
self.connect(self, sink)
- self.complex_sink = [self, sink]
+ elif src == 'bpf':
+ self.connect(self.bpf, sink)
+ elif src == 'if_out':
+ self.connect(self.if_out, sink)
+ elif src == 'agc':
+ self.connect(self.agc, sink)
+ elif src == 'cutoff':
+ self.connect(self.cutoff, sink)
diff --git a/op25/gr-op25_repeater/apps/plot-colors.json b/op25/gr-op25_repeater/apps/plot-colors.json
new file mode 100644
index 0000000..dca2dd0
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/plot-colors.json
@@ -0,0 +1,7 @@
+{
+ "label_color": "#ffffff",
+ "tic_color": "#cccccc",
+ "border_color": "#cccccc",
+ "plot_color": "#00a000",
+ "background_color": "#000000"
+}
diff --git a/op25/gr-op25_repeater/apps/runudp.sh b/op25/gr-op25_repeater/apps/runudp.sh
new file mode 100644
index 0000000..7ece287
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/runudp.sh
@@ -0,0 +1,7 @@
+#! /bin/sh
+
+t="-T 900.tsv"
+sr="-S 120000"
+v="-v 255"
+
+python3 rx.py --args "udp:127.0.0.1:25252" -f 924975000 $sr -q 0 -D fsk4 -P "datascope" -V -w -v 255 $t $v 2> stderr.2
diff --git a/op25/gr-op25_repeater/apps/rx.py b/op25/gr-op25_repeater/apps/rx.py
index 95f7cfe..56e4ac0 100755
--- a/op25/gr-op25_repeater/apps/rx.py
+++ b/op25/gr-op25_repeater/apps/rx.py
@@ -1,8 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2008-2011 Steve Glass
#
-# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
#
# Copyright 2003,2004,2005,2006 Free Software Foundation, Inc.
# (from radiorausch)
@@ -44,7 +44,7 @@ try:
except:
pass
-from gnuradio import audio, eng_notation, gr, gru, filter, blocks, fft, analog, digital
+from gnuradio import audio, eng_notation, gr, filter, blocks, fft, analog, digital
from gnuradio.eng_option import eng_option
from math import pi
from optparse import OptionParser
@@ -64,9 +64,14 @@ from gr_gnuplot import constellation_sink_c
from gr_gnuplot import fft_sink_c
from gr_gnuplot import symbol_sink_f
from gr_gnuplot import eye_sink_f
+from gr_gnuplot import mixer_sink_c
+from gr_gnuplot import setup_correlation
+from gr_gnuplot import sync_plot
-from terminal import curses_terminal
-from sockaudio import socket_audio
+from terminal import op25_terminal
+from sockaudio import audio_thread
+
+from sql_dbi import sql_dbi
#speeds = [300, 600, 900, 1200, 1440, 1800, 1920, 2400, 2880, 3200, 3600, 3840, 4000, 4800, 6000, 6400, 7200, 8000, 9600, 14400, 19200]
speeds = [4800, 6000]
@@ -75,101 +80,106 @@ os.environ['IMBE'] = 'soft'
WIRESHARK_PORT = 23456
+_def_interval = 3.0 # sec
+_def_file_dir = '../www/images'
+_def_error_update_time = 3.0 # freq error tracking interval
+_def_lo_adj_limit = 2500 # Hz
+
+class udp_source_c(gr.hier_block2):
+ def __init__(self, hostname, udp_port):
+ gr.hier_block2.__init__(self, "udp_source_c",
+ gr.io_signature(0, 0, 0), # Input signature
+ gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
+ bufsize = 32000
+ self.src = blocks.udp_source(gr.sizeof_gr_complex, hostname, udp_port, payload_size = bufsize)
+ self.sample_rate = 0
+ self.connect(self.src, self)
+
+ def set_center_freq(self, f):
+ sys.stderr.write('udp source: set_center_freq(%s) ignored\n' % f)
+
+ def set_bandwidth(self, f):
+ sys.stderr.write('udp source: set_bandwidth(%s) ignored\n' % f)
+
+ def set_sample_rate(self, f):
+ self.sample_rate = f
+ return f
+
+ def set_antenna(self, a):
+ sys.stderr.write('udp source: set_antenna(%s) ignored\n' % a)
+
# The P25 receiver
#
class p25_rx_block (gr.top_block):
# Initialize the P25 receiver
#
- def __init__(self):
+ def __init__(self, options):
self.trunk_rx = None
- self.kill_sink = None
+ self.plot_sinks = []
gr.top_block.__init__(self)
- # command line argument parsing
- parser = OptionParser(option_class=eng_option)
- parser.add_option("--args", type="string", default="", help="device args")
- parser.add_option("--antenna", type="string", default="", help="select antenna")
- parser.add_option("-a", "--audio", action="store_true", default=False, help="use direct audio input")
- parser.add_option("-A", "--audio-if", action="store_true", default=False, help="soundcard IF mode (use --calibration to set IF freq)")
- parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp")
- parser.add_option("-i", "--input", default=None, help="input file name")
- parser.add_option("-b", "--excess-bw", type="eng_float", default=0.2, help="for RRC filter", metavar="Hz")
- parser.add_option("-c", "--calibration", type="eng_float", default=0.0, help="USRP offset or audio IF frequency", metavar="Hz")
- parser.add_option("-C", "--costas-alpha", type="eng_float", default=0.04, help="value of alpha for Costas loop", metavar="Hz")
- parser.add_option("-D", "--demod-type", type="choice", default="cqpsk", choices=('cqpsk', 'fsk4'), help="cqpsk | fsk4")
- parser.add_option("-P", "--plot-mode", type="choice", default=None, choices=(None, 'constellation', 'fft', 'symbol', 'datascope'), help="constellation | fft | symbol | datascope")
- parser.add_option("-f", "--frequency", type="eng_float", default=0.0, help="USRP center frequency", metavar="Hz")
- parser.add_option("-F", "--ifile", type="string", default=None, help="read input from complex capture file")
- parser.add_option("-H", "--hamlib-model", type="int", default=None, help="specify model for hamlib")
- parser.add_option("-s", "--seek", type="int", default=0, help="ifile seek in K")
- parser.add_option("-L", "--logfile-workers", type="int", default=None, help="number of demodulators to instantiate")
- parser.add_option("-S", "--sample-rate", type="int", default=320e3, help="source samp rate")
- parser.add_option("-t", "--tone-detect", action="store_true", default=False, help="use experimental tone detect algorithm")
- parser.add_option("-T", "--trunk-conf-file", type="string", default=None, help="trunking config file name")
- parser.add_option("-v", "--verbosity", type="int", default=0, help="message debug level")
- parser.add_option("-V", "--vocoder", action="store_true", default=False, help="voice codec")
- parser.add_option("-o", "--offset", type="eng_float", default=0.0, help="tuning offset frequency [to circumvent DC offset]", metavar="Hz")
- parser.add_option("-p", "--pause", action="store_true", default=False, help="block on startup")
- parser.add_option("-w", "--wireshark", action="store_true", default=False, help="output data to Wireshark")
- parser.add_option("-W", "--wireshark-host", type="string", default="127.0.0.1", help="Wireshark host")
- parser.add_option("-r", "--raw-symbols", type="string", default=None, help="dump decoded symbols to file")
- parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0), help="select USRP Rx side A or B (default=A)")
- parser.add_option("-g", "--gain", type="eng_float", default=None, help="set USRP gain in dB (default is midpoint) or set audio gain")
- parser.add_option("-G", "--gain-mu", type="eng_float", default=0.025, help="gardner gain")
- parser.add_option("-N", "--gains", type="string", default=None, help="gain settings")
- parser.add_option("-O", "--audio-output", type="string", default="default", help="audio output device name")
- parser.add_option("-U", "--udp-player", action="store_true", default=False, help="enable built-in udp audio player")
- parser.add_option("-q", "--freq-corr", type="eng_float", default=0.0, help="frequency correction")
- parser.add_option("-d", "--fine-tune", type="eng_float", default=0.0, help="fine tuning")
- parser.add_option("-2", "--phase2-tdma", action="store_true", default=False, help="enable phase2 tdma decode")
- parser.add_option("-Z", "--decim-amt", type="int", default=1, help="spectrum decimation")
- (options, args) = parser.parse_args()
- if len(args) != 0:
- parser.print_help()
- sys.exit(1)
-
self.channel_rate = 0
self.baseband_input = False
self.rtl_found = False
self.channel_rate = options.sample_rate
self.fft_sink = None
+ self.last_error_update = 0
+ self.error_band = 0
+ self.tuning_error = 0
+ self.freq_correction = 0
+ self.last_set_freq = 0
+ self.last_set_freq_at = time.time()
+ self.last_change_freq = 0
+ self.last_change_freq_at = time.time()
+ self.last_freq_params = {'freq' : 0.0, 'tgid' : None, 'tag' : "", 'tdma' : None}
+ self.next_status_png = time.time()
+ self.last_process_update = 0
+ self.sql_db = sql_dbi()
+ self.last_center_freq = 0
+ self.last_relative_freq = 0
self.src = None
- if not options.input:
+ if (not options.input) and (not options.audio) and (not options.audio_if) and (not options.args.startswith('udp:')):
# check if osmocom is accessible
try:
import osmosdr
self.src = osmosdr.source(options.args)
except Exception:
- print "osmosdr source_c creation failure"
+ print ("osmosdr source_c creation failure")
ignore = True
- if "rtl" in options.args.lower():
- #print "'rtl' has been found in options.args (%s)" % (options.args)
+ if any(x in options.args.lower() for x in ['rtl', 'airspy', 'hackrf', 'uhd']):
+ #print ("'rtl' has been found in options.args (%s)" % (options.args))
self.rtl_found = True
gain_names = self.src.get_gain_names()
- for name in gain_names:
- range = self.src.get_gain_range(name)
- print "gain: name: %s range: start %d stop %d step %d" % (name, range[0].start(), range[0].stop(), range[0].step())
+ if 0: # pending fix crash ### for name in gain_names:
+ range1 = self.src.get_gain_range(name)
+ print ("gain: name: %s range: start %d stop %d step %d" % (name, range1[0].start(), range1[0].stop(), range1[0].step()))
if options.gains:
- for tuple in options.gains.split(","):
- name, gain = tuple.split(":")
+ for tup in options.gains.split(","):
+ name, gain = tup.split(":")
gain = int(gain)
- print "setting gain %s to %d" % (name, gain)
+ print ("setting gain %s to %d" % (name, gain))
self.src.set_gain(gain, name)
rates = self.src.get_sample_rates()
try:
- print 'supported sample rates %d-%d step %d' % (rates.start(), rates.stop(), rates.step())
+ print ('supported sample rates %d-%d step %d' % (rates.start(), rates.stop(), rates.step()))
except:
pass # ignore
if options.freq_corr:
self.src.set_freq_corr(options.freq_corr)
+ elif (not options.input) and (not options.audio) and (not options.audio_if) and options.args.startswith('udp:'):
+ hostinfo = options.args.split(':')
+ hostname = hostinfo[1]
+ udp_port = int(hostinfo[2])
+ self.src = udp_source_c(hostname, udp_port)
+ sys.stderr.write('started udp listener: %s %s\n' % (hostname, udp_port))
if options.audio:
self.channel_rate = 48000
@@ -184,8 +194,9 @@ class p25_rx_block (gr.top_block):
# setup (read-only) attributes
self.symbol_rate = 4800
self.symbol_deviation = 600.0
- self.basic_rate = 48000
+ self.basic_rate = 24000
_default_speed = 4800
+ self.options = options
# keep track of flow graph connections
self.cnxns = []
@@ -195,9 +206,7 @@ class p25_rx_block (gr.top_block):
self.constellation_scope_connected = False
- self.options = options
-
- for i in xrange(len(speeds)):
+ for i in range(len(speeds)):
if speeds[i] == _default_speed:
self.current_speed = i
self.default_speed_idx = i
@@ -207,32 +216,34 @@ class p25_rx_block (gr.top_block):
# wait for gdb
if options.pause:
- print 'Ready for GDB to attach (pid = %d)' % (os.getpid(),)
+ print ('Ready for GDB to attach (pid = %d)' % (os.getpid(),))
raw_input("Press 'Enter' to continue...")
- self.input_q = gr.msg_queue(10)
+ self.input_q = gr.msg_queue(20)
self.output_q = gr.msg_queue(10)
# configure specified data source
if options.input:
self.open_file(options.input)
- elif options.frequency:
- self.open_usrp()
elif options.audio_if:
self.open_audio_c(self.channel_rate, options.gain, options.audio_input)
elif options.audio:
self.open_audio(self.channel_rate, options.gain, options.audio_input)
elif options.ifile:
self.open_ifile(self.channel_rate, options.gain, options.ifile, options.seek)
+ elif (self.rtl_found or options.frequency):
+ self.open_usrp()
else:
pass
- # attach terminal thread
- self.terminal = curses_terminal(self.input_q, self.output_q)
+ # attach terminal thread and make sure currently tuned frequency is displayed
+ self.terminal = op25_terminal(self.input_q, self.output_q, self.options.terminal_type)
+ if self.terminal is None:
+ sys.stderr.write('warning: no terminal attached\n')
# attach audio thread
if self.options.udp_player:
- self.audio = socket_audio("127.0.0.1", WIRESHARK_PORT, self.options.audio_output)
+ self.audio = audio_thread("127.0.0.1", self.options.wireshark_port, self.options.audio_output, False, self.options.audio_gain)
else:
self.audio = None
@@ -241,72 +252,98 @@ class p25_rx_block (gr.top_block):
def __build_graph(self, source, capture_rate):
global speeds
global WIRESHARK_PORT
- # tell the scope the source rate
+
+ sps = 5 # samples / symbol
+ if_rate = sps * 4800
self.rx_q = gr.msg_queue(100)
udp_port = 0
- if self.options.udp_player or self.options.wireshark or (self.options.wireshark_host != "127.0.0.1"):
- udp_port = WIRESHARK_PORT
+ vocoder = self.options.vocoder
+ wireshark = self.options.wireshark
+ wireshark_host = self.options.wireshark_host
+ if self.options.udp_player:
+ vocoder = True
+ wireshark = True
+ wireshark_host = "127.0.0.1"
+
+ if wireshark or (wireshark_host != "127.0.0.1"):
+ udp_port = self.options.wireshark_port
self.tdma_state = False
self.xor_cache = {}
- self.fft_state = False
- self.c4fm_state = False
- self.fscope_state = False
- self.corr_state = False
- self.fac_state = False
- self.fsk4_demod_connected = False
- self.psk_demod_connected = False
- self.fsk4_demod_mode = False
- self.corr_i_chan = False
-
if self.baseband_input:
- self.demod = p25_demodulator.p25_demod_fb(input_rate=capture_rate)
+ self.demod = p25_demodulator.p25_demod_fb(input_rate=capture_rate, excess_bw=self.options.excess_bw,if_rate=if_rate)
else: # complex input
# local osc
- self.lo_freq = self.options.offset + self.options.fine_tune
- if self.options.audio_if or self.options.ifile or self.options.input:
+ self.lo_freq = self.options.offset
+ if self.options.ifile or self.options.input:
self.lo_freq += self.options.calibration
self.demod = p25_demodulator.p25_demod_cb( input_rate = capture_rate,
demod_type = self.options.demod_type,
relative_freq = self.lo_freq,
offset = self.options.offset,
- if_rate = 48000,
+ if_rate = if_rate,
gain_mu = self.options.gain_mu,
costas_alpha = self.options.costas_alpha,
- symbol_rate = self.symbol_rate)
+ excess_bw = self.options.excess_bw,
+ symbol_rate = self.symbol_rate,
+ use_old_decim = True if self.options.audio_if else False)
num_ambe = 0
if self.options.phase2_tdma:
num_ambe = 1
- self.decoder = p25_decoder.p25_decoder_sink_b(dest='audio', do_imbe=True, num_ambe=num_ambe, wireshark_host=self.options.wireshark_host, udp_port=udp_port, do_msgq = True, msgq=self.rx_q, audio_output=self.options.audio_output, debug=self.options.verbosity)
+ self.decoder = p25_decoder.p25_decoder_sink_b(dest='audio', do_imbe=vocoder, num_ambe=num_ambe, wireshark_host=wireshark_host, udp_port=udp_port, do_msgq = True, msgq=self.rx_q, audio_output=self.options.audio_output, debug=self.options.verbosity)
# connect it all up
self.connect(source, self.demod, self.decoder)
- if self.options.plot_mode == 'constellation':
- assert self.options.demod_type == 'cqpsk' ## constellation requires cqpsk demod-type
- self.constellation_sink = constellation_sink_c()
- self.demod.connect_complex('diffdec', self.constellation_sink)
- self.kill_sink = self.constellation_sink
- elif self.options.plot_mode == 'symbol':
- self.symbol_sink = symbol_sink_f()
- self.demod.connect_float(self.symbol_sink)
- self.kill_sink = self.symbol_sink
- elif self.options.plot_mode == 'fft':
- self.fft_sink = fft_sink_c()
- self.spectrum_decim = filter.rational_resampler_ccf(1, self.options.decim_amt)
- self.connect(self.spectrum_decim, self.fft_sink)
- self.demod.connect_complex('src', self.spectrum_decim)
- self.kill_sink = self.fft_sink
- elif self.options.plot_mode == 'datascope':
- assert self.options.demod_type == 'fsk4' ## datascope requires fsk4 demod-type
- self.eye_sink = eye_sink_f(sps=10)
- self.demod.connect_bb('symbol_filter', self.eye_sink)
- self.kill_sink = self.eye_sink
+ if self.baseband_input:
+ sps = if_rate // 4800
+ plot_modes = []
+ if self.options.plot_mode is not None:
+ plot_modes = self.options.plot_mode.split(',')
+ for plot_mode in plot_modes:
+ if plot_mode == 'constellation':
+ assert self.options.demod_type == 'cqpsk' ## constellation requires cqpsk demod-type
+ sink = constellation_sink_c()
+ self.plot_sinks.append(sink)
+ self.demod.connect_complex('diffdec', sink)
+ elif plot_mode == 'symbol':
+ sink = symbol_sink_f()
+ self.plot_sinks.append(sink)
+ self.demod.connect_float(sink)
+ elif plot_mode == 'fft':
+ sink = fft_sink_c()
+ self.plot_sinks.append(sink)
+ self.spectrum_decim = filter.rational_resampler_ccf(1, self.options.decim_amt)
+ self.connect(self.spectrum_decim, sink)
+ self.demod.connect_complex('src', self.spectrum_decim)
+ elif plot_mode == 'mixer':
+ sink = mixer_sink_c()
+ self.plot_sinks.append(sink)
+ self.demod.connect_complex('mixer', sink)
+ elif plot_mode == 'datascope':
+ assert self.options.demod_type == 'fsk4' ## datascope requires fsk4 demod-type
+ sink = eye_sink_f(sps=sps)
+ self.plot_sinks.append(sink)
+ self.demod.connect_bb('symbol_filter', sink)
+ elif plot_mode == 'correlation':
+ assert self.options.demod_type == 'fsk4' ## correlation plot requires fsk4 demod type
+ self.plot_sinks += setup_correlation(sps, "", self.demod.connect_bb)
+ elif plot_mode == 'sync':
+ assert self.options.demod_type == 'cqpsk' ## sync plot requires cqpsk demod-type
+ sink = sync_plot(block = self.demod.clock)
+ self.plot_sinks.append(sink)
+ # no flowgraph connection in this plot
+ else:
+ raise ValueError('unsupported plot type: %s' % plot_mode)
+ if self.is_http_term():
+ for sink in self.plot_sinks:
+ sink.gnuplot.set_interval(_def_interval)
+ sink.gnuplot.set_output_dir(_def_file_dir)
if self.options.raw_symbols:
self.sink_sf = blocks.file_sink(gr.sizeof_char, self.options.raw_symbols)
@@ -316,17 +353,26 @@ class p25_rx_block (gr.top_block):
if self.options.phase2_tdma:
num_ambe = 2
if self.options.logfile_workers:
- for i in xrange(self.options.logfile_workers):
+ for i in range(self.options.logfile_workers):
demod = p25_demodulator.p25_demod_cb(input_rate=capture_rate,
demod_type=self.options.demod_type,
offset=self.options.offset)
- decoder = p25_decoder.p25_decoder_sink_b(debug = self.options.verbosity, do_imbe = self.options.vocoder, num_ambe=num_ambe)
+ decoder = p25_decoder.p25_decoder_sink_b(debug = self.options.verbosity, do_imbe = vocoder, num_ambe=num_ambe)
logfile_workers.append({'demod': demod, 'decoder': decoder, 'active': False})
self.connect(source, demod, decoder)
- self.trunk_rx = trunking.rx_ctl(frequency_set = self.change_freq, debug = self.options.verbosity, conf_file = self.options.trunk_conf_file, logfile_workers=logfile_workers)
+ self.trunk_rx = trunking.rx_ctl(frequency_set = self.change_freq, debug = self.options.verbosity, conf_file = self.options.trunk_conf_file, logfile_workers=logfile_workers, send_event=self.send_event)
- self.du_watcher = du_queue_watcher(self.rx_q, self.trunk_rx.process_qmsg)
+ self.du_watcher = du_queue_watcher(self.rx_q, self.preprocess_qmsg)
+
+ def preprocess_qmsg(self, msg):
+ self.trunk_rx.process_qmsg(msg)
+ if self.options.freq_error_tracking:
+ if self.last_error_update + _def_error_update_time > time.time() \
+ or self.last_change_freq_at + _def_error_update_time > time.time():
+ pass
+ else:
+ self.error_tracking()
# Connect up the flow graph
#
@@ -360,55 +406,135 @@ class p25_rx_block (gr.top_block):
def configure_tdma(self, params):
if params['tdma'] is not None and not self.options.phase2_tdma:
- print '***TDMA request for frequency %d failed- phase2_tdma option not enabled' % params['freq']
+ sys.stderr.write("***TDMA request for frequency %d failed- phase2_tdma option not enabled\n" % params['freq'])
return
set_tdma = False
if params['tdma'] is not None:
set_tdma = True
+ self.decoder.set_slotid(params['tdma'])
+ self.demod.clock.set_tdma(set_tdma)
if set_tdma == self.tdma_state:
return # already in desired state
self.tdma_state = set_tdma
if set_tdma:
- self.decoder.set_slotid(params['tdma'])
hash = '%x%x%x' % (params['nac'], params['sysid'], params['wacn'])
if hash not in self.xor_cache:
self.xor_cache[hash] = lfsr.p25p2_lfsr(params['nac'], params['sysid'], params['wacn']).xor_chars
self.decoder.set_xormask(self.xor_cache[hash], hash)
- sps = self.basic_rate / 6000
+ self.decoder.set_nac(params['nac'])
+ rate = 6000
else:
- sps = self.basic_rate / 4800
+ rate = 4800
+ sps = self.basic_rate / rate
+ self.demod.set_symbol_rate(rate) # this and the foll. call should be merged?
self.demod.clock.set_omega(float(sps))
+ def error_tracking(self):
+ if self.last_error_update + _def_error_update_time > time.time() \
+ or self.last_change_freq_at + _def_error_update_time > time.time():
+ return
+ self.last_error_update = time.time()
+ band = self.demod.get_error_band()
+ freq_error = self.demod.get_freq_error()
+ if band:
+ self.error_band += band
+ self.freq_correction += freq_error * 0.15
+ self.freq_correction = int(self.freq_correction)
+ if self.freq_correction > 600:
+ self.freq_correction -= 1200
+ self.error_band += 1
+ elif self.freq_correction < -600:
+ self.freq_correction += 1200
+ self.error_band -= 1
+ self.tuning_error = int(self.error_band * 1200 + self.freq_correction)
+ e = 0
+ if self.last_change_freq > 0:
+ e = (self.tuning_error*1e6) / float(self.last_change_freq)
+ if self.options.verbosity >= 10:
+ sys.stderr.write('frequency_tracking\t%d\t%d\t%d\t%d\t%f\n' % (freq_error, self.error_band, self.tuning_error, self.freq_correction, e))
+
+ self.adjust_lo_freq() # adjust lo based on updated tuning error
+
+ d = {'time': time.time(), 'json_type': 'freq_error_tracking', 'name': 'rx.py', 'device': self.options.args, 'freq_error': freq_error, 'band': band, 'error_band': self.error_band, 'tuning_error': self.tuning_error, 'freq_correction': self.freq_correction}
+ js = json.dumps(d)
+ if self.options.verbosity > 0:
+ sys.stderr.write('%f error tracking: %s\n' % (time.time(), js))
+ if self.input_q.full_p():
+ if self.options.verbosity > 0:
+ sys.stderr.write('%f error_tracking: qfull\n' % (time.time()))
+ return
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def adjust_lo_freq(self):
+ # apply tuning error updates to adjust lo frequency
+ center_freq = self.last_center_freq
+ offset = self.options.offset
+ if not center_freq:
+ new_lo_freq = offset + self.tuning_error
+ else:
+ new_lo_freq = self.last_relative_freq + offset + self.tuning_error
+ if abs(self.lo_freq - new_lo_freq) > _def_lo_adj_limit:
+ sys.stderr.write('adjust_lo_freq: adjustment exceeds limit: previous %d requested %d\n' % (self.lo_freq, new_lo_freq))
+ return
+ self.lo_freq = new_lo_freq
+ self.demod.set_relative_frequency(self.lo_freq)
+
def change_freq(self, params):
+ if self.options.verbosity > 1:
+ sys.stderr.write('%f change_freq: %s\n' % (time.time(), params))
+ self.last_freq_params = params
freq = params['freq']
- offset = params['offset']
+ offset = self.options.offset
center_freq = params['center_frequency']
- fine_tune = self.options.fine_tune
+ self.last_center_freq = center_freq
+ if self.options.freq_error_tracking:
+ self.error_tracking()
+ if self.last_change_freq != freq:
+ self.last_change_freq = freq
+ self.last_change_freq_at = time.time()
+
+ self.configure_tdma(params)
if self.options.hamlib_model:
self.hamlib.set_freq(freq)
- elif params['center_frequency']:
- relative_freq = center_freq - freq
- if abs(relative_freq + self.options.offset) > self.channel_rate / 2:
- self.lo_freq = self.options.offset + self.options.fine_tune # relative tune not possible
- self.demod.set_relative_frequency(self.lo_freq) # reset demod relative freq
- self.set_freq(freq + offset) # direct tune instead
- else:
- self.lo_freq = self.options.offset + relative_freq + fine_tune
- if self.demod.set_relative_frequency(self.lo_freq): # relative tune successful
- self.set_freq(center_freq + offset)
- if self.fft_sink:
- self.fft_sink.set_relative_freq(self.lo_freq)
- else:
- self.lo_freq = self.options.offset + self.options.fine_tune # relative tune unsuccessful
- self.demod.set_relative_frequency(self.lo_freq) # reset demod relative freq
- self.set_freq(freq + offset) # direct tune instead
- else:
- self.set_freq(freq + offset)
+ return
+
+ if not center_freq:
+ self.lo_freq = offset + self.tuning_error
+ self.demod.set_relative_frequency(self.lo_freq)
+ self.set_freq(freq)
+ return
+ relative_freq = center_freq - freq
+ self.last_relative_freq = relative_freq
+
+ if abs(relative_freq + offset + self.tuning_error) > self.channel_rate / 2:
+ self.lo_freq = offset + self.tuning_error # relative tune not possible
+ self.demod.set_relative_frequency(self.lo_freq) # reset demod relative freq
+ self.set_freq(freq) # direct tune instead
+ return
+
+ self.lo_freq = relative_freq + offset + self.tuning_error
+ if self.demod.set_relative_frequency(self.lo_freq): # relative tune successful
+ self.set_freq(center_freq)
+ if self.fft_sink:
+ self.fft_sink.set_relative_freq(self.lo_freq)
+ return
+
+ self.lo_freq = offset + self.tuning_error # relative tune unsuccessful
+ self.demod.set_relative_frequency(self.lo_freq) # reset demod relative freq
+ self.set_freq(freq + offset) # direct tune instead
self.configure_tdma(params)
+ self.freq_update()
+ def freq_update(self):
+ if self.input_q.full_p():
+ return
+ params = self.last_freq_params
params['json_type'] = 'change_freq'
+ params['fine_tune'] = self.options.fine_tune
+ params['current_time'] = time.time()
js = json.dumps(params)
msg = gr.message().make_from_string(js, -4, 0, 0)
self.input_q.insert_tail(msg)
@@ -430,7 +556,7 @@ class p25_rx_block (gr.top_block):
if self.rtl_found:
self.src.set_gain(gain, 'LNA')
if self.options.verbosity:
- print 'RTL Gain of %d set to: %.1f' % (gain, self.src.get_gain('LNA'))
+ print ('RTL Gain of %d set to: %.1f' % (gain, self.src.get_gain('LNA')))
else:
if self.baseband_input:
f = 1.0
@@ -439,8 +565,9 @@ class p25_rx_block (gr.top_block):
self.demod.set_baseband_gain(float(gain) * f)
def set_audio_scaler(self, vol):
- #print 'audio scaler: %f' % ((1 / 32768.0) * (vol * 0.1))
- self.decoder.set_scaler_k((1 / 32768.0) * (vol * 0.1))
+ #print ('audio scaler: %f' % ((1 / 32768.0) * (vol * 0.1)))
+ if hasattr(self.decoder, 'set_scaler_k'):
+ self.decoder.set_scaler_k((1 / 32768.0) * (vol * 0.1))
def set_rtl_ppm(self, ppm):
self.src.set_freq_corr(ppm)
@@ -462,11 +589,12 @@ class p25_rx_block (gr.top_block):
"""
if not self.src:
return False
- tune_freq = target_freq + self.options.calibration + self.options.offset
+ self.target_freq = target_freq
+ tune_freq = target_freq + self.options.calibration + self.options.offset + self.options.fine_tune
r = self.src.set_center_freq(tune_freq)
if self.fft_sink:
- self.fft_sink.set_center_freq(tune_freq)
+ self.fft_sink.set_center_freq(target_freq)
self.fft_sink.set_width(self.options.sample_rate)
if r:
@@ -474,6 +602,9 @@ class p25_rx_block (gr.top_block):
#if self.show_debug_info:
# self.myform['baseband'].set_value(r.baseband_freq)
# self.myform['ddc'].set_value(r.dxc_freq)
+ if self.last_set_freq != tune_freq:
+ self.last_set_freq = tune_freq
+ self.last_set_freq_at = time.time()
return True
return False
@@ -509,10 +640,9 @@ class p25_rx_block (gr.top_block):
self.src.set_antenna(self.options.antenna)
self.info["capture-rate"] = capture_rate
self.src.set_bandwidth(capture_rate)
- r = self.src.set_center_freq(self.options.frequency + self.options.calibration+ self.options.offset)
- print 'set_center_freq: %d' % r
+ r = self.src.set_center_freq(self.options.frequency + self.options.calibration+ self.options.offset + self.options.fine_tune)
if not r:
- raise RuntimeError("failed to set USRP frequency")
+ sys.stderr.write("__set_rx_from_osmosdr(): failed to set frequency\n")
# capture file
# if preserve:
if 0:
@@ -534,22 +664,13 @@ class p25_rx_block (gr.top_block):
pickle.dump(self.info, f)
f.close()
- # Adjust the channel offset
- #
- def adjust_channel_offset(self, delta_hz):
- max_delta_hz = 12000.0
- delta_hz *= self.symbol_deviation
- delta_hz = max(delta_hz, -max_delta_hz)
- delta_hz = min(delta_hz, max_delta_hz)
- self.channel_filter.set_center_freq(self.channel_offset - delta_hz+ self.options.offset)
-
def open_ifile(self, capture_rate, gain, input_filename, file_seek):
speed = 96000 # TODO: fixme
ifile = blocks.file_source(gr.sizeof_gr_complex, input_filename, 1)
if file_seek > 0:
rc = ifile.seek(file_seek*1024, gr.SEEK_SET)
assert rc == True
- #print "seek: %d, rc = %d" % (file_seek, rc)
+ #print ("seek: %d, rc = %d" % (file_seek, rc))
throttle = blocks.throttle(gr.sizeof_gr_complex, speed)
self.source = blocks.multiply_const_cc(gain)
self.connect(ifile, throttle, self.source)
@@ -562,13 +683,17 @@ class p25_rx_block (gr.top_block):
"source-dev": "AUDIO",
"source-decim": 1 }
self.audio_source = audio.source(capture_rate, audio_input_filename)
+ self.null_source = blocks.null_source (gr.sizeof_float)
self.audio_cvt = blocks.float_to_complex()
- self.connect((self.audio_source, 0), (self.audio_cvt, 0))
- self.connect((self.audio_source, 1), (self.audio_cvt, 1))
+ self.connect(self.audio_source, (self.audio_cvt, 0))
+ self.connect(self.null_source, (self.audio_cvt, 1))
self.source = blocks.multiply_const_cc(gain)
self.connect(self.audio_cvt, self.source)
self.__set_rx_from_audio(capture_rate)
+ rc = self.demod.set_relative_frequency(self.options.calibration)
+ sys.stderr.write('open_audio_c: set_relative_frequency %d: %s\n' % (self.options.calibration, rc))
+
def open_audio(self, capture_rate, gain, audio_input_filename):
self.info = {
"capture-rate": capture_rate,
@@ -590,41 +715,94 @@ class p25_rx_block (gr.top_block):
"source-dev": "USRP",
"source-decim": 1 }
self.__set_rx_from_osmosdr()
+ if self.options.frequency:
+ self.last_freq_params['freq'] = self.options.frequency
+ self.set_freq(self.options.frequency)
# except Exception, x:
# wx.MessageBox("Cannot open USRP: " + x.message, "USRP Error", wx.CANCEL | wx.ICON_EXCLAMATION)
- # Set the channel offset
- #
- def set_channel_offset(self, offset_hz, scale, units):
- self.channel_offset = -offset_hz
- self.channel_filter.set_center_freq(self.channel_offset+ self.options.offset)
- self.frame.SetStatusText("Channel offset: " + str(offset_hz * scale) + units, 1)
+ def is_http_term(self):
+ if self.options.terminal_type.startswith('http:'):
+ return True
+ elif self.options.terminal_type.startswith('zmq:'):
+ return True
+ else:
+ return False
- # Set the RF squelch threshold level
- #
- def set_squelch_threshold(self, squelch_db):
- self.squelch.set_threshold(squelch_db)
- self.frame.SetStatusText("Squelch: " + str(squelch_db) + "dB", 2)
+ def process_ajax(self):
+ if not self.is_http_term():
+ return
+ if self.input_q.full_p():
+ return
+ filenames = [sink.gnuplot.filename for sink in self.plot_sinks if sink.gnuplot.filename]
+ error = None
+ if self.options.demod_type == 'cqpsk':
+ error = self.demod.get_freq_error()
+ d = {'json_type': 'rx_update', 'error': error, 'fine_tune': self.options.fine_tune, 'files': filenames, 'time': time.time()}
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+
+ def process_update(self):
+ UPDATE_INTERVAL = 1.0 # sec.
+ now = time.time()
+ if self.options.freq_error_tracking:
+ self.error_tracking()
+ if self.input_q.full_p():
+ return
+ if now < self.last_process_update + UPDATE_INTERVAL:
+ return
+ self.last_process_update = now
+ self.freq_update()
+ if self.trunk_rx is None:
+ return ## possible race cond - just ignore
+ if self.input_q.full_p():
+ return
+ js = self.trunk_rx.to_json()
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ self.input_q.insert_tail(msg)
+ self.process_ajax()
+
+ def send_event(self, d): ## called from trunking module to send json msgs / updates to client
+ if d is not None:
+ self.sql_db.event(d)
+ if d and not self.input_q.full_p():
+ msg = gr.message().make_from_string(json.dumps(d), -4, 0, 0)
+ self.input_q.insert_tail(msg)
+ self.process_update()
def process_qmsg(self, msg):
# return true = end top block
- RX_COMMANDS = 'skip lockout hold'
+ RX_COMMANDS = 'skip lockout hold'.split()
s = msg.to_string()
+ t = msg.type()
+ if t == -4:
+ d = json.loads(s)
+ s = d['command']
+ if type(s) is not str and isinstance(s, bytes):
+ # should only get here if python3
+ s = s.decode()
if s == 'quit': return True
- elif s == 'update':
- if self.trunk_rx is None:
- return False ## possible race cond - just ignore
- js = self.trunk_rx.to_json()
- msg = gr.message().make_from_string(js, -4, 0, 0)
- self.input_q.insert_tail(msg)
+ elif s == 'update': ## deprecated here: to be removed
+ pass
+ # self.process_update()
elif s == 'set_freq':
freq = msg.arg1()
+ self.last_freq_params['freq'] = freq
self.set_freq(freq)
+ elif s == 'adj_tune':
+ freq = msg.arg1()
+ elif s == 'dump_tgids':
+ self.trunk_rx.dump_tgids()
+ elif s == 'reload_tags':
+ nac = msg.arg1()
+ self.trunk_rx.reload_tags(int(nac))
elif s == 'add_default_config':
nac = msg.arg1()
- self.trunk_rx.add_default_config(nac)
+ self.trunk_rx.add_default_config(int(nac))
elif s in RX_COMMANDS:
self.rx_q.insert_tail(msg)
+ elif s == 'settings-enable' and self.trunk_rx is not None:
+ self.trunk_rx.enable_status(d['data'])
return False
############################################################################
@@ -644,26 +822,90 @@ class du_queue_watcher(threading.Thread):
def run(self):
while(self.keep_running):
msg = self.msgq.delete_head()
+ if not self.keep_running:
+ break
self.callback(msg)
+class rx_main(object):
+ def __init__(self):
+ self.keep_running = True
+ self.cli_options()
+ self.tb = p25_rx_block(self.options)
+ self.q_watcher = du_queue_watcher(self.tb.output_q, self.process_qmsg)
+ sys.stderr.write('python version detected: %s\n' % sys.version)
+
+ def process_qmsg(self, msg):
+ if self.tb.process_qmsg(msg):
+ self.keep_running = False
+
+ def run(self):
+ try:
+ self.tb.start()
+ while self.keep_running:
+ time.sleep(1)
+ except:
+ sys.stderr.write('main: exception occurred\n')
+ sys.stderr.write('main: exception:\n%s\n' % traceback.format_exc())
+ if self.tb.terminal:
+ self.tb.terminal.end_terminal()
+ if self.tb.audio:
+ self.tb.audio.stop()
+ self.tb.stop()
+ for sink in self.tb.plot_sinks:
+ sink.kill()
+
+ def cli_options(self):
+ # command line argument parsing
+ parser = OptionParser(option_class=eng_option)
+ parser.add_option("--args", type="string", default="", help="device args")
+ parser.add_option("--antenna", type="string", default="", help="select antenna")
+ parser.add_option("-a", "--audio", action="store_true", default=False, help="use direct audio input")
+ parser.add_option("-A", "--audio-if", action="store_true", default=False, help="soundcard IF mode (use --calibration to set IF freq)")
+ parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp")
+ parser.add_option("-i", "--input", type="string", default=None, help="input file name")
+ parser.add_option("-b", "--excess-bw", type="eng_float", default=0.2, help="for RRC filter", metavar="Hz")
+ parser.add_option("-c", "--calibration", type="eng_float", default=0.0, help="USRP offset or audio IF frequency", metavar="Hz")
+ parser.add_option("-C", "--costas-alpha", type="eng_float", default=0.04, help="value of alpha for Costas loop", metavar="Hz")
+ parser.add_option("-D", "--demod-type", type="choice", default="cqpsk", choices=('cqpsk', 'fsk4'), help="cqpsk | fsk4")
+ parser.add_option("-P", "--plot-mode", type="string", default=None, help="one or more of constellation, fft, symbol, datascope (comma-separated)")
+ parser.add_option("-f", "--frequency", type="eng_float", default=0.0, help="USRP center frequency", metavar="Hz")
+ parser.add_option("-F", "--ifile", type="string", default=None, help="read input from complex capture file")
+ parser.add_option("-H", "--hamlib-model", type="int", default=None, help="specify model for hamlib")
+ parser.add_option("-s", "--seek", type="int", default=0, help="ifile seek in K")
+ parser.add_option("-l", "--terminal-type", type="string", default='curses', help="'curses' or udp port or 'http:host:port'")
+ parser.add_option("-L", "--logfile-workers", type="int", default=None, help="number of demodulators to instantiate")
+ parser.add_option("-S", "--sample-rate", type="int", default=320e3, help="source samp rate")
+ parser.add_option("-t", "--tone-detect", action="store_true", default=False, help="use experimental tone detect algorithm")
+ parser.add_option("-T", "--trunk-conf-file", type="string", default=None, help="trunking config file name")
+ parser.add_option("-v", "--verbosity", type="int", default=0, help="message debug level")
+ parser.add_option("-V", "--vocoder", action="store_true", default=False, help="voice codec")
+ parser.add_option("-n", "--nocrypt", action="store_true", default=False, help="silence encrypted traffic")
+ parser.add_option("-o", "--offset", type="eng_float", default=0.0, help="tuning offset frequency [to circumvent DC offset]", metavar="Hz")
+ parser.add_option("-p", "--pause", action="store_true", default=False, help="block on startup")
+ parser.add_option("-w", "--wireshark", action="store_true", default=False, help="output data to Wireshark")
+ parser.add_option("-W", "--wireshark-host", type="string", default="127.0.0.1", help="Wireshark host")
+ parser.add_option("-u", "--wireshark-port", type="int", default=23456, help="Wireshark udp port")
+ parser.add_option("-r", "--raw-symbols", type="string", default=None, help="dump decoded symbols to file")
+ parser.add_option("-g", "--gain", type="eng_float", default=None, help="set USRP gain in dB (default is midpoint) or set audio gain")
+ parser.add_option("-G", "--gain-mu", type="eng_float", default=0.025, help="gardner gain")
+ parser.add_option("-N", "--gains", type="string", default=None, help="gain settings")
+ parser.add_option("-O", "--audio-output", type="string", default="default", help="audio output device name")
+ parser.add_option("-x", "--audio-gain", type="eng_float", default="1.0", help="audio gain (default = 1.0)")
+ parser.add_option("-X", "--freq-error-tracking", action="store_true", default=False, help="enable experimental frequency error tracking")
+ parser.add_option("-U", "--udp-player", action="store_true", default=False, help="enable built-in udp audio player")
+ parser.add_option("-q", "--freq-corr", type="eng_float", default=0.0, help="frequency correction")
+ parser.add_option("-d", "--fine-tune", type="eng_float", default=0.0, help="fine tuning")
+ parser.add_option("-2", "--phase2-tdma", action="store_true", default=False, help="enable phase2 tdma decode")
+ parser.add_option("-Z", "--decim-amt", type="int", default=1, help="spectrum decimation")
+ (options, args) = parser.parse_args()
+ if len(args) != 0:
+ parser.print_help()
+ sys.exit(1)
+ self.options = options
+
# Start the receiver
#
if __name__ == "__main__":
- tb = p25_rx_block()
- tb.start()
- try:
- while True:
- msg = tb.output_q.delete_head()
- if tb.process_qmsg(msg):
- break
- except:
- sys.stderr.write('main: exception occurred\n')
- sys.stderr.write('main: exception:\n%s\n' % traceback.format_exc())
- if tb.terminal:
- tb.terminal.end_curses()
- if tb.audio:
- tb.audio.stop()
- tb.stop()
- if tb.kill_sink:
- tb.kill_sink.kill()
+ rx = rx_main()
+ rx.run()
diff --git a/op25/gr-op25_repeater/apps/site-alias.json b/op25/gr-op25_repeater/apps/site-alias.json
new file mode 100644
index 0000000..63cfb94
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/site-alias.json
@@ -0,0 +1,12 @@
+{
+ "552": {
+ "1": {
+ "1": {
+ "alias": "new1"
+ },
+ "2": {
+ "alias": "new2"
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/sockaudio.py b/op25/gr-op25_repeater/apps/sockaudio.py
index d0f7432..68c6adb 100755
--- a/op25/gr-op25_repeater/apps/sockaudio.py
+++ b/op25/gr-op25_repeater/apps/sockaudio.py
@@ -1,6 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
-# Copyright 2017 Graham Norbury
+# Copyright 2017, 2018 Graham Norbury
+#
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
#
# This file is part of OP25
#
@@ -20,20 +22,26 @@
# 02110-1301, USA.
from ctypes import *
+import os
import sys
import time
import threading
+import select
import socket
import errno
+import struct
+import ctypes
+import numpy as np
+from log_ts import log_ts
# OP25 defaults
-PCM_RATE = 8000 # audio sample rate (Hz)
-PCM_BUFFER_SIZE = 2000 # size of ALSA buffer in frames
+PCM_RATE = 8000 # audio sample rate (Hz)
+PCM_BUFFER_SIZE = 4000 # size of ALSA buffer in frames
-MAX_SUPERFRAME_SIZE = 320 # maximum size of incoming UDP audio buffer
+MAX_SUPERFRAME_SIZE = 320 # maximum size of incoming UDP audio buffer
# Debug
-LOG_AUDIO_XRUNS = True # log audio underruns to stderr
+LOG_AUDIO_XRUNS = True # log audio underruns to stderr
# Alsa PCM constants
SND_PCM_FORMAT_S8 = c_int(0)
@@ -99,211 +107,450 @@ SND_PCM_ACCESS_RW_INTERLEAVED = c_int(3)
SND_PCM_ACCESS_RW_NONINTERLEAVED = c_int(4)
SND_PCM_ACCESS_LAST = SND_PCM_ACCESS_RW_NONINTERLEAVED
+PA_STREAM_PLAYBACK = 1
+PA_SAMPLE_S16LE = 3
+
# Python CTypes wrapper to Alsa libasound2
class alsasound(object):
- def __init__(self):
- self.libasound = cdll.LoadLibrary("libasound.so.2")
- self.c_pcm = c_void_p()
- self.format = 0
- self.channels = 0
- self.rate = 0
- self.framesize = 0
-
- def open(self, hwdev):
- b_hwdev = create_string_buffer(str.encode(hwdev))
- c_stream = SND_PCM_STREAM_PLAYBACK
- err = self.libasound.snd_pcm_open(byref(self.c_pcm), b_hwdev, c_stream, SND_PCM_NORMAL)
- return err
-
- def close(self):
- if (self.c_pcm.value == None):
- return
- self.libasound.snd_pcm_close(self.c_pcm)
- self.c_pcm.value = None
-
- def setup(self, pcm_format, pcm_channels, pcm_rate, pcm_buffer_size):
- if (self.c_pcm.value == None):
- return
-
- self.format = pcm_format
- self.channels = pcm_channels
- self.rate = pcm_rate
- pcm_start_threshold = int(pcm_buffer_size * 0.75)
-
- c_pars = (c_void_p * int(self.libasound.snd_pcm_hw_params_sizeof() / sizeof(c_void_p)))()
- err = self.libasound.snd_pcm_hw_params_any(self.c_pcm, c_pars)
- if err < 0:
- sys.stderr.write("hw_params_any failed: %d\n" % err)
- return err
-
- err = self.libasound.snd_pcm_hw_params_set_access(self.c_pcm, c_pars, SND_PCM_ACCESS_RW_INTERLEAVED);
- if err < 0:
- sys.stderr.write("set_access failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_hw_params_set_format(self.c_pcm, c_pars, c_uint(self.format));
- if err < 0:
- sys.stderr.write("set_format failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_hw_params_set_channels(self.c_pcm, c_pars, c_uint(self.channels));
- if err < 0:
- sys.stderr.write("set_channels failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_hw_params_set_rate(self.c_pcm, c_pars, c_uint(self.rate), c_int(0));
- if err < 0:
- sys.stderr.write("set_rate failed: %d\n" % err)
- return err
- err = 0 ########self.libasound.snd_pcm_hw_params_set_buffer_size(self.c_pcm, c_pars, c_ulong(pcm_buffer_size), c_int(0));
- if err < 0:
- sys.stderr.write("set_buffer_size failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_hw_params(self.c_pcm, c_pars);
- if err < 0:
- sys.stderr.write("hw_params failed: %d\n" % err)
- return err
-
- self.libasound.snd_pcm_hw_params_current(self.c_pcm, c_pars)
- c_bits = self.libasound.snd_pcm_hw_params_get_sbits(c_pars)
- self.framesize = self.channels * c_bits/8;
-
- c_sw_pars = (c_void_p * int(self.libasound.snd_pcm_sw_params_sizeof() / sizeof(c_void_p)))()
- err = self.libasound.snd_pcm_sw_params_current(self.c_pcm, c_sw_pars)
- if err < 0:
- sys.stderr.write("get_sw_params_current failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_sw_params_set_start_threshold(self.c_pcm, c_sw_pars, c_uint(pcm_start_threshold))
- if err < 0:
- sys.stderr.write("set_sw_params_start_threshold failed: %d\n" % err)
- return err
- err = self.libasound.snd_pcm_sw_params(self.c_pcm, c_sw_pars)
- if err < 0:
- sys.stderr.write("sw_params failed: %d\n" % err)
- return err
-
- ret = self.libasound.snd_pcm_prepare(self.c_pcm)
- #self.dump()
- return ret
-
- def write(self, pcm_data):
- datalen = len(pcm_data)
- n_frames = c_ulong(datalen / self.framesize)
- c_data = c_char_p(pcm_data)
- ret = 0
-
- if (self.c_pcm.value == None):
- sys.stderr.write("PCM device is closed\n")
- return -1
-
- ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
- if (ret < 0):
- if (ret == -errno.EPIPE): # underrun
- if (LOG_AUDIO_XRUNS):
- sys.stderr.write("[%f] PCM underrun\n" % time.time())
- ret = self.libasound.snd_pcm_recover(self.c_pcm, ret, 1)
- if (ret >= 0):
- ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
- else:
- ret = self.libasound.snd_pcm_prepare(self.c_pcm)
- ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
- elif (ret == -errno.ESTRPIPE): # suspended
- while True:
- ret = self.libasound.snd_pcm_resume(self.c_pcm)
- if (ret != -errno.EAGAIN):
- break
- time.sleep(1)
- if (ret < 0):
- ret = self.libasound.snd_pcm_prepare(self.c_pcm)
- elif (ret < 0): # other error
- ret = self.libasound.snd_pcm_prepare(self.c_pcm)
-
- return ret
-
- def drain(self):
- ret = self.libasound.snd_pcm_drain(self.c_pcm)
- if (ret == -errno.ESTRPIPE): # suspended
- while True:
- ret = self.libasound.snd_pcm_resume(self.c_pcm)
- if (ret != -errno.EAGAIN):
- break
- time.sleep(1)
- ret = self.libasound.snd_pcm_prepare(self.c_pcm)
-
- def dump(self):
- if (self.c_pcm.value == None):
- return
-
- c_buf_p = c_void_p()
- c_str_p = c_char_p()
- c_strlen = c_uint(0)
- self.libasound.snd_output_buffer_open(byref(c_buf_p))
- self.libasound.snd_pcm_dump_setup(self.c_pcm, c_buf_p)
- c_strlen = self.libasound.snd_output_buffer_string(c_buf_p, byref(c_str_p))
- sys.stderr.write("%s\n" % c_str_p.value[0:c_strlen-1])
- self.libasound.snd_output_close(c_buf_p)
-
-# OP25 thread to receive UDP audio samples and send to Alsa driver
-class socket_audio(threading.Thread):
- def __init__(self, udp_host, udp_port, pcm_device, **kwds):
- threading.Thread.__init__(self, **kwds)
- self.setDaemon(1)
- self.keep_running = True
- self.sock = None
- self.pcm = alsasound()
- self.setup_socket(udp_host, udp_port)
- self.setup_pcm(pcm_device)
- self.start()
- return
-
- def run(self):
- while self.keep_running:
- # Data received on the udp port is 320 bytes for an audio frame or 2 bytes for a flag
- #
- d = self.sock.recvfrom(MAX_SUPERFRAME_SIZE) # recvfrom blocks until data becomes available
- if d[0]:
- d_len = len(d[0])
- if (d_len == 2): # flag
- flag = ord(d[0][0]) + (ord(d[0][1]) << 8) # 16 bit little endian
- if (flag == 0): # 0x0000 = drain pcm buffer
- self.pcm.drain()
- else: # audio data
- self.pcm.write(d[0])
- else:
- break
-
- self.close_socket()
- self.close_pcm()
- return
-
- def stop(self):
- self.keep_running = False
- return
-
- def setup_socket(self, udp_host, udp_port):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- self.sock.bind((udp_host, udp_port))
- sys.stderr.write('setup_socket: %d\n' % udp_port)
- return
-
- def close_socket(self):
- self.sock.close()
- return
-
- def setup_pcm(self, hwdevice):
- sys.stderr.write('audio device: %s\n' % hwdevice)
- err = self.pcm.open(hwdevice)
- if err < 0:
- sys.stderr.write('failed to open audio device: %s\n' % hwdevice)
- self.pcm.dump()
- self.keep_running = False
- return
-
- err = self.pcm.setup(SND_PCM_FORMAT_S16_LE.value, 1, PCM_RATE, PCM_BUFFER_SIZE)
- if err < 0:
- sys.stderr.write('failed to set up pcm stream\n')
- self.keep_running = False
- return
- return
-
- def close_pcm(self):
- self.pcm.close()
- return
+ def __init__(self):
+ self.libasound = cdll.LoadLibrary("libasound.so.2")
+ self.c_pcm = c_void_p()
+ self.format = 0
+ self.channels = 0
+ self.rate = 0
+ self.framesize = 0
+
+ def open(self, hwdev):
+ b_hwdev = create_string_buffer(str.encode(hwdev))
+ c_stream = SND_PCM_STREAM_PLAYBACK
+ err = self.libasound.snd_pcm_open(byref(self.c_pcm), b_hwdev, c_stream, SND_PCM_NORMAL)
+ return err
+
+ def close(self):
+ if (self.c_pcm.value == None):
+ return
+ self.libasound.snd_pcm_close(self.c_pcm)
+ self.c_pcm.value = None
+
+ def setup(self, pcm_format, pcm_channels, pcm_rate, pcm_buffer_size):
+ if (self.c_pcm.value == None):
+ return
+
+ self.format = pcm_format
+ self.channels = pcm_channels
+ self.rate = pcm_rate
+ pcm_buf_sz = c_ulong(pcm_buffer_size)
+
+ c_pars = (c_void_p * int(self.libasound.snd_pcm_hw_params_sizeof() / sizeof(c_void_p)))()
+ err = self.libasound.snd_pcm_hw_params_any(self.c_pcm, c_pars)
+ if err < 0:
+ sys.stderr.write("hw_params_any failed: %d\n" % err)
+ return err
+
+ err = self.libasound.snd_pcm_hw_params_set_access(self.c_pcm, c_pars, SND_PCM_ACCESS_RW_INTERLEAVED)
+ if err < 0:
+ sys.stderr.write("set_access failed: %d\n" % err)
+ return err
+ err = self.libasound.snd_pcm_hw_params_set_format(self.c_pcm, c_pars, c_uint(self.format))
+ if err < 0:
+ sys.stderr.write("set_format failed: %d\n" % err)
+ return err
+ err = self.libasound.snd_pcm_hw_params_set_channels(self.c_pcm, c_pars, c_uint(self.channels))
+ if err < 0:
+ sys.stderr.write("set_channels failed: %d\n" % err)
+ return err
+ err = self.libasound.snd_pcm_hw_params_set_rate(self.c_pcm, c_pars, c_uint(self.rate), c_int(0))
+ if err < 0:
+ sys.stderr.write("set_rate failed: %d\n" % err)
+ return err
+ err = self.libasound.snd_pcm_hw_params_set_buffer_size_near(self.c_pcm, c_pars, byref(pcm_buf_sz))
+ if err < 0:
+ sys.stderr.write("set_buffer_size_near failed: %d\n" % err)
+ return err
+ if pcm_buf_sz.value != pcm_buffer_size:
+ sys.stderr.write("set_buffer_size_near requested %d, but returned %d\n" % (pcm_buffer_size, pcm_buf_sz.value))
+ err = self.libasound.snd_pcm_hw_params(self.c_pcm, c_pars)
+ if err < 0:
+ sys.stderr.write("hw_params failed: %d\n" % err)
+ return err
+
+ self.libasound.snd_pcm_hw_params_current(self.c_pcm, c_pars)
+ c_bits = self.libasound.snd_pcm_hw_params_get_sbits(c_pars)
+ self.framesize = self.channels * c_bits//8
+
+ c_sw_pars = (c_void_p * int(self.libasound.snd_pcm_sw_params_sizeof() / sizeof(c_void_p)))()
+ err = self.libasound.snd_pcm_sw_params_current(self.c_pcm, c_sw_pars)
+ if err < 0:
+ sys.stderr.write("get_sw_params_current failed: %d\n" % err)
+ return err
+ pcm_start_threshold = int(pcm_buf_sz.value * 0.75)
+ err = self.libasound.snd_pcm_sw_params_set_start_threshold(self.c_pcm, c_sw_pars, c_uint(pcm_start_threshold))
+ if err < 0:
+ sys.stderr.write("set_sw_params_start_threshold failed: %d\n" % err)
+ return err
+ err = self.libasound.snd_pcm_sw_params(self.c_pcm, c_sw_pars)
+ if err < 0:
+ sys.stderr.write("sw_params failed: %d\n" % err)
+ return err
+
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+ #self.dump()
+ return ret
+
+ def write(self, pcm_data):
+ datalen = len(pcm_data)
+ n_frames = c_ulong(datalen // self.framesize)
+ c_data = c_char_p(pcm_data)
+ ret = 0
+
+ if (self.c_pcm.value == None):
+ sys.stderr.write("PCM device is closed\n")
+ return -1
+
+ ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
+ if (ret < 0):
+ if (ret == -errno.EPIPE): # underrun
+ if (LOG_AUDIO_XRUNS):
+ sys.stderr.write("%s PCM underrun\n" % log_ts.get())
+ ret = self.libasound.snd_pcm_recover(self.c_pcm, ret, 1)
+ if (ret >= 0):
+ ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
+ else:
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+ ret = self.libasound.snd_pcm_writei(self.c_pcm, cast(c_data, POINTER(c_void_p)), n_frames)
+ elif (ret == -errno.ESTRPIPE): # suspended
+ while True:
+ ret = self.libasound.snd_pcm_resume(self.c_pcm)
+ if (ret != -errno.EAGAIN):
+ break
+ time.sleep(1)
+ if (ret < 0):
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+ elif (ret < 0): # other error
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+
+ return ret
+
+ def drain(self):
+ ret = self.libasound.snd_pcm_drain(self.c_pcm)
+ if (ret == -errno.ESTRPIPE): # suspended
+ while True:
+ ret = self.libasound.snd_pcm_resume(self.c_pcm)
+ if (ret != -errno.EAGAIN):
+ break
+ time.sleep(1)
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+ return ret
+
+ def drop(self):
+ ret = self.libasound.snd_pcm_drop(self.c_pcm)
+ if (ret == -errno.ESTRPIPE): # suspended
+ while True:
+ ret = self.libasound.snd_pcm_resume(self.c_pcm)
+ if (ret != -errno.EAGAIN):
+ break
+ time.sleep(1)
+ ret = self.libasound.snd_pcm_prepare(self.c_pcm)
+ return ret
+
+ def dump(self):
+ if (self.c_pcm.value == None):
+ return
+
+ c_buf_p = c_void_p()
+ c_str_p = c_char_p()
+ c_strlen = c_uint(0)
+ self.libasound.snd_output_buffer_open(byref(c_buf_p))
+ self.libasound.snd_pcm_dump_setup(self.c_pcm, c_buf_p)
+ c_strlen = self.libasound.snd_output_buffer_string(c_buf_p, byref(c_str_p))
+ sys.stderr.write("%s\n" % c_str_p.value[0:c_strlen-1])
+ self.libasound.snd_output_close(c_buf_p)
+
+ def check(self):
+ return 0
+
+class _struct_pa_sample_spec(Structure):
+ _fields_ = [("format", c_int),
+ ("rate", c_uint32),
+ ("channels", c_uint8)]
+
+class pa_sound(object):
+ def __init__(self):
+ self.error = c_int(0)
+ self.libpa = cdll.LoadLibrary("libpulse-simple.so.0")
+ self.libpa.strerror.restype = c_char_p
+ self.ss = _struct_pa_sample_spec(PA_SAMPLE_S16LE, 8000, 2)
+
+ def open(self, hwdevice):
+ self.out = c_void_p(self.libpa.pa_simple_new(None,
+ "OP25".encode("ascii"),
+ PA_STREAM_PLAYBACK,
+ None,
+ "OP25 Playback".encode('ascii'),
+ byref(self.ss),
+ None,
+ None,
+ byref(self.error)))
+
+ if not self.out:
+ sys.stderr.write("%s Could not open PulseAudio stream: %s\n" % (log_ts.get(), self.libpa.strerror(self.error)))
+
+ return self.error.value
+
+ def close(self):
+ self.libpa.pa_simple_free(self.out)
+
+ def setup(self, pcm_format, pcm_channels, pcm_rate, pcm_buffer_size):
+ self.ss.format = PA_SAMPLE_S16LE # fixed format
+ self.ss.channels = pcm_channels
+ self.ss.rate = pcm_rate
+ return 0
+
+ def write(self, pcm_data):
+ self.libpa.pa_simple_write(self.out, pcm_data, len(pcm_data), byref(self.error))
+ return self.error
+
+ def drain(self):
+ self.libpa.pa_simple_drain(self.out, byref(self.error))
+ return self.error.value
+
+ def drop(self):
+ self.libpa.pa_simple_flush(self.out, byref(self.error))
+ return self.error.value
+
+ def dump(self):
+ return 0
+
+ def check(self):
+ return 0
+
+
+
+# Wrapper to emulate pcm writes of sound samples to stdout (for liquidsoap)
+class stdout_wrapper(object):
+ def __init__(self):
+ self.silence = chr(0) * 640
+ pass
+
+ def open(self, hwdev):
+ return 0
+
+ def close(self):
+ return 0
+
+ def setup(self, pcm_format, pcm_channels, pcm_rate, pcm_buffer_size):
+ return 0
+
+ def drain(self):
+ try:
+ sys.stdout.flush()
+ except IOError: # IOError means listener has terminated
+ return -1
+ return 0
+
+ def drop(self):
+ return 0
+
+ def write(self, pcm_data):
+ try:
+ if sys.version[0] != '2' and type(pcm_data) is str:
+ pcm_data = pcm_data.encode('latin1') # python3 strikes again
+ sys.stdout.write(pcm_data)
+ except IOError: # IOError means listener has terminated
+ return -1
+ return 0
+
+ def check(self):
+ rc = 0
+ if (self.write(self.silence) < 0) or (self.drain() < 0): # write silence to check pipe connectivity
+ rc = -1
+ return rc
+
+ def dump(self):
+ pass
+
+# Main class that receives UDP audio samples and sends them to a PCM subsystem (currently ALSA or STDOUT)
+class socket_audio(object):
+ def __init__(self, udp_host, udp_port, pcm_device, two_channels = False, audio_gain = 1.0, dest_stdout = False, silent_flag=False, **kwds):
+ self.keep_running = True
+ self.two_channels = two_channels
+ self.audio_gain = audio_gain
+ self.dest_stdout = dest_stdout
+ self.sock_a = None
+ self.sock_b = None
+ self.pcm = None
+ self.silent_flag = silent_flag
+ if dest_stdout:
+ pcm_device = "stdout"
+ sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0) # reopen stdout with buffering disabled
+ self.pcm = stdout_wrapper()
+ else:
+ if pcm_device.lower() == "pulse":
+ try:
+ self.pcm = pa_sound() # first try to use PulseAudio
+ sys.stderr.write("using PulseAudio sound system\n")
+ except:
+ sys.stderr.write("unable to load PulseAudio library\n")
+ pcm_device = "default"
+
+ if self.pcm is None:
+ try:
+ self.pcm = alsasound() # if PulseAudio not available, try to use ALSA
+ sys.stderr.write("using ALSA sound system\n")
+ except:
+ sys.stderr.write("unable to load ALSA library\n")
+
+ if self.pcm is not None:
+ self.setup_pcm(pcm_device)
+ else:
+ self.keep_running = False
+
+ self.setup_sockets(udp_host, udp_port)
+
+ def run(self):
+ rc = 0
+ while self.keep_running and (rc >= 0):
+ readable, writable, exceptional = select.select( [self.sock_a, self.sock_b], [], [self.sock_a, self.sock_b], 5.0)
+ in_a = None
+ in_b = None
+ data_a = ""
+ data_b = ""
+ flag_a = -1
+ flag_b = -1
+
+ # Check for select() polling timeout and pcm self-check
+ if (not readable) and (not writable) and (not exceptional):
+ if self.silent_flag:
+ rc = 0 # suppress additional zeros to preserve timing
+ else:
+ rc = self.pcm.check()
+ if isinstance(rc, ctypes.c_int):
+ rc = rc.value
+ continue
+
+ # Data received on the udp port is 320 bytes for an audio frame or 2 bytes for a flag
+ if self.sock_a in readable:
+ in_a = self.sock_a.recvfrom(MAX_SUPERFRAME_SIZE)
+
+ if self.sock_b in readable:
+ in_b = self.sock_b.recvfrom(MAX_SUPERFRAME_SIZE)
+
+ if in_a is not None:
+ len_a = len(in_a[0])
+ if len_a == 2:
+ flag_a = np.frombuffer(in_a[0], dtype=np.int16)[0]
+ elif len_a > 0:
+ data_a = in_a[0]
+
+ if in_b is not None:
+ len_b = len(in_b[0])
+ if len_b == 2:
+ flag_b = np.frombuffer(in_b[0], dtype=np.int16)[0]
+ elif len_b > 0:
+ data_b = in_b[0]
+
+ if (flag_a == 0) or (flag_b == 0):
+ rc = self.pcm.drain()
+ if isinstance(rc, ctypes.c_int):
+ rc = rc.value
+ continue
+
+ if (((flag_a == 1) and (flag_b == 1)) or
+ ((flag_a == 1) and (in_b is None)) or
+ ((flag_b == 1) and (in_a is None))):
+ rc = self.pcm.drop()
+ if isinstance(rc, ctypes.c_int):
+ rc = rc.value
+ continue
+
+ if not self.two_channels:
+ data_a = self.scale(data_a)
+ rc = self.pcm.write(self.interleave(data_a, data_a))
+ if isinstance(rc, ctypes.c_int):
+ rc = rc.value
+ else:
+ data_a = self.scale(data_a)
+ data_b = self.scale(data_b)
+ rc = self.pcm.write(self.interleave(data_a, data_b))
+ if isinstance(rc, ctypes.c_int):
+ rc = rc.value
+
+ self.close_sockets()
+ self.close_pcm()
+ return
+
+ def scale(self, data): # crude amplitude scaler (volume) for S16_LE samples
+ arr = np.array(np.frombuffer(data, dtype=np.int16), dtype=np.float32)
+ result = np.zeros(len(arr), dtype=np.int16)
+ arr = np.clip(arr*self.audio_gain, -32767, 32766, out=result)
+ return result.tobytes('C')
+
+ def interleave(self, data_a, data_b):
+ arr_a = np.frombuffer(data_a, dtype=np.int16)
+ arr_b = np.frombuffer(data_b, dtype=np.int16)
+ d_len = max(len(arr_a), len(arr_b))
+ result = np.zeros(d_len*2, dtype=np.int16)
+ if len(arr_a):
+ # copy arr_a to result[0,2,4, ...]
+ result[ range(0, len(arr_a)*2, 2) ] = arr_a
+ if len(arr_b):
+ # copy arr_b to result[1,3,5, ...]
+ result[ range(1, len(arr_b)*2, 2) ] = arr_b
+ return result.tobytes('C')
+
+ def stop(self):
+ self.keep_running = False
+ return
+
+ def setup_sockets(self, udp_host, udp_port):
+ sys.stderr.write("Listening on %s:%d\n" % (udp_host, udp_port))
+ self.sock_a = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock_b = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock_a.setblocking(0)
+ self.sock_b.setblocking(0)
+ self.sock_a.bind((udp_host, udp_port))
+ self.sock_b.bind((udp_host, udp_port + 2))
+ return
+
+ def close_sockets(self):
+ self.sock_a.close()
+ self.sock_b.close()
+ return
+
+ def setup_pcm(self, hwdevice):
+ sys.stderr.write('audio device: %s\n' % hwdevice)
+ err = self.pcm.open(hwdevice)
+ if err < 0:
+ sys.stderr.write('failed to open audio device: %s\n' % hwdevice)
+ self.pcm.dump()
+ self.keep_running = False
+ return
+
+ err = self.pcm.setup(SND_PCM_FORMAT_S16_LE.value, 2, PCM_RATE, PCM_BUFFER_SIZE)
+ if err < 0:
+ sys.stderr.write('failed to set up pcm stream\n')
+ self.keep_running = False
+ return
+ return
+
+ def close_pcm(self):
+ sys.stderr.write('audio closing\n')
+ if self.pcm is not None:
+ self.pcm.close()
+ return
+
+class audio_thread(threading.Thread):
+ def __init__(self, udp_host, udp_port, pcm_device, two_channels = False, audio_gain = 1.0, dest_stdout = False, **kwds):
+ threading.Thread.__init__(self, **kwds)
+ self.setDaemon(True)
+ self.keep_running = True
+ self.sock_audio = socket_audio(udp_host, udp_port, pcm_device, two_channels, audio_gain, dest_stdout, **kwds)
+ self.start()
+ return
+
+ def run(self):
+ self.sock_audio.run()
+
+ def stop(self):
+ self.sock_audio.stop()
diff --git a/op25/gr-op25_repeater/apps/sql_dbi.py b/op25/gr-op25_repeater/apps/sql_dbi.py
new file mode 100755
index 0000000..4837359
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/sql_dbi.py
@@ -0,0 +1,338 @@
+#!/usr/bin/env python
+
+# Copyright 2021 Max H. Parke KA1RBI
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import sys
+import os
+import time
+import json
+import threading
+import traceback
+import sqlite3
+
+import op25
+from gnuradio import gr
+
+from emap import events_map, cc_events
+
+_def_db_file = 'op25-data.db'
+_def_msgq_size = 100
+_def_uncommitted = 25
+
+class du_queue_runner(threading.Thread):
+ def __init__(self, msgq, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.msgq = msgq
+ self.db_filename = _def_db_file
+ self.conn = None
+ self.cursor = None
+ self.failed = False
+ self.keep_running = True
+ self.uncommitted = 0
+ self.max_q = 0
+ self.next_t = time.time()
+ self.start()
+
+ def run(self):
+ self.connect()
+ while self.keep_running and not self.failed:
+ self.max_q = max(self.max_q, self.msgq.count())
+ if time.time() > self.next_t:
+ self.next_t = time.time() + 2
+ msg = self.msgq.delete_head()
+ if self.failed or not self.keep_running:
+ break
+ self.insert_row(msg)
+
+ def disconnect(self):
+ self.conn.close()
+ self.cursor = None
+ self.conn = None
+
+ def connect(self):
+ self.conn = sqlite3.connect(self.db_filename)
+ self.cursor = self.conn.cursor()
+
+ def insert_row(self, msg):
+ if self.cursor is None or self.conn is None:
+ return
+ d = json.loads(msg.to_string())
+ try:
+ self.cursor.execute(d['command'], d['row'])
+ # optimization: only commit when no more msgs queued (or limit reached)
+ if self.uncommitted < _def_uncommitted and self.msgq.count():
+ self.uncommitted += 1
+ else:
+ self.conn.commit()
+ self.uncommitted = 0
+ except:
+ self.failed = True
+ traceback.print_exc(limit=None, file=sys.stdout)
+ traceback.print_exc(limit=None, file=sys.stderr)
+ sys.stderr.write('sql_dbi: db logging stopped due to error (or db not initialized)\n')
+ # TODO - add error recovery?
+
+class sql_dbi:
+ def __init__(self, db_filename=_def_db_file):
+ self.conn = None
+ self.cursor = None
+ self.db_filename = db_filename
+ self.db_msgq = gr.msg_queue(_def_msgq_size)
+ self.q_runner = du_queue_runner(self.db_msgq)
+ self.db_msgq_overflow = 0
+
+ self.sql_commands = {
+ 'calls': 'INSERT INTO calls(time, sysid, options, tgid, srcid)',
+ 'joins': 'INSERT INTO joins(time, sysid, rv, tgid, srcid)',
+ 'create_data_store': '''CREATE TABLE data_store (
+ id INTEGER PRIMARY KEY,
+ time REAL NOT NULL,
+ cc_event INTEGER NOT NULL,
+ opcode INTEGER NOT NULL,
+ sysid INTEGER NOT NULL,
+ mfrid INTEGER NULL,
+ p INTEGER NULL,
+ p2 INTEGER NULL,
+ p3 INTEGER NULL,
+ wacn INTEGER NULL,
+ frequency INTEGER NULL,
+ tgid INTEGER NULL,
+ tgid2 INTEGER NULL,
+ suid INTEGER NULL,
+ suid2 INTEGER NULL,
+ tsbk_sysid INTEGER NULL,
+ FOREIGN KEY(cc_event) REFERENCES event_keys (id))''',
+ 'create_event_keys': '''CREATE TABLE event_keys (
+ id INTEGER PRIMARY KEY,
+ tag TEXT NOT NULL )''',
+ 'create_sysid': '''CREATE TABLE sysid_tags (
+ id INTEGER PRIMARY KEY,
+ sysid INTEGER NOT NULL,
+ tag TEXT)''',
+ 'create_tgid': '''CREATE TABLE tgid_tags (
+ id INTEGER PRIMARY KEY,
+ rid INTEGER NOT NULL,
+ sysid INTEGER NOT NULL,
+ tag TEXT,
+ priority INTEGER)''',
+ 'create_unit_id': '''CREATE TABLE unit_id_tags (
+ id INTEGER PRIMARY KEY,
+ rid INTEGER NOT NULL,
+ sysid INTEGER NOT NULL,
+ tag TEXT,
+ priority INTEGER)''',
+ 'create_2b_rv': '''CREATE TABLE loc_reg_resp_rv (
+ rv INTEGER NOT NULL,
+ tag TEXT NOT NULL)''',
+ 'populate_2b_rv': '''INSERT INTO loc_reg_resp_rv(rv, tag) VALUES(0, "join")
+ INSERT INTO loc_reg_resp_rv(rv, tag) VALUES(1, "fail")
+ INSERT INTO loc_reg_resp_rv(rv, tag) VALUES(2, "deny")
+ INSERT INTO loc_reg_resp_rv(rv, tag) VALUES(3, "refuse")''',
+ 'create_index': '''CREATE INDEX tgid_idx ON data_store(tgid)
+ CREATE INDEX tgid2_idx ON data_store(tgid2)
+ CREATE INDEX suid_idx ON data_store(suid)
+ CREATE INDEX suid2_idx ON data_store(suid2)
+ CREATE INDEX t_tgid_idx ON tgid_tags(rid)
+ CREATE INDEX t_unit_id_idx ON unit_id_tags(rid)'''
+ }
+
+ def disconnect(self):
+ self.conn.close()
+ self.cursor = None
+ self.conn = None
+
+ def connect(self):
+ self.conn = sqlite3.connect(self.db_filename)
+ self.cursor = self.conn.cursor()
+
+ def reset_db(self): # any data in db will be destroyed!
+ if os.access(self.db_filename, os.W_OK):
+ os.remove(self.db_filename)
+ self.conn = sqlite3.connect(self.db_filename)
+ self.cursor = self.conn.cursor()
+ self.execute('create_sysid')
+ self.execute('create_2b_rv')
+ self.execute_lines('populate_2b_rv')
+ self.execute('create_tgid')
+ self.execute('create_unit_id')
+ self.execute('create_event_keys')
+ self.execute('create_data_store')
+ self.execute_lines('create_index')
+ self.conn.commit()
+ self.populate_event_keys()
+ self.conn.close()
+
+ def execute(self, q):
+ self.cursor.execute(self.sql_commands[q])
+ self.conn.commit()
+
+ def execute_lines(self,q):
+ for line in self.sql_commands[q].split('\n'):
+ self.cursor.execute(line)
+ self.conn.commit()
+
+ def q(self, query):
+ if query != '-':
+ return self.cursor.execute(query)
+ lines = sys.stdin.read().strip().split('\n')
+ for query in lines:
+ self.cursor.execute(query)
+ self.conn.commit()
+ return None
+
+ def write(self, table_name, row):
+ # the number of elements in tuple 'row' must be two less than the number of table columns
+ curr_time = time.time()
+ row = (curr_time,) + row
+ qs = ['?'] * len(row)
+ command = self.sql_commands[table_name] + ' VALUES (' + ','.join(qs) + ')'
+ self.cursor.execute(command, row)
+ self.conn.commit()
+
+ def event(self, d):
+ if d['cc_event'] not in events_map:
+ return
+ if not os.access(_def_db_file, os.W_OK): # if DB not (yet) set up or not writable
+ return
+ mapl = events_map[d['cc_event']]
+ row = []
+ column_names = []
+ for col in mapl:
+ colname = col[0]
+ k = col[1]
+ # special mappings: unwrap tgid and srcid objects
+ if colname.startswith('tgid') and type(d[k]) is dict:
+ val = d[k]['tg_id']
+ elif colname.startswith('suid') and type(d[k]) is dict:
+ val = d[k]['unit_id']
+ elif type(d[k]) is not dict:
+ val = d[k]
+ else:
+ sys.stderr.write('value retrieval error %s %s %s\n' % (d['cc_event'], type(d[k]) is dict, k))
+ val = -1
+ # special mappings: map cc_event tag to an int
+ if colname == 'cc_event':
+ val = cc_events[d[k]]
+ # special mappings: map affiliation to int
+ if k == 'affiliation':
+ if d[k] == 'global':
+ val = 1
+ elif d[k] == 'local':
+ val = 0
+ else:
+ val = -1
+ # special mappings: map duration to int(msec).
+ if k == 'duration':
+ val = int(d[k] * 1000)
+ row.append(val)
+ column_names.append(colname)
+ command = "INSERT INTO data_store(%s) VALUES(%s)" % (','.join(column_names), ','.join(['?'] * len(row)))
+ js = json.dumps({'command': command, 'row': row})
+ if not self.db_msgq.full_p():
+ msg = gr.message().make_from_string(js, 0, 0, 0)
+ self.db_msgq.insert_tail(msg)
+ else:
+ self.db_msgq_overflow += 1
+
+ def import_tsv(self, argv):
+ cmd = argv[1]
+ filename = argv[2]
+ sysid = int(argv[3])
+ if cmd == 'import_tgid':
+ table = 'tgid_tags'
+ elif cmd == 'import_unit':
+ table = 'unit_id_tags'
+ elif cmd == 'import_sysid':
+ table = 'sysid_tags'
+ else:
+ print('%s unsupported' % (cmd))
+ return
+ q = 'INSERT INTO ' + table + '(rid, sysid, tag, priority) VALUES(?,?,?,?)'
+ if table == 'sysid_tags':
+ q = 'INSERT INTO ' + table + '(sysid, tag) VALUES(?,?)'
+ rows = []
+ with open(filename, 'r') as f:
+ lines = f.read().rstrip().split('\n')
+ for i in range(len(lines)):
+ a = lines[i].split('\t')
+ if i == 0: # check hdr
+ if not a[0].strip().isdigit():
+ continue
+ rid = int(a[0])
+ tag = a[1]
+ priority = 0 if len(a) < 3 else int(a[2])
+ s = (rid, sysid, tag, priority)
+ if table == 'sysid_tags':
+ s = (rid, tag)
+ rows.append(s)
+ if len(rows):
+ self.cursor.executemany(q, rows)
+ self.conn.commit()
+
+ def populate_event_keys(self):
+ d = {cc_events[k]:k for k in cc_events}
+ query = 'INSERT INTO event_keys(id, tag) VALUES(?, ?)'
+ for k in sorted(d.keys()):
+ self.cursor.execute(query, [k, d[k]])
+ self.conn.commit()
+
+def main():
+ if len(sys.argv) > 1 and sys.argv[1] == 'reset_db':
+ sql_dbi().reset_db()
+ return
+
+ db1 = sql_dbi()
+ db1.connect()
+
+ if len(sys.argv) > 1 and sys.argv[1] == 'setup':
+ db1.cursor.execute(db1.sql_commands['create_tgid'])
+ db1.cursor.execute(db1.sql_commands['create_unit_id'])
+ db1.conn.commit()
+ db1.conn.close()
+ return
+
+ if len(sys.argv) > 1 and sys.argv[1] == 'execute_lines':
+ db1.execute_lines(sys.argv[2])
+ return
+
+ if len(sys.argv) > 1 and sys.argv[1] == 'execute':
+ db1.execute(sys.argv[2])
+ return
+
+ if len(sys.argv) > 1 and sys.argv[1] == 'insert':
+ db1.write('joins', (555, 5555, 5555555))
+ return
+
+ if len(sys.argv) > 3 and sys.argv[1].startswith('import_'):
+ db1.import_tsv(sys.argv)
+ return
+
+ if len(sys.argv) < 3 or sys.argv[1] != 'query':
+ print('nothing done')
+ return
+
+ result = db1.q(sys.argv[2])
+ if result:
+ for row in result:
+ print ('%s' % ('\t'.join([str(x) for x in row])))
+
+if __name__ == '__main__':
+ main()
diff --git a/op25/gr-op25_repeater/apps/tdma/bit_utils.py b/op25/gr-op25_repeater/apps/tdma/bit_utils.py
index df667dd..7238807 100644
--- a/op25/gr-op25_repeater/apps/tdma/bit_utils.py
+++ b/op25/gr-op25_repeater/apps/tdma/bit_utils.py
@@ -22,7 +22,7 @@ import numpy as np
def rev_int(n,l):
j=0
- for i in xrange(l):
+ for i in range(l):
b=n&1
n=n>>1
j = (j << 1) | b
@@ -30,7 +30,7 @@ def rev_int(n,l):
def bits_to_dibits(bits):
d = []
- for i in xrange(len(bits)>>1):
+ for i in range(len(bits)>>1):
d.append((bits[i*2]<<1) + bits[i*2+1])
return d
@@ -43,14 +43,14 @@ def dibits_to_bits(dibits):
def mk_array(n, l):
a = []
- for i in xrange(0,l):
+ for i in range(0,l):
a.insert(0, n & 1)
n = n >> 1
return np.array(a)
def mk_int(a):
- res= 0L
- for i in xrange(0, len(a)):
+ res= 0
+ for i in range(0, len(a)):
res = res * 2
res = res + (a[i] & 1)
return res
@@ -61,7 +61,7 @@ def mk_str(a):
def check_l(a,b):
ans = 0
assert len(a) == len(b)
- for i in xrange(len(a)):
+ for i in range(len(a)):
if (a[i] == b[i]):
ans += 1
return ans
@@ -77,7 +77,7 @@ def fixup(a):
return res
def find_sym(pattern, symbols):
- for i in xrange(0, len(symbols)-len(pattern)):
+ for i in range(0, len(symbols)-len(pattern)):
chunk = symbols[i : i + len(pattern)]
if chunk == pattern:
return i
diff --git a/op25/gr-op25_repeater/apps/tdma/lfsr.py b/op25/gr-op25_repeater/apps/tdma/lfsr.py
index 6a7d8ac..b746e92 100644
--- a/op25/gr-op25_repeater/apps/tdma/lfsr.py
+++ b/op25/gr-op25_repeater/apps/tdma/lfsr.py
@@ -25,65 +25,80 @@ class p25p2_lfsr(object):
def __init__(self,nac,sysid,wacn):
xorbits = self.mk_xor_bits(nac,sysid,wacn)
#self.xorsyms = np.zeros(len(xorbits)/2)
- self.xorsyms = [0] * (len(xorbits)/2)
- for i in xrange(len(self.xorsyms)):
+ self.xorsyms = [0] * (len(xorbits)//2)
+ for i in range(len(self.xorsyms)):
self.xorsyms[i] = (xorbits[i*2] << 1) + xorbits[i*2+1]
self.xor_chars = ''.join([chr(c) for c in self.xorsyms])
def asm_reg(self,s1,s2,s3,s4,s5,s6):
- s1 = s1 & 0xfL
- s2 = s2 & 0x1fL
- s3 = s3 & 0x3fL
- s4 = s4 & 0x1fL
- s5 = s5 & 0x3fffL
- s6 = s6 & 0x3ffL
+ s1 = s1 & 0xf
+ s2 = s2 & 0x1f
+ s3 = s3 & 0x3f
+ s4 = s4 & 0x1f
+ s5 = s5 & 0x3fff
+ s6 = s6 & 0x3ff
return (s1<<40)+(s2<<35)+(s3<<29)+(s4<<24)+(s5<<10)+s6
def disasm_reg(self,r):
- s1 = (r>>40) & 0xfL
- s2 = (r>>35) & 0x1fL
- s3 = (r>>29) & 0x3fL
- s4 = (r>>24) & 0x1fL
- s5 = (r>>10) & 0x3fffL
- s6 = r & 0x3ffL
+ s1 = (r>>40) & 0xf
+ s2 = (r>>35) & 0x1f
+ s3 = (r>>29) & 0x3f
+ s4 = (r>>24) & 0x1f
+ s5 = (r>>10) & 0x3fff
+ s6 = r & 0x3ff
return s1,s2,s3,s4,s5,s6
def cyc_reg(self, reg):
s1,s2,s3,s4,s5,s6 = self.disasm_reg(reg)
- cy1 = (s1 >> 3) & 1L
- cy2 = (s2 >> 4) & 1L
- cy3 = (s3 >> 5) & 1L
- cy4 = (s4 >> 4) & 1L
- cy5 = (s5 >> 13) & 1L
- cy6 = (s6 >> 9) & 1L
+ cy1 = (s1 >> 3) & 1
+ cy2 = (s2 >> 4) & 1
+ cy3 = (s3 >> 5) & 1
+ cy4 = (s4 >> 4) & 1
+ cy5 = (s5 >> 13) & 1
+ cy6 = (s6 >> 9) & 1
x1 = cy1 ^ cy2
x2 = cy1 ^ cy3
x3 = cy1 ^ cy4
x4 = cy1 ^ cy5
x5 = cy1 ^ cy6
- s1 = (s1 << 1) & 0xfL
- s2 = (s2 << 1) & 0x1fL
- s3 = (s3 << 1) & 0x3fL
- s4 = (s4 << 1) & 0x1fL
- s5 = (s5 << 1) & 0x3fffL
- s6 = (s6 << 1) & 0x3ffL
- s1 = s1 | (x1 & 1L)
- s2 = s2 | (x2 & 1L)
- s3 = s3 | (x3 & 1L)
- s4 = s4 | (x4 & 1L)
- s5 = s5 | (x5 & 1L)
- s6 = s6 | (cy1 & 1L)
+ s1 = (s1 << 1) & 0xf
+ s2 = (s2 << 1) & 0x1f
+ s3 = (s3 << 1) & 0x3f
+ s4 = (s4 << 1) & 0x1f
+ s5 = (s5 << 1) & 0x3fff
+ s6 = (s6 << 1) & 0x3ff
+ s1 = s1 | (x1 & 1)
+ s2 = s2 | (x2 & 1)
+ s3 = s3 | (x3 & 1)
+ s4 = s4 | (x4 & 1)
+ s5 = s5 | (x5 & 1)
+ s6 = s6 | (cy1 & 1)
return self.asm_reg(s1,s2,s3,s4,s5,s6)
def mk_xor_bits(self, nac,sysid,wacn):
- reg = mk_array(16777216*wacn + 4096*sysid + nac, 44)
+ reg = np.int64(mk_array(16777216*wacn + 4096*sysid + nac, 44))
M = np.array(np.mat('1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0; 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0; 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0; 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0; 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1; 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1'))
reg = mk_int(np.dot(reg,M))
s = []
- for i in xrange(4320):
+ for i in range(4320):
s.append((reg >> 43) & 1)
reg = self.cyc_reg(reg)
return s
+
+if __name__ == '__main__':
+ import sys
+
+ xor_cache = {}
+ params = {}
+ params['nac'] = 0x293
+ params['sysid'] = 0x18
+ params['wacn'] = 0x1
+
+ hash = '%x%x%x' % (params['nac'], params['sysid'], params['wacn'])
+ if hash not in xor_cache:
+ xor_cache[hash] = p25p2_lfsr(params['nac'], params['sysid'], params['wacn']).xor_chars
+
+ sys.stdout.write(xor_cache[hash])
diff --git a/op25/gr-op25_repeater/apps/tdma/tdma_audio.py b/op25/gr-op25_repeater/apps/tdma/tdma_audio.py
index 391ed9f..ade6bb6 100755
--- a/op25/gr-op25_repeater/apps/tdma/tdma_audio.py
+++ b/op25/gr-op25_repeater/apps/tdma/tdma_audio.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-from gnuradio import gr, gru, audio, eng_notation, analog, blocks, filter
+from gnuradio import gr, audio, eng_notation, analog, blocks, filter
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import numpy as np
diff --git a/op25/gr-op25_repeater/apps/terminal.py b/op25/gr-op25_repeater/apps/terminal.py
index 46efa1a..fb4b7f8 100644..100755
--- a/op25/gr-op25_repeater/apps/terminal.py
+++ b/op25/gr-op25_repeater/apps/terminal.py
@@ -1,8 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2008-2011 Steve Glass
#
-# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Max H. Parke KA1RBI
#
# This file is part of OP25
#
@@ -28,11 +28,29 @@ import time
import json
import threading
import traceback
+import socket
+import op25
from gnuradio import gr
+KEEPALIVE_TIME = 3.0 # no data received in (seconds)
+
+class q_watcher(threading.Thread):
+ def __init__(self, msgq, callback, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.msgq = msgq
+ self.callback = callback
+ self.keep_running = True
+ self.start()
+
+ def run(self):
+ while(self.keep_running):
+ msg = self.msgq.delete_head()
+ self.callback(msg)
+
class curses_terminal(threading.Thread):
- def __init__(self, input_q, output_q, **kwds):
+ def __init__(self, input_q, output_q, sock=None, **kwds):
threading.Thread.__init__ (self, **kwds)
self.setDaemon(1)
self.input_q = input_q
@@ -41,31 +59,83 @@ class curses_terminal(threading.Thread):
self.last_update = 0
self.auto_update = True
self.current_nac = None
+ self.maxx = 0
+ self.maxy = 0
+ self.sock = sock
self.start()
def setup_curses(self):
self.stdscr = curses.initscr()
+ self.maxy, self.maxx = self.stdscr.getmaxyx()
+ if (self.maxy < 6) or (self.maxx < 60):
+ sys.stderr.write("Terminal window too small! Minimum size [70 x 6], actual [%d x %d]\n" % (self.maxx, self.maxy))
+ print ("Terminal window too small! Minimum size [70 x 6], actual [%d x %d]\n" % (self.maxx, self.maxy))
+ self.keep_running = False
+ return
curses.noecho()
curses.halfdelay(1)
- self.top_bar = curses.newwin(1, 80, 0, 0)
- self.freq_list = curses.newwin(20, 80, 1, 0)
- self.active1 = curses.newwin(1, 80, 21, 0)
- self.active2 = curses.newwin(1, 80, 22, 0)
- self.prompt = curses.newwin(1, 10, 23, 0)
- self.text_win = curses.newwin(1, 70, 23, 10)
-
+ self.title_bar = curses.newwin(1, self.maxx, 0, 0)
+ self.help_bar = curses.newwin(1, self.maxx, self.maxy-1, 0)
+ self.top_bar = curses.newwin(1, self.maxx, 1, 0)
+ self.freq_list = curses.newwin(self.maxy-5, self.maxx, 2, 0)
+ self.active1 = curses.newwin(1, self.maxx-15, self.maxy-3, 0)
+ self.active2 = curses.newwin(1, self.maxx-15, self.maxy-2, 0)
+ self.status1 = curses.newwin(1, 15, self.maxy-3, self.maxx-15)
+ self.status2 = curses.newwin(1, 15, self.maxy-2, self.maxx-15)
+ self.prompt = curses.newwin(1, 10, self.maxy-1, 0)
+ self.text_win = curses.newwin(1, 11, self.maxy-1, 10)
self.textpad = curses.textpad.Textbox(self.text_win)
+ self.stdscr.refresh()
+
+ self.title_help()
+
+ def resize_curses(self):
+ self.maxy, self.maxx = self.stdscr.getmaxyx()
+
+ if (self.maxx < 60) or (self.maxy < 6): # do not resize if window is now too small
+ return
- def end_curses(self):
+ self.stdscr.erase()
+
+ self.title_bar.resize(1, self.maxx)
+ self.help_bar.resize(1, self.maxx)
+ self.help_bar.mvwin(self.maxy-1, 0)
+ self.top_bar.resize(1, self.maxx)
+ self.freq_list.resize(self.maxy-5, self.maxx)
+ self.active1.resize(1, self.maxx-15)
+ self.active1.mvwin(self.maxy-3, 0)
+ self.active2.resize(1, self.maxx-15)
+ self.active2.mvwin(self.maxy-2, 0)
+ self.status1.resize(1, 15)
+ self.status1.mvwin(self.maxy-3, self.maxx-15)
+ self.status2.resize(1, 15)
+ self.status2.mvwin(self.maxy-2, self.maxx-15)
+ self.stdscr.refresh()
+
+ self.title_help()
+
+ def end_terminal(self):
try:
curses.endwin()
except:
pass
+ def title_help(self):
+ title_str = "OP25"
+ help_str = "(f)req (h)old (s)kip (l)ock (q)uit"
+ self.title_bar.erase()
+ self.help_bar.erase()
+ self.title_bar.addstr(0, 0, title_str.center(self.maxx-1, " "), curses.A_REVERSE)
+ self.help_bar.addstr(0, 0, help_str.center(self.maxx-1, " "), curses.A_REVERSE)
+ self.title_bar.refresh()
+ self.help_bar.refresh()
+ self.stdscr.move(1,0)
+ self.stdscr.refresh()
+
def do_auto_update(self):
- UPDATE_INTERVAL = 1 # sec.
+ UPDATE_INTERVAL = 0.5 # sec.
if not self.auto_update:
return False
if self.last_update + UPDATE_INTERVAL > time.time():
@@ -75,32 +145,33 @@ class curses_terminal(threading.Thread):
def process_terminal_events(self):
# return true signifies end of main event loop
+ if curses.is_term_resized(self.maxy, self.maxx) is True:
+ self.resize_curses()
+
_ORD_S = ord('s')
_ORD_L = ord('l')
_ORD_H = ord('h')
COMMANDS = {_ORD_S: 'skip', _ORD_L: 'lockout', _ORD_H: 'hold'}
c = self.stdscr.getch()
if c == ord('u') or self.do_auto_update():
- msg = gr.message().make_from_string('update', -2, 0, 0)
- self.output_q.insert_tail(msg)
+ self.send_command('update', 0)
if c in COMMANDS.keys():
- msg = gr.message().make_from_string(COMMANDS[c], -2, 0, 0)
- self.output_q.insert_tail(msg)
+ self.send_command(COMMANDS[c], 0)
elif c == ord('q'):
- return True
+ return True
elif c == ord('t'):
if self.current_nac:
- msg = gr.message().make_from_string('add_default_config', -2, int(self.current_nac), 0)
- self.output_q.insert_tail(msg)
+ self.send_command('add_default_config', int(self.current_nac))
elif c == ord('f'):
self.prompt.addstr(0, 0, 'Frequency')
self.prompt.refresh()
- self.text_win.clear()
+ self.text_win.erase()
response = self.textpad.edit()
- self.prompt.clear()
+ self.prompt.erase()
self.prompt.refresh()
- self.text_win.clear()
+ self.text_win.erase()
self.text_win.refresh()
+ self.title_help()
try:
freq = float(response)
if freq < 10000:
@@ -108,8 +179,37 @@ class curses_terminal(threading.Thread):
except:
freq = None
if freq:
- msg = gr.message().make_from_string('set_freq', -2, freq, 0)
- self.output_q.insert_tail(msg)
+ self.send_command('set_freq', freq)
+ elif c == ord('H'):
+ self.prompt.addstr(0, 0, 'Hold tgid')
+ self.prompt.refresh()
+ self.text_win.erase()
+ response = self.textpad.edit()
+ self.prompt.erase()
+ self.prompt.refresh()
+ self.text_win.erase()
+ self.text_win.refresh()
+ self.title_help()
+ try:
+ tgid = int(response)
+ if (tgid < 0) or (tgid > 65535):
+ tgid = 0
+ except:
+ tgid = 0
+ self.send_command('hold', tgid)
+
+ elif c == ord(','):
+ self.send_command('adj_tune', -100)
+ elif c == ord('.'):
+ self.send_command('adj_tune', 100)
+ elif c == ord('<'):
+ self.send_command('adj_tune', -1200)
+ elif c == ord('>'):
+ self.send_command('adj_tune', 1200)
+ elif (c >= ord('1') ) and (c <= ord('5')):
+ self.send_command('toggle_plot', (c - ord('0')))
+ elif c == ord('d'):
+ self.send_command('dump_tgids', 0)
elif c == ord('x'):
assert 1 == 0
return False
@@ -118,11 +218,14 @@ class curses_terminal(threading.Thread):
# return true signifies end of main event loop
msg = json.loads(js)
if msg['json_type'] == 'trunk_update':
- nacs = [x for x in msg.keys() if x != 'json_type']
+ nacs = [x for x in msg.keys() if x.isnumeric() ]
if not nacs:
return
- times = {msg[nac]['last_tsbk']:nac for nac in nacs}
- current_nac = times[ sorted(times.keys(), reverse=True)[0] ]
+ if msg.get('nac'):
+ current_nac = str(msg['nac'])
+ else:
+ times = {msg[nac]['last_tsbk']:nac for nac in nacs}
+ current_nac = times[ sorted(times.keys(), reverse=True)[0] ]
self.current_nac = current_nac
s = 'NAC 0x%x' % (int(current_nac))
s += ' WACN 0x%x' % (msg[current_nac]['wacn'])
@@ -131,30 +234,50 @@ class curses_terminal(threading.Thread):
s += '/%f' % (msg[current_nac]['txchan']/ 1000000.0)
s += ' tsbks %d' % (msg[current_nac]['tsbks'])
freqs = sorted(msg[current_nac]['frequencies'].keys())
- s = s[:79]
- self.top_bar.clear()
+ s = s[:(self.maxx - 1)]
+ self.top_bar.erase()
self.top_bar.addstr(0, 0, s)
self.top_bar.refresh()
- self.freq_list.clear()
- for i in xrange(len(freqs)):
+ self.freq_list.erase()
+ for i in range(len(freqs)):
+ if i > (self.maxy - 6):
+ break
s=msg[current_nac]['frequencies'][freqs[i]]
- s = s[:79]
+ s = s[:(self.maxx - 1)]
self.freq_list.addstr(i, 0, s)
self.freq_list.refresh()
+ self.status1.erase()
+ if 'srcaddr' in msg:
+ srcaddr = msg['srcaddr']
+ if (srcaddr != 0) and (srcaddr != 0xffffff):
+ s = '%d' % (srcaddr)
+ s = s[:14]
+ self.status1.addstr(0, (14-len(s)), s)
+ self.status1.refresh()
+ self.status2.erase()
+ if 'encrypted' in msg:
+ encrypted = msg['encrypted']
+ if encrypted != 0:
+ s = 'ENCRYPTED'
+ self.status2.addstr(0, (14-len(s)), s, curses.A_REVERSE)
+ self.status2.refresh()
self.stdscr.refresh()
elif msg['json_type'] == 'change_freq':
s = 'Frequency %f' % (msg['freq'] / 1000000.0)
+ if 'fine_tune' in msg and msg['fine_tune'] is not None:
+ s +='(%d)' % msg['fine_tune']
if msg['tgid'] is not None:
s += ' Talkgroup ID %s' % (msg['tgid'])
if msg['tdma'] is not None:
s += ' TDMA Slot %s' % msg['tdma']
- self.active1.clear()
- self.active2.clear()
+ s = s[:(self.maxx - 16)]
+ self.active1.erase()
+ self.active2.erase()
self.active1.addstr(0, 0, s)
self.active1.refresh()
if msg['tag']:
s = msg['tag']
- s = s[:79]
+ s = s[:(self.maxx - 16)]
self.active2.addstr(0, 0, s)
self.active2.refresh()
self.stdscr.refresh()
@@ -163,6 +286,8 @@ class curses_terminal(threading.Thread):
def process_q_events(self):
# return true signifies end of main event loop
while True:
+ if curses.is_term_resized(self.maxy, self.maxx) is True:
+ self.resize_curses()
if self.input_q.empty_p():
break
msg = self.input_q.delete_head_nowait()
@@ -170,18 +295,187 @@ class curses_terminal(threading.Thread):
return self.process_json(msg.to_string())
return False
+ def send_command(self, command, data):
+ if self.sock:
+ self.sock.send(json.dumps({'command': command, 'data': data}))
+ else:
+ msg = gr.message().make_from_string(command, -2, data, 0)
+ self.output_q.insert_tail(msg)
+
def run(self):
try:
self.setup_curses()
+
while(self.keep_running):
if self.process_terminal_events():
break
if self.process_q_events():
break
except:
- sys.stderr.write('terminal: exception occurred\n')
+ sys.stderr.write('terminal: exception occurred (%d, %d)\n' % (self.maxx, self.maxy))
sys.stderr.write('terminal: exception:\n%s\n' % traceback.format_exc())
finally:
- self.end_curses()
- msg = gr.message().make_from_string('quit', -2, 0, 0)
- self.output_q.insert_tail(msg)
+ self.end_terminal()
+ self.keep_running = False
+ self.send_command('quit', 0)
+
+class zeromq_terminal(threading.Thread):
+ def __init__(self, input_q, output_q, endpoint, **kwds):
+ import zmq
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.input_q = input_q
+ self.output_q = output_q
+ self.endpoint = endpoint
+ self.keep_running = True
+
+ if not endpoint.startswith('tcp:'):
+ sys.stderr.write('zeromq_terminal unsupported endpoint: %s\n' % endpoint)
+ return
+ port = endpoint.replace('tcp:', '')
+ port = int(port)
+
+ self.zmq_context = zmq.Context()
+
+ self.zmq_sub = self.zmq_context.socket(zmq.SUB)
+ self.zmq_sub.connect('tcp://localhost:%d' % (port+1))
+ self.zmq_sub.setsockopt(zmq.SUBSCRIBE, '')
+
+ self.zmq_pub = self.zmq_context.socket(zmq.PUB)
+ self.zmq_pub.sndhwm = 5
+ self.zmq_pub.bind('tcp://*:%d' % port)
+
+ self.queue_watcher = q_watcher(self.input_q, lambda msg : self.zmq_pub.send(msg.to_string()))
+ self.start()
+
+ def end_terminal(self):
+ self.keep_running = False
+
+ def run(self):
+ while self.keep_running:
+ js = self.zmq_sub.recv()
+ if not self.keep_running:
+ break
+ d = json.loads(js)
+ msg = gr.message().make_from_string(str(d['command']), d['msgtype'], d['data'], 0)
+ if self.output_q.full_p():
+ self.output_q.delete_head()
+ if not self.output_q.full_p():
+ self.output_q.insert_tail(msg)
+
+class http_terminal(threading.Thread):
+ def __init__(self, input_q, output_q, endpoint, **kwds):
+ from http_server import http_server
+
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.input_q = input_q
+ self.output_q = output_q
+ self.endpoint = endpoint
+ self.keep_running = True
+ self.server = http_server(self.input_q, self.output_q, self.endpoint)
+
+ self.start()
+
+ def end_terminal(self):
+ self.keep_running = False
+
+ def run(self):
+ self.server.run()
+
+class udp_terminal(threading.Thread):
+ def __init__(self, input_q, output_q, port, **kwds):
+ threading.Thread.__init__ (self, **kwds)
+ self.setDaemon(1)
+ self.input_q = input_q
+ self.output_q = output_q
+ self.keep_running = True
+ self.port = port
+ self.remote_ip = '127.0.0.1'
+ self.remote_port = 0
+ self.keepalive_until = 0
+
+ self.setup_socket(port)
+ self.q_handler = q_watcher(self.input_q, self.process_qmsg)
+ self.start()
+
+ def setup_socket(self, port):
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.bind(('0.0.0.0', port))
+
+ def process_qmsg(self, msg):
+ if time.time() >= self.keepalive_until:
+ return
+ s = msg.to_string()
+ if msg.type() == -4 and self.remote_port > 0:
+ self.sock.sendto(s, (self.remote_ip, self.remote_port))
+
+ def end_terminal(self):
+ self.keep_running = False
+
+ def run(self):
+ while self.keep_running:
+ data, addr = self.sock.recvfrom(2048)
+ data = json.loads(data)
+ if data['command'] == 'quit':
+ self.keepalive_until = 0
+ continue
+ msg = gr.message().make_from_string(str(data['command']), -2, data['data'], 0)
+ self.output_q.insert_tail(msg)
+ self.remote_ip = addr[0]
+ self.remote_port = addr[1]
+ self.keepalive_until = time.time() + KEEPALIVE_TIME
+
+def op25_terminal(input_q, output_q, terminal_type):
+ if terminal_type == 'curses':
+ return curses_terminal(input_q, output_q)
+ elif terminal_type.startswith('zmq:'):
+ return zeromq_terminal(input_q, output_q, terminal_type.replace('zmq:', ''))
+ elif terminal_type[0].isdigit():
+ port = int(terminal_type)
+ return udp_terminal(input_q, output_q, port)
+ elif terminal_type.startswith('http:'):
+ return http_terminal(input_q, output_q, terminal_type.replace('http:', ''))
+ else:
+ sys.stderr.write('warning: unsupported terminal type: %s\n' % terminal_type)
+ return None
+
+class terminal_client(object):
+ def __init__(self):
+ self.input_q = gr.msg_queue(10)
+ self.keep_running = True
+ self.terminal = None
+
+ ip_addr = sys.argv[1]
+ port = int(sys.argv[2])
+
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.connect((ip_addr, port))
+ self.sock.settimeout(0.1)
+
+ self.terminal = curses_terminal(self.input_q, None, sock=self.sock)
+
+ def run(self):
+ while self.keep_running:
+ try:
+ js, addr = self.sock.recvfrom(2048)
+ msg = gr.message().make_from_string(js, -4, 0, 0)
+ self.input_q.insert_tail(msg)
+ except socket.timeout:
+ pass
+ except:
+ raise
+ if not self.terminal.keep_running:
+ self.keep_running = False
+
+if __name__ == '__main__':
+ terminal = None
+ try:
+ terminal = terminal_client()
+ terminal.run()
+ except:
+ sys.stderr.write('terminal: exception occurred\n')
+ sys.stderr.write('terminal: exception:\n%s\n' % traceback.format_exc())
+ finally:
+ if terminal is not None and terminal.terminal is not None:
+ terminal.terminal.end_terminal()
diff --git a/op25/gr-op25_repeater/apps/trunk.tsv b/op25/gr-op25_repeater/apps/trunk.tsv
index 2bcc560..8305356 100644
--- a/op25/gr-op25_repeater/apps/trunk.tsv
+++ b/op25/gr-op25_repeater/apps/trunk.tsv
@@ -3,5 +3,6 @@
"Cortland" "454.05" "0" "0x4e1" "CQPSK"
"Onondaga" "460.5" "0" "0x2a0" "CQPSK" "onondaga.tsv"
"Cayuga" "460.4125" "0" "0x2a8" "CQPSK" "onondaga.tsv"
-"Ontario" "769.55625,769.85625,770.10625" "0" "0x47f" "CQPSK" "ontario.tsv"
+"Ontario" "769.28125,769.55625,769.85625,770.10625" "0" "0x47f" "CQPSK" "ontario.tsv"
+"460.375" "460.375" "0" "0x2a4" "CQPSK" "onondaga.tsv"
"NYSEG" "152.0225" "0" "0x260" "C4FM" "nyseg.tsv"
diff --git a/op25/gr-op25_repeater/apps/trunking.py b/op25/gr-op25_repeater/apps/trunking.py
index aaf28b7..7aa4019 100644
--- a/op25/gr-op25_repeater/apps/trunking.py
+++ b/op25/gr-op25_repeater/apps/trunking.py
@@ -1,5 +1,6 @@
+#! /usr/bin/env python
-# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Max H. Parke KA1RBI
#
# This file is part of OP25
#
@@ -20,11 +21,16 @@
#
import sys
+import os
import time
import collections
import json
sys.path.append('tdma')
import lfsr
+from tsvfile import make_config, load_tsv, id_registry, read_tags_file
+from create_image import create_image
+
+FILTERED_CC_EVENT = 'mot_grg_add_cmd grp_v_ch_grant_updt grp_v_ch_grant_updt_exp'.split()
def crc16(dat,len): # slow version
poly = (1<<12) + (1<<5) + (1<<0)
@@ -39,14 +45,18 @@ def crc16(dat,len): # slow version
crc = crc ^ 0xffff
return crc
-def get_frequency(f): # return frequency in Hz
- if f.find('.') == -1: # assume in Hz
- return int(f)
- else: # assume in MHz due to '.'
- return int(float(f) * 1000000)
+def get_ordinals(s):
+ t = 0
+ if type(s) is not str and isinstance(s, bytes):
+ for c in s:
+ t = (t << 8) + c
+ else:
+ for c in s:
+ t = (t << 8) + ord(c)
+ return t
class trunked_system (object):
- def __init__(self, debug=0, config=None):
+ def __init__(self, debug=0, config=None, send_event=None, nac=None):
self.debug = debug
self.freq_table = {}
self.stats = {}
@@ -55,6 +65,7 @@ class trunked_system (object):
self.tsbk_cache = {}
self.secondary = {}
self.adjacent = {}
+ self.adjacent_data = {}
self.rfss_syid = 0
self.rfss_rfid = 0
self.rfss_stid = 0
@@ -66,23 +77,34 @@ class trunked_system (object):
self.voice_frequencies = {}
self.blacklist = {}
self.whitelist = None
- self.tgid_map = {}
+ self.tgid_map = None
+ self.unit_id_map = None
self.offset = 0
self.sysname = 0
+ self.tgid_tags_tsv = ""
+ self.unit_id_tags_tsv = ""
self.trunk_cc = 0
+ self.last_trunk_cc = 0
self.cc_list = []
self.cc_list_index = 0
self.CC_HUNT_TIME = 5.0
self.center_frequency = 0
self.last_tsbk = 0
self.cc_timeouts = 0
+ self.next_hunt_cc = time.time() + 8.0
+ self.last_voice_time = 0.0
self.talkgroups = {}
+ self.frequency_table = {}
+ self.CALL_TIMEOUT = 0.7 # call expiration time (sec.)
+ self.CHECK_INTERVAL = 0.1 # freq tracking check interval
+ self.next_frequency_tracking_expire = 0
if config:
self.blacklist = config['blacklist']
self.whitelist = config['whitelist']
self.tgid_map = config['tgid_map']
+ self.unit_id_map = config['unit_id_map']
self.offset = config['offset']
self.sysname = config['sysname']
self.trunk_cc = config['cclist'][0] # TODO: scan thru list
@@ -90,25 +112,52 @@ class trunked_system (object):
self.center_frequency = config['center_frequency']
self.modulation = config['modulation']
- def to_json(self):
+ self.current_srcaddr = 0
+ self.current_grpaddr = 0 # from P25 LCW
+ self.current_alg = ""
+ self.current_algid = 128
+ self.current_keyid = 0
+ self.send_event = send_event
+ self.harris_sgs = {}
+ self.nac = nac
+
+ def to_dict(self):
d = {}
d['syid'] = self.rfss_syid
+ d['sysname'] = self.sysname
d['rfid'] = self.rfss_rfid
d['stid'] = self.rfss_stid
d['sysid'] = self.ns_syid
d['rxchan'] = self.rfss_chan
d['txchan'] = self.rfss_txchan
d['wacn'] = self.ns_wacn
- d['secondary'] = self.secondary.keys()
+ d['secondary'] = [k for k in self.secondary.keys()]
d['tsbks'] = self.stats['tsbks']
d['frequencies'] = {}
+ d['frequency_data'] = {}
d['last_tsbk'] = self.last_tsbk
+ d['srcaddr'] = self.current_srcaddr
+ d['grpaddr'] = self.current_grpaddr
+ d['algid'] = self.current_algid
+ d['alg'] = self.current_alg
+ d['keyid'] = self.current_keyid
t = time.time()
for f in self.voice_frequencies.keys():
tgs = '%s %s' % (self.voice_frequencies[f]['tgid'][0], self.voice_frequencies[f]['tgid'][1])
d['frequencies'][f] = 'voice frequency %f tgid(s) %s %4.1fs ago count %d' % (f / 1000000.0, tgs, t - self.voice_frequencies[f]['time'], self.voice_frequencies[f]['counter'])
- return json.dumps(d)
+ d['frequency_data'][f] = {'tgids': self.voice_frequencies[f]['tgid'], 'last_activity': '%7.1f' % (t - self.voice_frequencies[f]['time']), 'counter': self.voice_frequencies[f]['counter']}
+ for s in 'srcaddr tg_tag tg_color srcaddr_tag srcaddr_color'.split():
+ d['frequency_data'][f][s] = self.voice_frequencies[f][s]
+ d['adjacent_data'] = self.adjacent_data
+ d['talkgroup_data'] = self.talkgroups
+ self.frequency_tracking_expire(always=True)
+ d['frequency_tracking'] = self.frequency_table
+ d['harris_supergroups'] = self.harris_sgs
+ return d
+
+ def to_json(self):
+ return json.dumps(self.to_dict())
def to_string(self):
s = []
@@ -132,6 +181,24 @@ class trunked_system (object):
s.append('adjacent %f: %s' % (float(f) / 1000000.0, self.adjacent[f]))
return '\n'.join(s)
+ def post_event(self, d):
+ if self.send_event is None:
+ return
+ if d['cc_event'] in FILTERED_CC_EVENT:
+ return
+ d['json_type'] = 'cc_event'
+ d['sysid'] = self.rfss_syid if self.rfss_syid else 0
+ d['sysname'] = self.sysname
+ d['time'] = time.time()
+ d['nac'] = self.nac
+ self.send_event(d)
+
+ def mk_tg_dict(self, tgid):
+ return {'tg_id': tgid, 'tag': self.get_tag(tgid), 'priority': self.get_prio(tgid), 'color': self.get_tag_color(tgid)}
+
+ def mk_src_dict(self, srcaddr):
+ return {'unit_id': srcaddr, 'tag': self.get_unit_id_tag(srcaddr), 'color': self.get_unit_id_color(srcaddr)}
+
def get_tdma_slot(self, id):
table = (id >> 12) & 0xf
channel = id & 0xfff
@@ -142,14 +209,19 @@ class trunked_system (object):
return channel & 1
# return frequency in Hz
- def channel_id_to_frequency(self, id):
+ def channel_id_to_frequency(self, id, uplink=False):
table = (id >> 12) & 0xf
channel = id & 0xfff
if table not in self.freq_table:
return None
if 'tdma' not in self.freq_table[table]:
- return self.freq_table[table]['frequency'] + self.freq_table[table]['step'] * channel
- return self.freq_table[table]['frequency'] + self.freq_table[table]['step'] * int(channel / self.freq_table[table]['tdma'])
+ f = self.freq_table[table]['frequency'] + self.freq_table[table]['step'] * channel
+ else:
+ f = self.freq_table[table]['frequency'] + self.freq_table[table]['step'] * int(channel / self.freq_table[table]['tdma'])
+ uplink_f = f + self.freq_table[table]['offset']
+ if uplink:
+ f = uplink_f
+ return f
def channel_id_to_string(self, id):
f = self.channel_id_to_frequency(id)
@@ -157,35 +229,185 @@ class trunked_system (object):
return "ID-0x%x" % (id)
return "%f" % (f / 1000000.0)
+ def get_unit_id_color(self, unit_id):
+ if not unit_id:
+ return 0
+ elif self.unit_id_map is None:
+ return 0
+ return self.unit_id_map.get_color(unit_id)
+
+ def get_unit_id_tag(self, unit_id):
+ if not unit_id:
+ return ""
+ elif self.unit_id_map is None:
+ return "Unit %d" % unit_id
+ return self.unit_id_map.get_tag(unit_id)
+
def get_tag(self, tgid):
if not tgid:
return ""
- if tgid not in self.tgid_map:
- return "Talkgroup ID %d [0x%x]" % (tgid, tgid)
- return self.tgid_map[tgid]
+ elif self.tgid_map is None:
+ return "Talkgroup %d" % tgid
+ return self.tgid_map.get_tag(tgid)
+
+ def get_tag_color(self, tgid):
+ if not tgid:
+ return 0
+ elif self.tgid_map is None:
+ return 0
+ return self.tgid_map.get_color(tgid) % 100
+
+ # the third col in the tsv file performs two separate roles
+ # low-order 2 decimal digits are taken as the tag color code
+ # remaining upper digits are priority - this is incompatibile
+ # with previous tsv files (if priorities are in use).
+ def get_prio(self, tgid):
+ if not tgid:
+ return 0
+ elif self.tgid_map is None:
+ return 0
+ return int(self.tgid_map.get_color(tgid) // 100)
+
+ def end_call(self, call, code):
+ d = {'cc_event': 'end_call', 'code': code, 'srcaddr': call['srcaddr'], 'tgid': call['tgid'], 'duration': call['end_time'] - call['start_time'], 'count': call['count'], 'opcode': -1 }
+ self.post_event(d)
+ return
+
+ def frequency_tracking_expire(self, always=False):
+ current_time = time.time()
+ if current_time < self.next_frequency_tracking_expire and not always:
+ return
+ self.next_frequency_tracking_expire = current_time + self.CHECK_INTERVAL
+ for f in self.frequency_table.keys():
+ freq = self.frequency_table[f]
+ for i in range(len(freq['calls'])):
+ call = freq['calls'][i]
+ if call is not None and call['end_time'] == 0 and call['last_active'] + self.CALL_TIMEOUT < current_time:
+ call['end_time'] = current_time
+ self.end_call(call, 1)
+
+ def frequency_tracking(self, frequency, tgid, tdma_slot, srcaddr, protected):
+ current_time = time.time()
+ is_tdma = tdma_slot is not None
+ slot = tdma_slot if is_tdma else 0
+ if frequency not in self.frequency_table.keys():
+ self.frequency_table[frequency] = {'counter':0,
+ 'calls': [None,None],
+ 'tgids': [None,None],
+ 'last_active': current_time}
+ self.frequency_table[frequency]['tdma'] = is_tdma
+ call = {'srcaddr': self.mk_src_dict(srcaddr),
+ 'protected': protected,
+ 'tgid': self.mk_tg_dict(tgid),
+ 'count': 0,
+ 'start_time': current_time,
+ 'last_active': current_time,
+ 'end_time': 0}
+
+ self.frequency_table[frequency]['tgids'][slot] = tgid
+ self.frequency_table[frequency]['calls'][slot] = call
+ return
+
+ self.frequency_table[frequency]['counter'] += 1
+ self.frequency_table[frequency]['last_active'] = current_time
+ found = 0
+ for f in self.frequency_table.keys():
+ freq = self.frequency_table[f]
+ for i in range(len(freq['tgids'])):
+ tg = freq['tgids'][i]
+ call = freq['calls'][i]
+ if tg is None or call is None or tg != tgid:
+ continue
+ # general housekeeping: expire calls
+ if call['end_time'] == 0 and call['last_active'] + self.CALL_TIMEOUT < current_time:
+ call['end_time'] = current_time
+ self.end_call(call, 2)
+ if f == frequency and freq['tdma'] == is_tdma and i == slot :
+ found = 1
+ call['last_active'] = current_time
+ call['end_time'] = 0
+ call['count'] += 1
+ if srcaddr is not None:
+ call['srcaddr'] = self.mk_src_dict(srcaddr)
+ if protected is not None:
+ call['protected'] = protected
+ else: # found other entry with matching tgid but freq and/or tdma is wrong
+ if call['end_time'] == 0:
+ call['end_time'] = current_time
+ self.end_call(call, 3)
+ if found:
+ return
+
+ call = {'srcaddr': self.mk_src_dict(srcaddr),
+ 'protected': protected,
+ 'tgid': self.mk_tg_dict(tgid),
+ 'count': 0,
+ 'start_time': current_time,
+ 'last_active': current_time,
+ 'end_time': 0}
+ self.frequency_table[frequency]['tdma'] = is_tdma
+ self.frequency_table[frequency]['tgids'][slot] = tgid
+ self.frequency_table[frequency]['calls'][slot] = call
+ if not is_tdma:
+ self.frequency_table[frequency]['tgids'][1] = None
+ call = self.frequency_table[frequency]['calls'][1]
+ if call and call['end_time'] == 0:
+ call['end_time'] = current_time
+ self.end_call(call, 4)
+ self.frequency_table[frequency]['calls'][1] = None
+
+ def update_talkgroup(self, frequency, tgid, tdma_slot, srcaddr, uplink):
+ if self.debug >= 5:
+ sys.stderr.write('%f set tgid=%s, srcaddr=%s\n' % (time.time(), tgid, srcaddr))
- def update_talkgroup(self, frequency, tgid, tdma_slot):
if tgid not in self.talkgroups:
self.talkgroups[tgid] = {'counter':0}
+ if self.debug >= 5:
+ sys.stderr.write('%f new tgid: %s %s prio %d\n' % (time.time(), tgid, self.get_tag(tgid), self.get_prio(tgid)))
self.talkgroups[tgid]['time'] = time.time()
self.talkgroups[tgid]['frequency'] = frequency
self.talkgroups[tgid]['tdma_slot'] = tdma_slot
+ self.talkgroups[tgid]['prio'] = self.get_prio(tgid)
+ self.talkgroups[tgid]['tag_color'] = self.get_tag_color(tgid)
+ self.talkgroups[tgid]['uplink'] = uplink
+
+ if srcaddr is None or not srcaddr:
+ self.talkgroups[tgid]['srcaddr'] = 0
+ self.talkgroups[tgid]['srcaddr_tag'] = ""
+ self.talkgroups[tgid]['srcaddr_color'] = 0
+ else:
+ self.talkgroups[tgid]['srcaddr'] = srcaddr
+ self.talkgroups[tgid]['srcaddr_tag'] = self.get_unit_id_tag(srcaddr)
+ self.talkgroups[tgid]['srcaddr_color'] = self.get_unit_id_color(srcaddr)
- def update_voice_frequency(self, frequency, tgid=None, tdma_slot=None):
+ def update_voice_frequency(self, frequency, tgid=None, tdma_slot=None, srcaddr=None, protected=None, uplink=None):
if not frequency: # e.g., channel identifier not yet known
return
- self.update_talkgroup(frequency, tgid, tdma_slot)
+ self.frequency_tracking(frequency, tgid, tdma_slot, srcaddr, protected)
+ self.update_talkgroup(frequency, tgid, tdma_slot, srcaddr, uplink)
if frequency not in self.voice_frequencies:
self.voice_frequencies[frequency] = {'counter':0}
sorted_freqs = collections.OrderedDict(sorted(self.voice_frequencies.items()))
self.voice_frequencies = sorted_freqs
+ if self.debug >= 5:
+ sys.stderr.write('%f new freq: %f\n' % (time.time(), frequency/1000000.0))
+
if tdma_slot is None:
tdma_slot = 0
- if 'tgid' not in self.voice_frequencies[frequency]:
- self.voice_frequencies[frequency]['tgid'] = [None, None]
+
+ for s in 'tgid srcaddr tg_tag tg_color srcaddr_tag srcaddr_color'.split():
+ if s not in self.voice_frequencies[frequency].keys():
+ self.voice_frequencies[frequency][s] = [None, None]
+
self.voice_frequencies[frequency]['tgid'][tdma_slot] = tgid
self.voice_frequencies[frequency]['counter'] += 1
self.voice_frequencies[frequency]['time'] = time.time()
+ self.voice_frequencies[frequency]['tg_tag'][tdma_slot] = self.get_tag(tgid)
+ self.voice_frequencies[frequency]['tg_color'][tdma_slot] = self.get_tag_color(tgid)
+ if srcaddr is not None:
+ self.voice_frequencies[frequency]['srcaddr'][tdma_slot] = srcaddr
+ self.voice_frequencies[frequency]['srcaddr_tag'][tdma_slot] = self.get_unit_id_tag(srcaddr)
+ self.voice_frequencies[frequency]['srcaddr_color'][tdma_slot] = self.get_unit_id_color(srcaddr)
def get_updated_talkgroups(self, start_time):
return [tgid for tgid in self.talkgroups if (
@@ -200,11 +422,16 @@ class trunked_system (object):
for tg in expired_tgs:
self.blacklist.pop(tg)
- def find_talkgroup(self, start_time, tgid=None):
+ def find_talkgroup(self, start_time, tgid=None, hold=False):
+ tgt_tgid = None
self.blacklist_update(start_time)
- if tgid is not None and tgid in self.talkgroups and self.talkgroups[tgid]['time'] >= start_time:
- return self.talkgroups[tgid]['frequency'], tgid, self.talkgroups[tgid]['tdma_slot']
+
+ if tgid is not None and tgid in self.talkgroups:
+ tgt_tgid = tgid
+
for active_tgid in self.talkgroups:
+ if hold:
+ break
if self.talkgroups[active_tgid]['time'] < start_time:
continue
if active_tgid in self.blacklist:
@@ -213,31 +440,50 @@ class trunked_system (object):
continue
if self.talkgroups[active_tgid]['tdma_slot'] is not None and (self.ns_syid < 0 or self.ns_wacn < 0):
continue
- if tgid is None:
- return self.talkgroups[active_tgid]['frequency'], active_tgid, self.talkgroups[active_tgid]['tdma_slot']
- return None, None, None
+ if tgt_tgid is None:
+ tgt_tgid = active_tgid
+ elif self.talkgroups[active_tgid]['prio'] < self.talkgroups[tgt_tgid]['prio']:
+ tgt_tgid = active_tgid
+
+ if tgt_tgid is not None and self.talkgroups[tgt_tgid]['time'] >= start_time:
+ return self.talkgroups[tgt_tgid]['frequency'], tgt_tgid, self.talkgroups[tgt_tgid]['tdma_slot'], self.talkgroups[tgt_tgid]['srcaddr'], self.talkgroups[tgt_tgid]['uplink']
+ return None, None, None, None, None
+
+ def dump_tgids(self):
+ sys.stderr.write("Known tgids: { ")
+ for tgid in sorted(self.talkgroups.keys()):
+ sys.stderr.write("%d " % tgid);
+ sys.stderr.write("}\n")
def add_blacklist(self, tgid, end_time=None):
if not tgid:
return
self.blacklist[tgid] = end_time
- def decode_mbt_data(self, opcode, header, mbt_data):
+ def decode_mbt_data(self, opcode, src, header, mbt_data):
self.cc_timeouts = 0
self.last_tsbk = time.time()
updated = 0
if self.debug > 10:
- print "decode_mbt_data: %x %x" %(opcode, mbt_data)
+ sys.stderr.write('decode_mbt_data: %x %x\n' %(opcode, mbt_data))
if opcode == 0x0: # grp voice channel grant
+ mfrid = (header >> 72) & 0xff
+ srcaddr = (header >> 48) & 0xffffff
+ opts = (header >> 24) & 0xff
ch1 = (mbt_data >> 64) & 0xffff
ch2 = (mbt_data >> 48) & 0xffff
ga = (mbt_data >> 32) & 0xffff
f = self.channel_id_to_frequency(ch1)
- self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch1))
+ uplink = self.channel_id_to_frequency(ch2)
+ if self.debug > 0 and src != srcaddr:
+ sys.stderr.write('decode_mbt_data: grp_v_ch_grant: src %d does not match srcaddr %d\n' % (src, srcaddr))
+ d = {'cc_event': 'grp_v_ch_grant_mbt', 'mfrid': mfrid, 'options': opts, 'frequency': f, 'group': self.mk_tg_dict(ga), 'srcaddr': self.mk_src_dict(srcaddr), 'opcode': opcode, 'tdma_slot': self.get_tdma_slot(ch1) }
+ self.post_event(d)
+ self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch1), srcaddr=srcaddr, protected=opts&64 == 64, uplink=uplink)
if f:
updated += 1
if self.debug > 10:
- print "mbt00 voice grant ch1 %x ch2 %x addr 0x%x" %(ch1, ch2, ga)
+ sys.stderr.write('mbt00 voice grant ch1 %x ch2 %x addr 0x%x\n' %(ch1, ch2, ga))
elif opcode == 0x3c: # adjacent status
syid = (header >> 48) & 0xfff
rfid = (header >> 24) & 0xff
@@ -248,8 +494,9 @@ class trunked_system (object):
f2 = self.channel_id_to_frequency(ch2)
if f1 and f2:
self.adjacent[f1] = 'rfid: %d stid:%d uplink:%f' % (rfid, stid, f2 / 1000000.0)
+ self.adjacent_data[f1] = {'rfid': rfid, 'stid':stid, 'uplink': f2, 'table': None, 'sysid': syid}
if self.debug > 10:
- print "mbt3c adjacent sys %x rfid %x stid %x ch1 %x ch2 %x f1 %s f2 %s" %(syid, rfid, stid, ch1, ch2, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2))
+ sys.stderr.write('mbt3c adjacent sys %x rfid %x stid %x ch1 %x ch2 %x f1 %s f2 %s\n' % (syid, rfid, stid, ch1, ch2, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2)))
elif opcode == 0x3b: # network status
syid = (header >> 48) & 0xfff
wacn = (mbt_data >> 76) & 0xfffff
@@ -262,7 +509,7 @@ class trunked_system (object):
self.ns_wacn = wacn
self.ns_chan = f1
if self.debug > 10:
- print "mbt3b net stat sys %x wacn %x ch1 %s ch2 %s" %(syid, wacn, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2))
+ sys.stderr.write('mbt3b net stat sys %x wacn %x ch1 %s ch2 %s\n' %(syid, wacn, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2)))
elif opcode == 0x3a: # rfss status
syid = (header >> 48) & 0xfff
rfid = (mbt_data >> 88) & 0xff
@@ -278,9 +525,305 @@ class trunked_system (object):
self.rfss_chan = f1
self.rfss_txchan = f2
if self.debug > 10:
- print "mbt3a rfss stat sys %x rfid %x stid %x ch1 %s ch2 %s" %(syid, rfid, stid, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2))
- #else:
- # print "mbt other %x" % opcode
+ sys.stderr.write('mbt3a rfss stat sys %x rfid %x stid %x ch1 %s ch2 %s\n' %(syid, rfid, stid, self.channel_id_to_string(ch1), self.channel_id_to_string(ch2)))
+ elif opcode == 0x31: # AUTH_DMD
+ mfrid = (header >> 72) & 0xff
+ target_address = (header >> 48) & 0xffffff
+ wacn_p1 = (header >> 16) & 0xffff
+ msg_wacn = (wacn_p1 << 4) | (mbt_data >> 188) & 0xf
+ msg_sysid = (mbt_data >> 176) & 0xfff
+ target_id = (mbt_data >> 152) & 0xffffff
+ rs = (mbt_data >> 72) & 0x3ff
+ rand1 = (mbt_data >> 32) & 0x1f
+ d = {'cc_event': 'auth_dmd', 'mfrid': mfrid, 'target_address': self.mk_src_dict(target_address), 'target_id': self.mk_src_dict(target_id), 'opcode': opcode, 'msg_sysid': msg_sysid, 'msg_wacn': msg_wacn, 'rs': rs, 'rand1': rand1 }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('mbt31 auth_dmd target %d wacn 0x%x sysid 0x%x target id %d rs 0x%x rand1 0x%x\n' % (target_address, msg_wacn, msg_sysid, target_id, rs, rand1))
+ else:
+ sys.stderr.write('decode_mbt_data(): received unsupported mbt opcode %x\n' % opcode)
+ return updated
+
+ def decode_tdma_blk(self, blk):
+ self.stats['tsbks'] += 1
+ msg0 = get_ordinals(blk[:1])
+ op = (msg0 >> 6) & 3
+ moc = msg0 & 0x3f
+ if self.debug > 1:
+ sys.stderr.write('tdma_cc: decode_blk: op %x moc %x len %d msg0 0x%x\n' % (op, moc, len(blk), msg0))
+ if op == 0 and moc == 0: # null msg
+ if self.debug > 10:
+ sys.stderr.write('tdma_cc: null block\n')
+ return -1;
+ if op == 0 and moc == 8: # null msg zero bias
+ if self.debug > 10:
+ sys.stderr.write('tdma_cc: null block zero bias\n')
+ return -1;
+
+ if op == 1 and moc == 0x38: # system service broadcast
+ if self.debug > 10:
+ sys.stderr.write('tdma_cc: system service broadcast\n')
+ msglen = 9
+ elif op == 3 and moc == 0x16: # SNDCP data ch
+ if self.debug > 10:
+ sys.stderr.write('tdma_cc: SNDCP data channel announce\n')
+ msglen = 9
+ elif op == 0 and moc == 1: # group voice channel user
+ msglen = 7
+ msg = get_ordinals(blk[:msglen])
+ options = (msg >> 40) & 0xff
+ ga1 = (msg >> 24) & 0xffff
+ sa1 = (msg ) & 0xffffff
+ if self.debug > 1:
+ sys.stderr.write('decode_blk: group voice channel user opts %x ga %x sa %x\n' % (options, ga1, sa1))
+ elif op == 0 and moc == 0x30: # power control sq
+ msglen = 5
+ if self.debug > 1:
+ sys.stderr.write('decode_blk: power control sq\n')
+ elif op == 1 and moc == 0x30: # sync broadcast
+ msglen = 9
+ msg = get_ordinals(blk[:msglen])
+ year = (msg >> 33) & 0x7f
+ month = (msg >> 29) & 0xf
+ day = (msg >> 24) & 0x1f
+ if self.debug > 1:
+ sys.stderr.write('decode_blk: synchronization broadcast %d %d %d\n' % (year, month, day))
+ elif op == 1 and moc == 2: # group voice channel grant update
+ msglen = 9
+ msg = get_ordinals(blk[:msglen])
+ ch1 = (msg >> 48) & 0xffff
+ ga1 = (msg >> 32) & 0xffff
+ ch2 = (msg >> 16) & 0xffff
+ ga2 = (msg ) & 0xffff
+ f1 = self.channel_id_to_frequency(ch1)
+ f2 = self.channel_id_to_frequency(ch2)
+ uplink1 = self.channel_id_to_frequency(ch1, uplink=True)
+ uplink2 = self.channel_id_to_frequency(ch2, uplink=True)
+ if self.debug > 1:
+ sys.stderr.write('decode_blk: group voice channel grant update ga1 %d ch1 %s ga2 %d ch2 %s\n' % (ga1, f1, ga2, f2))
+ opcode = 2 # (p25p1 opcode)
+ d = {'cc_event': 'grp_v_ch_grant_updt', 'mfrid': 0, 'frequency1': f1, 'group1': self.mk_tg_dict(ga1), 'opcode': opcode, 'tdma_slot': self.get_tdma_slot(ch1) }
+ self.update_voice_frequency(f1, tgid=ga1, tdma_slot=self.get_tdma_slot(ch1), uplink=uplink1)
+ if f1 != f2:
+ self.update_voice_frequency(f2, tgid=ga2, tdma_slot=self.get_tdma_slot(ch2), uplink=uplink2)
+ d['frequency2'] = f2
+ d['group2'] = self.mk_tg_dict(ga2)
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('phase 2 tsbk02 grant update: chan %s %d %s %d\n' %(self.channel_id_to_string(ch1), ga1, self.channel_id_to_string(ch2), ga2))
+ elif op == 1 and moc == 0x3c: # adjacent
+ msglen = 9
+ msg = get_ordinals(blk[:msglen])
+ syid = (msg >> 40) & 0xfff
+ rfid = (msg >> 32) & 0xff
+ stid = (msg >> 24) & 0xff
+ ch1 = (msg >> 8) & 0xffff
+ table = (ch1 >> 12) & 0xf
+ cls = msg & 0xff
+ f1 = self.channel_id_to_frequency(ch1)
+ if f1 and table in self.freq_table:
+ self.adjacent[f1] = 'rfid: %d stid:%d uplink:%f tbl:%d sysid:0x%x' % (rfid, stid, (f1 + self.freq_table[table]['offset']) / 1000000.0, table, syid)
+ self.adjacent_data[f1] = {'rfid': rfid, 'stid':stid, 'uplink': f1 + self.freq_table[table]['offset'], 'table': table, 'sysid':syid}
+ if self.debug > 10:
+ sys.stderr.write('tsbk3c adjacent: rfid %x stid %d ch1 %x(%s)\n' %(rfid, stid, ch1, self.channel_id_to_string(ch1)))
+ if table in self.freq_table:
+ sys.stderr.write('tsbk3c : %s %s\n' % (self.freq_table[table]['frequency'] , self.freq_table[table]['step'] ))
+ elif op == 1 and moc == 0x33: # iden up tdma
+ msglen = 9
+ opcode = 0x33
+ msg = get_ordinals(blk[:msglen])
+ iden = (msg >> 60) & 0xf
+ channel_type = (msg >> 56) & 0xf
+ toff0 = (msg >> 42) & 0x3fff
+ toff_sign = (toff0 >> 13) & 1
+ toff = toff0 & 0x1fff
+ if toff_sign == 0:
+ toff = 0 - toff
+ spac = (msg >> 32) & 0x3ff
+ f1 = (msg) & 0xffffffff
+ slots_per_carrier = [1,1,1,2,4,2]
+ self.freq_table[iden] = {}
+ self.freq_table[iden]['offset'] = toff * spac * 125
+ self.freq_table[iden]['step'] = spac * 125
+ self.freq_table[iden]['frequency'] = f1 * 5
+ if slots_per_carrier[channel_type] > 1:
+ self.freq_table[iden]['tdma'] = slots_per_carrier[channel_type]
+ d = {'cc_event': 'iden_up_tdma', 'iden': iden, 'offset': self.freq_table[iden]['offset'], 'step': self.freq_table[iden]['step'], 'freq': self.freq_table[iden]['frequency'], 'slots': slots_per_carrier[channel_type], 'opcode': opcode }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk33 iden up tdma id %d f %d offset %d spacing %d slots/carrier %d\n' % (iden, self.freq_table[iden]['frequency'], self.freq_table[iden]['offset'], self.freq_table[iden]['step'], self.freq_table[iden]['tdma']))
+ elif op == 1 and moc == 0x3b: # network status
+ msglen = 11
+ opcode = 0x3b
+ msg = get_ordinals(blk[:msglen])
+ wacn = (msg >> 52) & 0xfffff
+ syid = (msg >> 40) & 0xfff
+ ch1 = (msg >> 24) & 0xffff
+ color = (msg ) & 0xfff
+ sys.stderr.write('tsbk3b net stat: color: 0x%x\n' % color)
+ f1 = self.channel_id_to_frequency(ch1)
+ if f1:
+ self.ns_syid = syid
+ self.ns_wacn = wacn
+ self.ns_chan = f1
+ if self.debug > 10:
+ sys.stderr.write('tsbk3b net stat: wacn %x syid %x ch1 %x(%s)\n' %(wacn, syid, ch1, self.channel_id_to_string(ch1)))
+ elif op == 1 and moc == 0x3a: # rfss status
+ msglen = 9
+ opcode = 0x3a
+ msg = get_ordinals(blk[:msglen])
+ syid = (msg >> 40) & 0xfff
+ rfid = (msg >> 32) & 0xff
+ stid = (msg >> 24) & 0xff
+ chan = (msg >> 8) & 0xffff
+ f1 = self.channel_id_to_frequency(chan)
+ if f1:
+ self.rfss_syid = syid
+ self.rfss_rfid = rfid
+ self.rfss_stid = stid
+ self.rfss_chan = f1
+ self.rfss_txchan = f1 + self.freq_table[chan >> 12]['offset']
+ if self.debug > 10:
+ sys.stderr.write('tsbk3a rfss status: syid: %x rfid %x stid %d ch1 %x(%s)\n' %(syid, rfid, stid, chan, self.channel_id_to_string(chan)))
+ elif op == 1 and moc == 0x39: # secondary cc
+ msglen = 9
+ opcode = 0x39
+ msg = get_ordinals(blk[:msglen])
+ rfid = (msg >> 56) & 0xff
+ stid = (msg >> 48) & 0xff
+ ch1 = (msg >> 32) & 0xffff
+ ch2 = (msg >> 8) & 0xffff
+ f1 = self.channel_id_to_frequency(ch1)
+ f2 = self.channel_id_to_frequency(ch2)
+ if f1 and f2:
+ self.secondary[ f1 ] = 1
+ self.secondary[ f2 ] = 1
+ sorted_freqs = collections.OrderedDict(sorted(self.secondary.items()))
+ self.secondary = sorted_freqs
+ if self.debug > 10:
+ sys.stderr.write('tsbk39 secondary cc: rfid %x stid %d ch1 %x(%s) ch2 %x(%s)\n' %(rfid, stid, ch1, self.channel_id_to_string(ch1), ch2, self.channel_id_to_string(ch2)))
+ elif op == 1 and moc == 0x3d: # iden_up
+ msglen = 9
+ opcode = 0x3d
+ msg = get_ordinals(blk[:msglen])
+ iden = (msg >> 60) & 0xf
+ bw = (msg >> 51) & 0x1ff
+ toff0 = (msg >> 42) & 0x1ff
+ spac = (msg >> 32) & 0x3ff
+ freq = msg & 0xffffffff
+ toff_sign = (toff0 >> 8) & 1
+ toff = toff0 & 0xff
+ if toff_sign == 0:
+ toff = 0 - toff
+ txt = ["mob xmit < recv", "mob xmit > recv"]
+ self.freq_table[iden] = {}
+ self.freq_table[iden]['offset'] = toff * 250000
+ self.freq_table[iden]['step'] = spac * 125
+ self.freq_table[iden]['frequency'] = freq * 5
+ d = {'cc_event': 'iden_up', 'iden': iden, 'offset': self.freq_table[iden]['offset'], 'step': self.freq_table[iden]['step'], 'freq': self.freq_table[iden]['frequency'], 'opcode': opcode }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk3d iden id %d toff %f spac %f freq %f\n' % (iden, toff * 0.25, spac * 0.125, freq * 0.000005))
+ else:
+ msglen = -1
+ if self.debug > 0:
+ sys.stderr.write ('tdma_cc unknown request: %x %x %x\n' % (op, moc, get_ordinals(blk)))
+ return msglen
+
+ def decode_tdma_cc(self, blk):
+ while True:
+ rc = self.decode_tdma_blk(blk)
+ if rc < 1:
+ break
+ if rc >= len(blk):
+ break
+ blk = blk[rc:]
+
+ def decode_tsbk_harris(self, tsbk, opcode, mfrid):
+ HARRIS_SGS_EXPIRES = 5.0 # sec.
+ updated = 0
+ if opcode != 0x30: # GRG_EXENC_CMD
+ sys.stderr.write('decode_tsbk: unsupported opcode %02x mfrid %02x\n' % (opcode, mfrid))
+ return updated
+ grg_options = (tsbk >> 72) & 0xff
+ opt_2way = (grg_options & 0x80) == 0
+ opt_group = (grg_options & 0x40) != 0
+ opt_act = (grg_options & 0x20) != 0
+ opt_ssn = grg_options & 0x1f
+ sg = (tsbk >> 56) & 0xffff
+ keyid = (tsbk >> 40) & 0xffff
+ target = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'grg_exenc_cmd', 'mfrid': mfrid, 'opt_2way': opt_2way, 'opt_group': opt_group, 'opt_act': opt_act, 'opt_ssn': opt_ssn, 'sg': self.mk_tg_dict(sg), 'keyid': keyid}
+ if opt_group: # target is a group
+ algid = (target >> 16) & 0xff
+ target = target & 0xffff
+ d['target_group'] = self.mk_tg_dict(target)
+ else: # target is a subscriber unit id
+ algid = 128
+ d['target_unit'] = self.mk_src_dict(target)
+ d['algid'] = algid
+ if opt_act and opt_group: # only group id type supported
+ sgkey = '%d-%d' % (sg, target)
+ self.harris_sgs[sgkey] = {'supergroup': self.mk_tg_dict(sg), 'target_group': self.mk_tg_dict(target), 'algid': algid, 'keyid': keyid, 'expires': time.time() + HARRIS_SGS_EXPIRES}
+ return updated
+
+ def decode_tsbk_mot(self, tsbk, opcode, mfrid):
+ updated = 0
+ if opcode == 0x00: # MOT_GRG_ADD_CMD
+ sg = (tsbk >> 64) & 0xffff
+ ga1 = (tsbk >> 48) & 0xffff
+ ga2 = (tsbk >> 32) & 0xffff
+ ga3 = (tsbk >> 16) & 0xffff
+ d = {'cc_event': 'mot_grg_add_cmd', 'mfrid': mfrid, 'sg': self.mk_tg_dict(sg), 'ga1': self.mk_tg_dict(ga1), 'ga2': self.mk_tg_dict(ga2), 'ga3': self.mk_tg_dict(ga3), 'opcode': opcode }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('MOT_GRG_ADD_CMD(0x00): sg:%d ga1:%d ga2:%d ga3:%d\n' % (sg, ga1, ga2, ga3))
+ elif opcode == 0x01: #MOT_GRG_DEL_CMD
+ sg = (tsbk >> 64) & 0xffff
+ ga1 = (tsbk >> 48) & 0xffff
+ ga2 = (tsbk >> 32) & 0xffff
+ ga3 = (tsbk >> 16) & 0xffff
+ d = {'cc_event': 'mot_grg_del_cmd', 'mfrid': mfrid, 'sg': self.mk_tg_dict(sg), 'ga1': self.mk_tg_dict(ga1), 'ga2': self.mk_tg_dict(ga2), 'ga3': self.mk_tg_dict(ga3), 'opcode': opcode }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('MOT_GRG_DEL_CMD(0x01): sg:%d ga1:%d ga2:%d ga3:%d\n' % (sg, ga1, ga2, ga3))
+ elif opcode == 0x02: # MOT_GRG_CN_CRANT
+ ch = (tsbk >> 56) & 0xffff
+ sg = (tsbk >> 40) & 0xffff
+ sa = (tsbk >> 16) & 0xffffff
+ f = self.channel_id_to_frequency(ch)
+ uplink = self.channel_id_to_frequency(ch, uplink=True)
+ d = {'cc_event': 'mot_grg_cn_grant', 'mfrid': mfrid, 'frequency': f, 'sg': self.mk_tg_dict(sg), 'sa': self.mk_src_dict(sa), 'opcode': opcode }
+ self.post_event(d)
+ self.update_voice_frequency(f, tgid=sg, tdma_slot=self.get_tdma_slot(ch), srcaddr=sa, uplink=uplink)
+ if f:
+ updated += 1
+ if self.debug > 10:
+ sys.stderr.write('MOT_GRG_CN_GRANT(0x02): freq %s sg:%d sa:%d\n' % (self.channel_id_to_string(ch), sg, sa))
+ elif opcode == 0x03: #MOT_GRG_CN_GRANT_UPDT
+ ch1 = (tsbk >> 64) & 0xffff
+ sg1 = (tsbk >> 48) & 0xffff
+ ch2 = (tsbk >> 32) & 0xffff
+ sg2 = (tsbk >> 16) & 0xffff
+ f1 = self.channel_id_to_frequency(ch1)
+ f2 = self.channel_id_to_frequency(ch2)
+ uplink1 = self.channel_id_to_frequency(ch1, uplink=True)
+ uplink2 = self.channel_id_to_frequency(ch2, uplink=True)
+ d = {'cc_event': 'mot_grg_cn_grant_updt', 'mfrid': mfrid, 'frequency1': f1, 'sg1': self.mk_tg_dict(sg1), 'opcode': opcode }
+ self.update_voice_frequency(f1, tgid=sg1, tdma_slot=self.get_tdma_slot(ch1), uplink=uplink1)
+ if f1 != f2:
+ self.update_voice_frequency(f2, tgid=sg2, tdma_slot=self.get_tdma_slot(ch2), uplink=uplink2)
+ d['sg2'] = self.mk_tg_dict(sg2)
+ d['frequency2'] = f2
+ self.post_event(d)
+ if f1:
+ updated += 1
+ if f2:
+ updated += 1
+ if self.debug > 10:
+ sys.stderr.write('MOT_GRG_CN_GRANT_UPDT(0x03): freq %s sg1:%d freq %s sg2:%d\n' % (self.channel_id_to_string(ch1), sg1, self.channel_id_to_string(ch2), sg2))
+ else:
+ if self.debug > 10:
+ sys.stderr.write('decode_tsbk: unsupported opcode %02x mfrid %02x\n' % (opcode, mfrid))
return updated
def decode_tsbk(self, tsbk):
@@ -288,104 +831,76 @@ class trunked_system (object):
self.last_tsbk = time.time()
self.stats['tsbks'] += 1
updated = 0
- #if crc16(tsbk, 12) != 0:
- # self.stats['crc'] += 1
- # return # crc check failed
tsbk = tsbk << 16 # for missing crc
opcode = (tsbk >> 88) & 0x3f
+ mfrid = (tsbk >> 80) & 0xff # mfrid
if self.debug > 10:
- print "TSBK: 0x%02x 0x%024x" % (opcode, tsbk)
+ sys.stderr.write('TSBK: 0x%02x 0x%024x mfrid %02x\n' % (opcode, tsbk, mfrid))
+
+ if mfrid == 0x90:
+ return self.decode_tsbk_mot(tsbk, opcode, mfrid)
+ elif mfrid == 0xa4:
+ return self.decode_tsbk_harris(tsbk, opcode, mfrid)
+ elif mfrid != 0:
+ sys.stderr.write('unsupported tsbk mfrid: 0x%02x opcode 0x%02x\n' % (mfrid, opcode))
+ return updated
+
if opcode == 0x00: # group voice chan grant
- mfrid = (tsbk >> 80) & 0xff
- if mfrid == 0x90: # MOT_GRG_ADD_CMD
- sg = (tsbk >> 64) & 0xffff
- ga1 = (tsbk >> 48) & 0xffff
- ga2 = (tsbk >> 32) & 0xffff
- ga3 = (tsbk >> 16) & 0xffff
- if self.debug > 10:
- print "MOT_GRG_ADD_CMD(0x00): sg:%d ga1:%d ga2:%d ga3:%d" % (sg, ga1, ga2, ga3)
- else:
- opts = (tsbk >> 72) & 0xff
- ch = (tsbk >> 56) & 0xffff
- ga = (tsbk >> 40) & 0xffff
- sa = (tsbk >> 16) & 0xffffff
- f = self.channel_id_to_frequency(ch)
- self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch))
- if f:
- updated += 1
- if self.debug > 10:
- print "tsbk00 grant freq %s ga %d sa %d" % (self.channel_id_to_string(ch), ga, sa)
- elif opcode == 0x01: # reserved
- mfrid = (tsbk >> 80) & 0xff
- if mfrid == 0x90: #MOT_GRG_DEL_CMD
- sg = (tsbk >> 64) & 0xffff
- ga1 = (tsbk >> 48) & 0xffff
- ga2 = (tsbk >> 32) & 0xffff
- ga3 = (tsbk >> 16) & 0xffff
- if self.debug > 10:
- print "MOT_GRG_DEL_CMD(0x01): sg:%d ga1:%d ga2:%d ga3:%d" % (sg, ga1, ga2, ga3)
+ opts = (tsbk >> 72) & 0xff
+ ch = (tsbk >> 56) & 0xffff
+ ga = (tsbk >> 40) & 0xffff
+ sa = (tsbk >> 16) & 0xffffff
+ f = self.channel_id_to_frequency(ch)
+ uplink = self.channel_id_to_frequency(ch, uplink=True)
+ d = {'cc_event': 'grp_v_ch_grant', 'mfrid': mfrid, 'options': opts, 'frequency': f, 'group': self.mk_tg_dict(ga), 'srcaddr': self.mk_src_dict(sa), 'opcode': opcode, 'tdma_slot': self.get_tdma_slot(ch) }
+ self.post_event(d)
+ self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch), srcaddr=sa, protected=opts&64 == 64, uplink=uplink)
+ if f:
+ updated += 1
+ if self.debug > 10:
+ sys.stderr.write('tsbk00 grant freq %s ga %d sa %d\n' % (self.channel_id_to_string(ch), ga, sa))
elif opcode == 0x02: # group voice chan grant update
- mfrid = (tsbk >> 80) & 0xff
- if mfrid == 0x90:
- ch = (tsbk >> 56) & 0xffff
- sg = (tsbk >> 40) & 0xffff
- sa = (tsbk >> 16) & 0xffffff
- f = self.channel_id_to_frequency(ch)
- self.update_voice_frequency(f, tgid=sg, tdma_slot=self.get_tdma_slot(ch))
- if f:
- updated += 1
- if self.debug > 10:
- print "MOT_GRG_CN_GRANT(0x02): freq %s sg:%d sa:%d" % (self.channel_id_to_string(ch), sg, sa)
- else:
- ch1 = (tsbk >> 64) & 0xffff
- ga1 = (tsbk >> 48) & 0xffff
- ch2 = (tsbk >> 32) & 0xffff
- ga2 = (tsbk >> 16) & 0xffff
- f1 = self.channel_id_to_frequency(ch1)
- f2 = self.channel_id_to_frequency(ch2)
- self.update_voice_frequency(f1, tgid=ga1, tdma_slot=self.get_tdma_slot(ch1))
- if f1 != f2:
- self.update_voice_frequency(f2, tgid=ga2, tdma_slot=self.get_tdma_slot(ch2))
- if f1:
- updated += 1
- if f2:
- updated += 1
- if self.debug > 10:
- print "tsbk02 grant update: chan %s %d %s %d" %(self.channel_id_to_string(ch1), ga1, self.channel_id_to_string(ch2), ga2)
+ ch1 = (tsbk >> 64) & 0xffff
+ ga1 = (tsbk >> 48) & 0xffff
+ ch2 = (tsbk >> 32) & 0xffff
+ ga2 = (tsbk >> 16) & 0xffff
+ f1 = self.channel_id_to_frequency(ch1)
+ f2 = self.channel_id_to_frequency(ch2)
+ uplink1 = self.channel_id_to_frequency(ch1, uplink=True)
+ uplink2 = self.channel_id_to_frequency(ch2, uplink=True)
+ d = {'cc_event': 'grp_v_ch_grant_updt', 'mfrid': mfrid, 'frequency1': f1, 'group1': self.mk_tg_dict(ga1), 'opcode': opcode, 'tdma_slot': self.get_tdma_slot(ch1) }
+ self.update_voice_frequency(f1, tgid=ga1, tdma_slot=self.get_tdma_slot(ch1), uplink=uplink1)
+ if f1 != f2:
+ self.update_voice_frequency(f2, tgid=ga2, tdma_slot=self.get_tdma_slot(ch2), uplink=uplink2)
+ d['frequency2'] = f2
+ d['group2'] = self.mk_tg_dict(ga2)
+ if f1:
+ updated += 1
+ if f2:
+ updated += 1
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk02 grant update: chan %s %d %s %d\n' %(self.channel_id_to_string(ch1), ga1, self.channel_id_to_string(ch2), ga2))
elif opcode == 0x03: # group voice chan grant update exp : TIA.102-AABC-B-2005 page 56
- mfrid = (tsbk >> 80) & 0xff
- if mfrid == 0x90: #MOT_GRG_CN_GRANT_UPDT
- ch1 = (tsbk >> 64) & 0xffff
- sg1 = (tsbk >> 48) & 0xffff
- ch2 = (tsbk >> 32) & 0xffff
- sg2 = (tsbk >> 16) & 0xffff
- f1 = self.channel_id_to_frequency(ch1)
- f2 = self.channel_id_to_frequency(ch2)
- self.update_voice_frequency(f1, tgid=sg1, tdma_slot=self.get_tdma_slot(ch1))
- if f1 != f2:
- self.update_voice_frequency(f2, tgid=sg2, tdma_slot=self.get_tdma_slot(ch2))
- if f1:
- updated += 1
- if f2:
- updated += 1
- if self.debug > 10:
- print "MOT_GRG_CN_GRANT_UPDT(0x03): freq %s sg1:%d freq %s sg2:%d" % (self.channel_id_to_string(ch1), sg1, self.channel_id_to_string(ch2), sg2)
- elif mfrid == 0:
- ch1 = (tsbk >> 48) & 0xffff
- ch2 = (tsbk >> 32) & 0xffff
- ga = (tsbk >> 16) & 0xffff
- f = self.channel_id_to_frequency(ch1)
- self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch1))
- if f:
- updated += 1
- if self.debug > 10:
- print "tsbk03: freq-t %s freq-r %s ga:%d" % (self.channel_id_to_string(ch1), self.channel_id_to_string(ch2), ga)
+ opts = (tsbk >> 72) & 0xff
+ ch1 = (tsbk >> 48) & 0xffff
+ ch2 = (tsbk >> 32) & 0xffff
+ ga = (tsbk >> 16) & 0xffff
+ f = self.channel_id_to_frequency(ch1)
+ uplink = self.channel_id_to_frequency(ch2)
+ d = {'cc_event': 'grp_v_ch_grant_updt_exp', 'mfrid': mfrid, 'options': opts, 'frequency': f, 'group': self.mk_tg_dict(ga), 'opcode': opcode, 'tdma_slot': self.get_tdma_slot(ch1) }
+ self.post_event(d)
+ self.update_voice_frequency(f, tgid=ga, tdma_slot=self.get_tdma_slot(ch1), uplink=uplink)
+ if f:
+ updated += 1
+ if self.debug > 10:
+ sys.stderr.write('tsbk03: freq-t %s freq-r %s ga:%d\n' % (self.channel_id_to_string(ch1), self.channel_id_to_string(ch2), ga))
elif opcode == 0x16: # sndcp data ch
ch1 = (tsbk >> 48) & 0xffff
ch2 = (tsbk >> 32) & 0xffff
if self.debug > 10:
- print "tsbk16 sndcp data ch: chan %x %x" %(ch1, ch2)
+ sys.stderr.write('tsbk16 sndcp data ch: chan %x %x\n' % (ch1, ch2))
elif opcode == 0x34: # iden_up vhf uhf
iden = (tsbk >> 76) & 0xf
bwvu = (tsbk >> 72) & 0xf
@@ -401,29 +916,31 @@ class trunked_system (object):
self.freq_table[iden]['offset'] = toff * spac * 125
self.freq_table[iden]['step'] = spac * 125
self.freq_table[iden]['frequency'] = freq * 5
+ d = {'cc_event': 'iden_up_vu', 'iden': iden, 'bwvu': bwvu, 'offset': self.freq_table[iden]['offset'], 'step': self.freq_table[iden]['step'], 'freq': self.freq_table[iden]['frequency'], 'opcode': opcode }
+ self.post_event(d)
if self.debug > 10:
- print "tsbk34 iden vhf/uhf id %d toff %f spac %f freq %f [%s]" % (iden, toff * spac * 0.125 * 1e-3, spac * 0.125, freq * 0.000005, txt[toff_sign])
+ sys.stderr.write('tsbk34 iden vhf/uhf id %d toff %f spac %f freq %f [%s]\n' % (iden, toff * spac * 0.125 * 1e-3, spac * 0.125, freq * 0.000005, txt[toff_sign]))
elif opcode == 0x33: # iden_up_tdma
- mfrid = (tsbk >> 80) & 0xff
- if mfrid == 0:
- iden = (tsbk >> 76) & 0xf
- channel_type = (tsbk >> 72) & 0xf
- toff0 = (tsbk >> 58) & 0x3fff
- spac = (tsbk >> 48) & 0x3ff
- toff_sign = (toff0 >> 13) & 1
- toff = toff0 & 0x1fff
- if toff_sign == 0:
- toff = 0 - toff
- f1 = (tsbk >> 16) & 0xffffffff
- slots_per_carrier = [1,1,1,2,4,2]
- self.freq_table[iden] = {}
- self.freq_table[iden]['offset'] = toff * spac * 125
- self.freq_table[iden]['step'] = spac * 125
- self.freq_table[iden]['frequency'] = f1 * 5
+ iden = (tsbk >> 76) & 0xf
+ channel_type = (tsbk >> 72) & 0xf
+ toff0 = (tsbk >> 58) & 0x3fff
+ spac = (tsbk >> 48) & 0x3ff
+ toff_sign = (toff0 >> 13) & 1
+ toff = toff0 & 0x1fff
+ if toff_sign == 0:
+ toff = 0 - toff
+ f1 = (tsbk >> 16) & 0xffffffff
+ slots_per_carrier = [1,1,1,2,4,2]
+ self.freq_table[iden] = {}
+ self.freq_table[iden]['offset'] = toff * spac * 125
+ self.freq_table[iden]['step'] = spac * 125
+ self.freq_table[iden]['frequency'] = f1 * 5
+ if slots_per_carrier[channel_type] > 1:
self.freq_table[iden]['tdma'] = slots_per_carrier[channel_type]
- if self.debug > 10:
- print "tsbk33 iden up tdma id %d f %d offset %d spacing %d slots/carrier %d" % (iden, self.freq_table[iden]['frequency'], self.freq_table[iden]['offset'], self.freq_table[iden]['step'], self.freq_table[iden]['tdma'])
-
+ d = {'cc_event': 'iden_up_tdma', 'iden': iden, 'offset': self.freq_table[iden]['offset'], 'step': self.freq_table[iden]['step'], 'freq': self.freq_table[iden]['frequency'], 'slots': slots_per_carrier[channel_type], 'opcode': opcode }
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk33 iden up tdma id %d f %d offset %d spacing %d slots/carrier %d\n' % (iden, self.freq_table[iden]['frequency'], self.freq_table[iden]['offset'], self.freq_table[iden]['step'], self.freq_table[iden]['tdma']))
elif opcode == 0x3d: # iden_up
iden = (tsbk >> 76) & 0xf
bw = (tsbk >> 67) & 0x1ff
@@ -439,8 +956,10 @@ class trunked_system (object):
self.freq_table[iden]['offset'] = toff * 250000
self.freq_table[iden]['step'] = spac * 125
self.freq_table[iden]['frequency'] = freq * 5
+ d = {'cc_event': 'iden_up', 'iden': iden, 'offset': self.freq_table[iden]['offset'], 'step': self.freq_table[iden]['step'], 'freq': self.freq_table[iden]['frequency'], 'opcode': opcode }
+ self.post_event(d)
if self.debug > 10:
- print "tsbk3d iden id %d toff %f spac %f freq %f" % (iden, toff * 0.25, spac * 0.125, freq * 0.000005)
+ sys.stderr.write('tsbk3d iden id %d toff %f spac %f freq %f\n' % (iden, toff * 0.25, spac * 0.125, freq * 0.000005))
elif opcode == 0x3a: # rfss status
syid = (tsbk >> 56) & 0xfff
rfid = (tsbk >> 48) & 0xff
@@ -454,7 +973,32 @@ class trunked_system (object):
self.rfss_chan = f1
self.rfss_txchan = f1 + self.freq_table[chan >> 12]['offset']
if self.debug > 10:
- print "tsbk3a rfss status: syid: %x rfid %x stid %d ch1 %x(%s)" %(syid, rfid, stid, chan, self.channel_id_to_string(chan))
+ sys.stderr.write('tsbk3a rfss status: syid: %x rfid %x stid %d ch1 %x(%s)\n' %(syid, rfid, stid, chan, self.channel_id_to_string(chan)))
+ elif opcode == 0x29: # secondary cc explicit
+ rfid = (tsbk >> 72) & 0xff # octet 2
+ stid = (tsbk >> 64) & 0xff # octet 3
+ ch_t = (tsbk >> 48) & 0xffff # octet 4,5
+ ch_r = (tsbk >> 24) & 0xffff # octet 7,8
+ ss = (tsbk >> 16) & 0xff # octet 9
+ ft = self.channel_id_to_frequency(ch_t)
+ if ft:
+ self.secondary[ft] = 1
+ if self.debug > 10:
+ sys.stderr.write('tsbk29 sccb_exp: rfid %x stid %d %x(%s) %x(%s)\n' %(rfid, stid, ch_t, self.channel_id_to_string(ch_t), ch_r, self.channel_id_to_string(ch_r)))
+ elif opcode == 0x35: # time and date
+ flags = (tsbk >> 76) & 0xf # octet 2 upper nib
+ local_time_offset = (tsbk >> 64) & 0xfff # octet 2 lower nib and octet 3
+ dt = (tsbk >> 40) & 0xffffff # octet 4-6
+ tm = (tsbk >> 16) & 0xffffff # octet 7-9
+ # TODO: FIXME: check 'flags' bits to verify time/date/offset valid prior to use
+ yy = (dt >> 2) & 0x1fff
+ dd = (dt >> 15) & 0x1f
+ mm = (dt >> 20) & 0xf
+ hh = (tm >> 19) & 0x1f
+ mn = (tm >> 13) & 0x3f
+ ss = (tm >> 7) & 0x3f
+ if self.debug > 10:
+ sys.stderr.write('tsbk35 time and date: flags %x offset %d %02d/%02d/%02d %02d:%02d:%02d\n' % (flags, local_time_offset, yy, mm, dd, hh, mn, ss))
elif opcode == 0x39: # secondary cc
rfid = (tsbk >> 72) & 0xff
stid = (tsbk >> 64) & 0xff
@@ -468,7 +1012,7 @@ class trunked_system (object):
sorted_freqs = collections.OrderedDict(sorted(self.secondary.items()))
self.secondary = sorted_freqs
if self.debug > 10:
- print "tsbk39 secondary cc: rfid %x stid %d ch1 %x(%s) ch2 %x(%s)" %(rfid, stid, ch1, self.channel_id_to_string(ch1), ch2, self.channel_id_to_string(ch2))
+ sys.stderr.write('tsbk39 secondary cc: rfid %x stid %d ch1 %x(%s) ch2 %x(%s)\n' %(rfid, stid, ch1, self.channel_id_to_string(ch1), ch2, self.channel_id_to_string(ch2)))
elif opcode == 0x3b: # network status
wacn = (tsbk >> 52) & 0xfffff
syid = (tsbk >> 40) & 0xfff
@@ -479,8 +1023,9 @@ class trunked_system (object):
self.ns_wacn = wacn
self.ns_chan = f1
if self.debug > 10:
- print "tsbk3b net stat: wacn %x syid %x ch1 %x(%s)" %(wacn, syid, ch1, self.channel_id_to_string(ch1))
+ sys.stderr.write('tsbk3b net stat: wacn %x syid %x ch1 %x(%s)\n' %(wacn, syid, ch1, self.channel_id_to_string(ch1)))
elif opcode == 0x3c: # adjacent status
+ syid = (tsbk >> 56) & 0xfff
rfid = (tsbk >> 48) & 0xff
stid = (tsbk >> 40) & 0xff
ch1 = (tsbk >> 24) & 0xffff
@@ -488,31 +1033,157 @@ class trunked_system (object):
f1 = self.channel_id_to_frequency(ch1)
if f1 and table in self.freq_table:
self.adjacent[f1] = 'rfid: %d stid:%d uplink:%f tbl:%d' % (rfid, stid, (f1 + self.freq_table[table]['offset']) / 1000000.0, table)
+ self.adjacent_data[f1] = {'rfid': rfid, 'stid':stid, 'uplink': f1 + self.freq_table[table]['offset'], 'table': table, 'sysid':syid}
if self.debug > 10:
- print "tsbk3c adjacent: rfid %x stid %d ch1 %x(%s)" %(rfid, stid, ch1, self.channel_id_to_string(ch1))
+ sys.stderr.write('tsbk3c adjacent: rfid %x stid %d ch1 %x(%s) sysid 0x%x\n' %(rfid, stid, ch1, self.channel_id_to_string(ch1), syid))
if table in self.freq_table:
- print "tsbk3c : %s %s" % (self.freq_table[table]['frequency'] , self.freq_table[table]['step'] )
- #else:
- # print "tsbk other %x" % opcode
+ sys.stderr.write('tsbk3c : %s %s\n' % (self.freq_table[table]['frequency'] , self.freq_table[table]['step'] ))
+ elif opcode == 0x20: # ACK_RESP_FNE
+ aiv = (tsbk >> 79) & 1
+ ex = (tsbk >> 78) & 1
+ addl = (tsbk >> 40) & 0xffffffff
+ wacn = None
+ sysid = None
+ srcaddr = None
+ if ex:
+ wacn = (addl > 12) & 0xfffff
+ sysid = addl & 0xfff
+ else:
+ srcaddr = addl & 0xffffff
+ target = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'ack_resp_fne', 'aiv': aiv, 'ex': ex, 'addl': addl, 'wacn': wacn, 'tsbk_sysid': sysid, 'source': self.mk_src_dict(srcaddr), 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk20 ack_resp_fne: aiv %d ex %d wacn %s sysid %s src %s\n' % (aiv, ex, wacn, sysid, srcaddr))
+ elif opcode == 0x27: # DENY_RESP
+ aiv = (tsbk >> 79) & 1
+ reason = (tsbk >> 64) & 0xff
+ addl = (tsbk >> 40) & 0xffffff
+ target = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'deny_resp', 'aiv': aiv, 'reason': reason, 'additional': addl, 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk27 deny_resp: aiv %d reason %02x additional %x target %d\n' % (aiv, reason, addl, target))
+ elif opcode == 0x28: # grp_aff_rsp
+ lg = (tsbk >> 79) & 0x01
+ gav = (tsbk >> 72) & 0x03
+ aga = (tsbk >> 56) & 0xffff
+ ga = (tsbk >> 40) & 0xffff
+ ta = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'grp_aff_resp', 'affiliation': ['local', 'global'][lg], 'group_aff_value': gav, 'announce_group': self.mk_tg_dict(aga), 'group': self.mk_tg_dict(ga), 'target': self.mk_src_dict(ta), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk28 grp_aff_resp: mfrid: 0x%x, gav: %d, aga: %d, ga: %d, ta: %d\n' % (mfrid, gav, aga, ga, ta))
+ elif opcode == 0x2a: # GRP_AFF_Q
+ target = (tsbk >> 40) & 0xffffff
+ source = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'grp_aff_q', 'source': self.mk_src_dict(source), 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk2a grp_aff_q: mfrid: 0x%x, target %d source %d\n' % (mfrid, target, source))
+ elif opcode == 0x2b: # LOC_REG_RESP
+ rv = (tsbk >> 72) & 3
+ ga = (tsbk >> 56) & 0xffff
+ rfss = (tsbk >> 48) & 0xff
+ siteid = (tsbk >> 40) & 0xff
+ target = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'loc_reg_resp', 'rv': rv, 'rfss': rfss, 'siteid': siteid, 'group': self.mk_tg_dict(ga), 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk2b loc_reg_resp: mfrid: 0x%x, rv %d group %d rfss 0x%x siteid 0x%x target %d\n' % (mfrid, rv, ga, rfss, siteid, target))
+ elif opcode == 0x2c: # U_REG_RESP
+ rv = (tsbk >> 76) & 1
+ sysid = (tsbk >> 64) & 0xfff
+ target = (tsbk >> 40) & 0xffffff
+ source = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'u_reg_resp', 'rv': rv, 'tsbk_sysid': sysid, 'source': self.mk_src_dict(source), 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk2c u_reg_resp: mfrid: 0x%x, rv %d sysid %x target %d source %d\n' % (mfrid, rv, sysid, target, source))
+ elif opcode == 0x2d: # U_REG_CMD
+ target = (tsbk >> 40) & 0xffffff
+ source = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'u_reg_cmd', 'source': self.mk_src_dict(source), 'target': self.mk_src_dict(target), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk2d u_reg_cmd: mfrid: 0x%x, target %d source %d\n' % (mfrid, target, source))
+ elif opcode == 0x2f: # U_DE_REG_ACK
+ wacn = (tsbk >> 52) & 0xfffff
+ sysid = (tsbk >> 40) & 0xfff
+ source = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'u_de_reg_ack', 'wacn': wacn, 'tsbk_sysid': sysid, 'source': self.mk_src_dict(source), 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk2f u_de_reg_ack: mfrid: 0x%x, wacn 0x%x sysid 0x%x source %d\n' % (mfrid, wacn, sysid, source))
+
+ elif opcode == 0x24: # EXT_FNCT_CMD
+ efclass = (tsbk >> 72) & 0xff
+ efoperand = (tsbk >> 64) & 0xff
+ efargs = (tsbk >> 40) & 0xffffff
+ target = (tsbk >> 16) & 0xffffff
+ d = {'cc_event': 'ext_fnct_cmd', 'mfrid': mfrid, 'efclass': efclass, 'efoperand': efoperand, 'efargs': self.mk_src_dict(efargs), 'target': target, 'opcode': opcode}
+ self.post_event(d)
+ if self.debug > 10:
+ sys.stderr.write('tsbk24 ext_fnct_cmd: efclass %d efoperand %d efargs %s target %s\n' % (efclass, efoperand, efargs, target))
+
+
+ else:
+ if self.debug > 1:
+ sys.stderr.write('received unsupported TSBK opcode %x (%x)\n' % (opcode, tsbk))
return updated
def hunt_cc(self, curr_time):
- if self.cc_timeouts < 6:
- return
+ # return True if a tune request for frequency=self.trunk_cc should be issued
+ HUNT_HOLD_TIME = 8.0
+ #if self.cc_timeouts < 6:
+ # return False
+ if self.last_tsbk + HUNT_HOLD_TIME > time.time():
+ return False
+ if self.last_voice_time + HUNT_HOLD_TIME > time.time():
+ return False
+ if time.time() < self.next_hunt_cc:
+ return False
+ self.next_hunt_cc = time.time() + HUNT_HOLD_TIME
self.cc_timeouts = 0
self.cc_list_index += 1
if self.cc_list_index >= len(self.cc_list):
self.cc_list_index = 0
self.trunk_cc = self.cc_list[self.cc_list_index]
- sys.stderr.write('%f set trunk_cc to %s\n' % (curr_time, self.trunk_cc))
-
-def get_int_dict(s):
- if s[0].isdigit():
- return dict.fromkeys([int(d) for d in s.split(',')])
- return dict.fromkeys([int(d) for d in open(s).readlines()])
+ sys.stderr.write('%f %s: cycling to next trunk_cc: %s\n' % (curr_time, self.sysname, self.trunk_cc))
+ if self.trunk_cc != self.last_trunk_cc:
+ self.last_trunk_cc = self.trunk_cc
+ if self.debug >=5:
+ sys.stderr.write('%f %s: control channel change: %f\n' % (curr_time, self.sysname, self.trunk_cc / 1000000.0))
+ return True
+ return True
+
+ def frequency_change_params(self, current_tgid, new_frequency, nac, new_slot, new_frequency_type, curr_time):
+ params = {
+ 'freq': new_frequency,
+ 'tgid': current_tgid,
+ 'offset': self.offset,
+ 'tag': self.get_tag(current_tgid),
+ 'nac': nac,
+ 'system': self.sysname,
+ 'center_frequency': self.center_frequency,
+ 'tdma': new_slot,
+ 'wacn': self.ns_wacn,
+ 'sysid': self.ns_syid,
+ 'srcaddr': self.current_srcaddr,
+ 'grpaddr': self.current_grpaddr,
+ 'alg': self.current_alg,
+ 'algid': self.current_algid,
+ 'channel_type': new_frequency_type,
+ 'keyid': self.current_keyid,
+ 'prio': self.get_prio(current_tgid),
+ 'tag_color': self.get_tag_color(current_tgid),
+ 'srcaddr_color': self.get_unit_id_color(self.current_srcaddr),
+ 'srcaddr_tag': self.get_unit_id_tag(self.current_srcaddr),
+ 'effective_time': curr_time }
+ return params
class rx_ctl (object):
- def __init__(self, debug=0, frequency_set=None, conf_file=None, logfile_workers=None):
+ def __init__(self, debug=0, frequency_set=None, conf_file=None, logfile_workers=None, send_event=None):
class _states(object):
ACQ = 0
CC = 1
@@ -537,23 +1208,29 @@ class rx_ctl (object):
self.wait_until = time.time()
self.configs = {}
self.nacs = []
- self.last_tdma_vf = 0
- self.P2_GRACE_TIME = 1.0 # TODO: make more configurable
self.logfile_workers = logfile_workers
self.active_talkgroups = {}
self.working_frequencies = {}
self.xor_cache = {}
self.last_garbage_collect = 0
+ self.last_command = {'command': None, 'time': time.time()}
if self.logfile_workers:
self.input_rate = self.logfile_workers[0]['demod'].input_rate
+ self.enabled_nacs = None
+ self.next_status_png = time.time()
+ self.send_event = send_event
+ self.status_msg = ''
+ self.next_hunt_time = time.time()
if conf_file:
if conf_file.endswith('.tsv'):
self.build_config_tsv(conf_file)
+ elif conf_file.endswith('.json'):
+ self.build_config_json(conf_file)
else:
self.build_config(conf_file)
- self.nacs = self.configs.keys()
- self.current_nac = self.nacs[0]
+ self.nacs = [int (x) for x in self.configs.keys()]
+ self.current_nac = self.find_next_tsys()
self.current_state = self.states.CC
tsys = self.trunked_systems[self.current_nac]
@@ -564,6 +1241,7 @@ class rx_ctl (object):
self.set_frequency({
'freq': tsys.trunk_cc,
+ 'channel_type': 'cc',
'tgid': None,
'offset': tsys.offset,
'tag': "",
@@ -572,47 +1250,50 @@ class rx_ctl (object):
'center_frequency': tsys.center_frequency,
'tdma': None,
'wacn': None,
- 'sysid': None})
+ 'sysid': None,
+ 'prio': 0,
+ 'tag_color': None })
+
+ def build_config_json(self, conf_file):
+ d = json.loads(open(conf_file).read())
+ chans = [x for x in d['channels'] if x['active'] and x['trunked']]
+ self.configs = { chan['nac']: {'cclist':chan['cclist'],
+ 'offset':0,
+ 'blacklist': {int(tgid):None for tgid in chan['blacklist']},
+ 'whitelist': {int(tgid):None for tgid in chan['whitelist']},
+ 'sysname': chan['name'],
+ 'center_frequency': chan['frequency'],
+ 'modulation': chan['demod_type'],
+ 'tgid_map': {int(tgid): chan['tgids'][tgid] for tgid in chan['tgids'].keys()}}
+ for chan in chans}
+ for nac in self.configs.keys():
+ self.add_trunked_system(nac)
def set_frequency(self, params):
frequency = params['freq']
if frequency and self.frequency_set:
self.frequency_set(params)
+ def enable_status(self, s):
+ if self.debug >= 10:
+ sys.stderr.write('rx_ctl: enable_status: %s\n' % s)
+ nacs = s.split(',')
+ if s and len(nacs):
+ nacs = [int(x) for x in nacs]
+ else:
+ sys.stderr.write('cannot disable all NACs - request ignored\n')
+ return
+ self.enabled_nacs = nacs
+
def add_trunked_system(self, nac):
assert nac not in self.trunked_systems # duplicate nac not allowed
- blacklist = {}
- whitelist = None
- tgid_map = {}
cfg = None
if nac in self.configs:
cfg = self.configs[nac]
- self.trunked_systems[nac] = trunked_system(debug = self.debug, config=cfg)
+ self.trunked_systems[nac] = trunked_system(debug = self.debug, config=cfg, send_event=self.send_event, nac=nac)
def build_config_tsv(self, tsv_filename):
- import csv
- hdrmap = []
- configs = {}
- with open(tsv_filename, 'rb') as csvfile:
- sreader = csv.reader(csvfile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
- for row in sreader:
- if not hdrmap:
- # process first line of tsv file - header line
- for hdr in row:
- hdr = hdr.replace(' ', '_')
- hdr = hdr.lower()
- hdrmap.append(hdr)
- continue
- fields = {}
- for i in xrange(len(row)):
- if row[i]:
- fields[hdrmap[i]] = row[i]
- if hdrmap[i] != 'sysname':
- fields[hdrmap[i]] = fields[hdrmap[i]].lower()
- nac = int(fields['nac'], 0)
- configs[nac] = fields
-
- self.setup_config(configs)
+ self.setup_config(load_tsv(tsv_filename))
def build_config(self, config_filename):
import ConfigParser
@@ -629,7 +1310,24 @@ class rx_ctl (object):
configs[nac]['sysname'] = section
self.setup_config(configs)
- def add_default_config(self, nac, cclist=[], offset=0, whitelist=None, blacklist={}, tgid_map={}, sysname=None, center_frequency=None, modulation='cqpsk'):
+ def reload_tags(self, nac):
+ if nac not in self.trunked_systems.keys():
+ return
+ tsys = self.trunked_systems[nac]
+ tgid_tags_file = self.configs[nac]['tgid_tags_file']
+ new_reg = id_registry()
+ read_tags_file(tgid_tags_file, new_reg)
+ tsys.tgid_map = new_reg
+ sys.stderr.write('reloaded %s nac 0x%x\n' % (tgid_tags_file, nac))
+ unit_id_tags_file = self.configs[nac]['unit_id_tags_file']
+ if unit_id_tags_file is None:
+ return
+ new_reg = id_registry()
+ read_tags_file(unit_id_tags_file, new_reg)
+ tsys.unit_id_map = new_reg
+ sys.stderr.write('reloaded %s nac 0x%x\n' % (unit_id_tags_file, nac))
+
+ def add_default_config(self, nac, cclist=[], offset=0, whitelist=None, blacklist={}, tgid_map=None, unit_id_map=None,sysname=None, center_frequency=None, modulation='cqpsk'):
if nac in self.configs.keys():
return
if nac not in self.trunked_systems.keys():
@@ -649,51 +1347,77 @@ class rx_ctl (object):
cclist = [tsys.rfss_chan]
cclist.extend(tsys.secondary.keys())
tsys.cc_list = cclist
- self.configs[nac] = {'cclist':cclist, 'offset':offset, 'whitelist':whitelist, 'blacklist':blacklist, 'tgid_map':tgid_map, 'sysname': sysname, 'center_frequency': center_frequency, 'modulation':modulation}
+ self.configs[nac] = {'cclist':cclist, 'offset':offset, 'whitelist':whitelist, 'blacklist':blacklist, 'tgid_map':tgid_map, 'unit_id_map': unit_id_map, 'sysname': sysname, 'center_frequency': center_frequency, 'modulation':modulation}
self.current_nac = nac
self.current_state = self.states.CC
if nac not in self.nacs:
self.nacs.append(nac)
def setup_config(self, configs):
- for nac in configs:
- self.configs[nac] = {'cclist':[], 'offset':0, 'whitelist':None, 'blacklist':{}, 'tgid_map':{}, 'sysname': configs[nac]['sysname'], 'center_frequency': None}
- for f in configs[nac]['control_channel_list'].split(','):
- self.configs[nac]['cclist'].append(get_frequency(f))
- if 'offset' in configs[nac]:
- self.configs[nac]['offset'] = int(configs[nac]['offset'])
- if 'modulation' in configs[nac]:
- self.configs[nac]['modulation'] = configs[nac]['modulation']
- else:
- self.configs[nac]['modulation'] = 'cqpsk'
- for k in ['whitelist', 'blacklist']:
- if k in configs[nac]:
- self.configs[nac][k] = get_int_dict(configs[nac][k])
- if 'tgid_tags_file' in configs[nac]:
- import csv
- with open(configs[nac]['tgid_tags_file'], 'rb') as csvfile:
- sreader = csv.reader(csvfile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
- for row in sreader:
- tgid = int(row[0])
- txt = row[1]
- self.configs[nac]['tgid_map'][tgid] = txt
- if 'center_frequency' in configs[nac]:
- self.configs[nac]['center_frequency'] = get_frequency(configs[nac]['center_frequency'])
-
+ self.configs = make_config(configs)
+ for nac in self.configs.keys():
self.add_trunked_system(nac)
def find_next_tsys(self):
- self.current_id += 1
- if self.current_id >= len(self.nacs):
- self.current_id = 0
- return self.nacs[self.current_id]
+ wrap = 0
+ while True:
+ self.current_id += 1
+ if self.current_id >= len(self.nacs):
+ if wrap:
+ break
+ self.current_id = 0
+ wrap = 1
+ if self.enabled_nacs is not None and self.nacs[self.current_id] not in self.enabled_nacs:
+ continue
+ return self.nacs[self.current_id]
+ return self.nacs[0] ## should not occur
def to_json(self):
+ current_time = time.time()
d = {'json_type': 'trunk_update'}
for nac in self.trunked_systems.keys():
- d[nac] = json.loads(self.trunked_systems[nac].to_json())
+ d[nac] = self.trunked_systems[nac].to_dict()
+ if nac in self.configs.keys() and 'tgid_tags_file' in self.configs[nac]:
+ d[nac]['tgid_tags_file'] = self.configs[nac]['tgid_tags_file']
+ if nac in self.configs.keys() and 'unit_id_tags_file' in self.configs[nac]:
+ d[nac]['unit_id_tags_file'] = self.configs[nac]['unit_id_tags_file']
+ d['data'] = {'last_command': self.last_command['command'],
+ 'last_command_time': int(self.last_command['time'] - current_time),
+ 'tgid_hold': self.tgid_hold,
+ 'tgid_hold_until': int(self.tgid_hold_until - current_time),
+ 'hold_mode': self.hold_mode}
+ d['time'] = current_time
return json.dumps(d)
+ def make_status_png(self):
+ PNG_UPDATE_INTERVAL = 1.0
+ output_file = '../www/images/status.png'
+ tmp_output_file = '../www/images/tmp-status.png'
+ if time.time() < self.next_status_png:
+ return
+ self.next_status_png = time.time() + PNG_UPDATE_INTERVAL
+ status_str = 'OP25-hls hacks (c) Copyright 2020, 2021, KA1RBI\n'
+ status_str += self.status_msg
+ status_str += self.to_string()
+ status = status_str.split('\n')
+ status = [s for s in status if not s.startswith('tbl-id')]
+ create_image(status, imgfile=tmp_output_file, bgcolor="#c0c0c0", windowsize=(640,480))
+ if not os.access(tmp_output_file, os.R_OK):
+ return
+ os.rename(tmp_output_file, output_file)
+
+ def frequency_tracking_expire(self):
+ for nac in self.trunked_systems.keys():
+ self.trunked_systems[nac].frequency_tracking_expire()
+
+ def in_voice_state(self):
+ rc = self.current_state == self.states.TO_VC or self.current_state == self.states.VC
+ return rc
+
+ def dump_tgids(self):
+ for nac in self.trunked_systems.keys():
+ self.trunked_systems[nac].dump_tgids()
+
def to_string(self):
s = ''
for nac in self.trunked_systems:
@@ -702,61 +1426,154 @@ class rx_ctl (object):
return s
def process_qmsg(self, msg):
- type = msg.type()
+ self.frequency_tracking_expire()
+ if self.send_event is not None:
+ self.send_event(None) # periodically sends general status info
+ mtype = msg.type()
updated = 0
curr_time = time.time()
- if type == -2: # request from gui
- cmd = msg.to_string()
+ msgtext = msg.to_string()
+ aa55 = get_ordinals(msgtext[:2])
+ if mtype >= 0 or mtype in [-1, -3, -5, -6, -7]:
+ assert aa55 == 0xaa55
+ msgq_id = get_ordinals(msgtext[2:4])
+ msgtext = msgtext[4:]
+ else:
+ assert aa55 != 0xaa55
+ msgq_id = None
+ if mtype == -7: # P25 phase 1 link control
+ nac = get_ordinals(msgtext[:2])
+ msgtext = msgtext[2:]
+ msg = get_ordinals(msgtext)
+ if self.debug > 10:
+ sys.stderr.write("%f process_qmsg: LC info: %x\n" % (time.time(), msg))
+ opcode = (msg >> 64) & 0x3f
+ if opcode == 40: # rfss
+ lra = (msg >> 56) & 0xff
+ ch1 = (msg >> 40) & 0xffff
+ rfss = (msg >> 32) & 0xff
+ stid = (msg >> 24) & 0xff
+ ch2 = (msg >> 8) & 0xffff
+ ssclass = msg & 0xff
+ if self.debug > 10:
+ sys.stderr.write("%f p25p1 LC: LCRSBX: nac 0x%x lra 0x%x ch1 %x rfss 0x%x stid 0x%x ch2 %x ssclass 0x%x\n" %(time.time(), nac, lra, ch1, rfss, stid, ch2, ssclass))
+ elif opcode == 39: # adjacent
+ lra = (msg >> 56) & 0xff
+ ch1 = (msg >> 40) & 0xffff
+ rfss = (msg >> 32) & 0xff
+ stid = (msg >> 24) & 0xff
+ ch2 = (msg >> 8) & 0xffff
+ flags = msg & 0xff
+ if self.debug > 10:
+ sys.stderr.write("%f p25p1 LC: LCASBX: nac 0x%x lra 0x%x ch1 %x rfss 0x%x stid 0x%x ch2 %x flags 0x%x\n" %(time.time(), nac, lra, ch1, rfss, stid, ch2, flags))
+ else:
+ if self.debug > 0:
+ sys.stderr.write("%f p25p1 LC: unhandled LCO: nac 0x%x 0x%x\n" % (time.time(), nac, opcode))
+ return
+ elif mtype == -3: # P25 call signalling data
if self.debug > 10:
- print "process_qmsg: command: %s" % cmd
- self.update_state(cmd, curr_time)
+ sys.stderr.write("%f process_qmsg: P25 info: %s\n" % (time.time(), msgtext))
+ js = json.loads(msgtext)
+ nac = js['nac']
+ if nac != self.current_nac:
+ sys.stderr.write('warning: nac mismatch: nac %x current_nac %x js %s\n' % (nac, self.current_nac, msgtext))
+ # return
+ if nac not in self.trunked_systems.keys():
+ return
+ tsys = self.trunked_systems[nac]
+ if self.current_state != self.states.CC:
+ tsys.last_voice_time = curr_time
+ if 'srcaddr' in js.keys():
+ tsys.current_srcaddr = js['srcaddr']
+ if 'grpaddr' in js.keys():
+ tsys.current_grpaddr = js['grpaddr']
+ if 'algid' in js.keys():
+ tsys.current_algid = js['algid']
+ if 'alg' in js.keys():
+ tsys.current_alg = js['alg']
+ if 'keyid' in js.keys():
+ tsys.current_keyid = js['keyid']
+ return
+ elif mtype == -2: # request from gui
+ cmd = msgtext
+ if self.debug > 10:
+ sys.stderr.write('process_qmsg: command: %s\n' % cmd)
+ self.update_state(cmd, curr_time, int(msg.arg1())) # self.update_state(cmd, curr_time)
return
- elif type == -1: # timeout
- if self.debug:
- print "process_data_unit timeout"
+ elif mtype == -1: # timeout
+ if self.debug > 0:
+ sys.stderr.write('%f process_data_unit timeout, channel %s\n' % (time.time(), msgq_id))
self.update_state('timeout', curr_time)
if self.logfile_workers:
self.logging_scheduler(curr_time)
return
- elif type < 0:
- print 'unknown message type %d' % (type)
+ elif mtype == -6: # p25 tdma cc
+ # nac is always 1st two bytes
+ nac = get_ordinals(msgtext[:2])
+ msgtext = msgtext[2:]
+ if self.debug > 1:
+ sys.stderr.write('tdma_cc message nac 0x%x text 0x%x len %d\n' % (nac, get_ordinals(msgtext), len(msgtext)))
+ if nac not in self.trunked_systems.keys():
+ sys.stderr.write('tdma_cc received from unexpected NAC 0x%x\n' % nac)
+ return
+ tsys = self.trunked_systems[nac]
+ tsys.decode_tdma_cc(msgtext[1:])
+ return
+ elif mtype < 0:
+ sys.stderr.write('unknown message type %d\n' % (mtype))
return
- s = msg.to_string()
+ s = msgtext
# nac is always 1st two bytes
- nac = (ord(s[0]) << 8) + ord(s[1])
+ nac = get_ordinals(s[:2])
if nac == 0xffff:
- # TDMA
- self.update_state('tdma_duid%d' % type, curr_time)
+ sys.stderr.write('received invalid nac 0xffff, mtype %d msgq_id %s\n' % (mtype, msgq_id))
return
s = s[2:]
if self.debug > 10:
- print "nac %x type %d at %f state %d len %d" %(nac, type, time.time(), self.current_state, len(s))
- if (type == 7 or type == 12) and nac not in self.trunked_systems:
+ sys.stderr.write('nac %x type %d at %f state %d len %d\n' %(nac, mtype, time.time(), self.current_state, len(s)))
+ if (mtype == 7 or mtype == 12) and nac not in self.trunked_systems:
if not self.configs:
# TODO: allow whitelist/blacklist rather than blind automatic-add
self.add_trunked_system(nac)
else:
+ sys.stderr.write("%f NAC %x not configured\n" % (time.time(), nac))
return
- if type == 7: # trunk: TSBK
- t = 0
- for c in s:
- t = (t << 8) + ord(c)
- updated += self.trunked_systems[nac].decode_tsbk(t)
- elif type == 12: # trunk: MBT
- s1 = s[:10]
- s2 = s[10:]
- header = mbt_data = 0
- for c in s1:
- header = (header << 8) + ord(c)
- for c in s2:
- mbt_data = (mbt_data << 8) + ord(c)
+ if nac not in self.trunked_systems.keys():
+ sys.stderr.write('received unknown nac 0x%x, mtype %d len configs %d msgq_id %d\n' % (nac, mtype, len(self.configs.keys()), msgq_id))
+ return
+ tsys = self.trunked_systems[nac]
+ if mtype == 0 or mtype == 5 or mtype == 10: # HDU or LDU1 or LDU2 i.e. voice
+ if self.current_state != self.states.CC:
+ tsys.last_voice_time = curr_time
+ elif mtype == 7: # trunk: TSBK
+ t = get_ordinals(s)
+ updated += tsys.decode_tsbk(t)
+ elif mtype == 12: # trunk: MBT
+ s1 = s[:10] # header without crc
+ s2 = s[12:]
+ header = get_ordinals(s1)
+ mbt_data = get_ordinals(s2)
+
+ fmt = (header >> 72) & 0x1f
+ sap = (header >> 64) & 0x3f
+ src = (header >> 48) & 0xffffff
+ if fmt != 0x17: # only Extended Format MBT presently supported
+ return
+
opcode = (header >> 16) & 0x3f
if self.debug > 10:
- print "type %d at %f state %d len %d/%d opcode %x [%x/%x]" %(type, time.time(), self.current_state, len(s1), len(s2), opcode, header,mbt_data)
- updated += self.trunked_systems[nac].decode_mbt_data(opcode, header << 16, mbt_data << 32)
+ sys.stderr.write('type %d at %f state %d len %d/%d opcode %x [%x/%x]\n' %(mtype, time.time(), self.current_state, len(s1), len(s2), opcode, header,mbt_data))
+ updated += tsys.decode_mbt_data(opcode, src, header << 16, mbt_data << 32)
- if nac != self.current_nac:
- return
+ self.make_status_png()
+
+ #if nac != self.current_nac:
+ # if self.debug > 10: # this is occasionally expected if cycling between different tsys
+ # cnac = self.current_nac
+ # if cnac is None:
+ # cnac = 0
+ # sys.stderr.write("%f received NAC %x does not match expected NAC %x\n" % (time.time(), nac, cnac))
+ # return
if self.logfile_workers:
self.logging_scheduler(curr_time)
@@ -765,7 +1582,7 @@ class rx_ctl (object):
if updated:
self.update_state('update', curr_time)
else:
- self.update_state('duid%d' % type, curr_time)
+ self.update_state('duid%d' % mtype, curr_time)
def find_available_worker(self):
for worker in self.logfile_workers:
@@ -779,7 +1596,7 @@ class rx_ctl (object):
self.working_frequencies[frequency]['worker']['demod'].set_relative_frequency(0)
self.working_frequencies[frequency]['worker']['active'] = False
self.working_frequencies.pop(frequency)
- print '%f release worker frequency %d' % (curr_time, frequency)
+ sys.stderr.write('%f release worker frequency %d\n' % (curr_time, frequency))
def free_talkgroup(self, frequency, tgid, curr_time):
decoder = self.working_frequencies[frequency]['worker']['decoder']
@@ -787,10 +1604,8 @@ class rx_ctl (object):
index = tdma_slot
if tdma_slot is None:
index = 0
- filename = 'idle-channel-%d-%d-%f.wav' % (frequency, index, curr_time)
- decoder.set_output(filename, index=index)
self.working_frequencies[frequency]['tgids'].pop(tgid)
- print '%f release tgid %d frequency %d' % (curr_time, tgid, frequency)
+ sys.stderr.write('%f release tgid %d frequency %d\n' % (curr_time, tgid, frequency))
def logging_scheduler(self, curr_time):
tsys = self.trunked_systems[self.current_nac]
@@ -800,14 +1615,14 @@ class rx_ctl (object):
# see if this tgid active on any other freq(s)
other_freqs = [f for f in self.working_frequencies if f != frequency and tgid in self.working_frequencies[f]['tgids']]
if other_freqs:
- print '%f tgid %d slot %s frequency %d found on other frequencies %s' % (curr_time, tgid, tdma_slot, frequency, ','.join(['%s' % f for f in other_freqs]))
+ sys.stderr.write('%f tgid %d slot %s frequency %d found on other frequencies %s\n' % (curr_time, tgid, tdma_slot, frequency, ','.join(['%s' % f for f in other_freqs])))
for f in other_freqs:
self.free_talkgroup(f, tgid, curr_time)
if not self.working_frequencies[f]['tgids']:
self.free_frequency(f, curr_time)
diff = abs(tsys.center_frequency - frequency)
if diff > self.input_rate/2:
- #print '%f request for frequency %d tgid %d failed, offset %d exceeds maximum %d' % (curr_time, frequency, tgid, diff, self.input_rate/2)
+ #sys.stderr.write('%f request for frequency %d tgid %d failed, offset %d exceeds maximum %d\n' % (curr_time, frequency, tgid, diff, self.input_rate/2))
continue
update = True
@@ -817,25 +1632,28 @@ class rx_ctl (object):
if tgids[tgid]['tdma_slot'] == tdma_slot:
update = False
else:
- print '%f slot switch %s was %s tgid %d frequency %d' % (curr_time, tdma_slot, tgids[tgid]['tdma_slot'], tgid, frequency)
+ sys.stderr.write('%f slot switch %s was %s tgid %d frequency %d\n' % (curr_time, tdma_slot, tgids[tgid]['tdma_slot'], tgid, frequency))
worker = self.working_frequencies[frequency]['worker']
else:
#active_tdma_slots = [tgids[tg]['tdma_slot'] for tg in tgids]
- print '%f new tgid %d slot %s arriving on already active frequency %d' % (curr_time, tgid, tdma_slot, frequency)
+ sys.stderr.write("%f new tgid %d slot %s arriving on already active frequency %d\n" % (curr_time, tgid, tdma_slot, frequency))
+ previous_tgid = [id for id in tgids if tgids[id]['tdma_slot'] == tdma_slot]
+ assert len(previous_tgid) == 1 ## check for logic error
+ self.free_talkgroup(frequency, previous_tgid[0], curr_time)
worker = self.working_frequencies[frequency]['worker']
else:
worker = self.find_available_worker()
if worker is None:
- print '*** error, no free demodulators, freq %d tgid %d' % (frequency, tgid)
+ sys.stderr.write('*** error, no free demodulators, freq %d tgid %d\n' % (frequency, tgid))
continue
self.working_frequencies[frequency] = {'tgids' : {}, 'worker': worker}
worker['demod'].set_relative_frequency(tsys.center_frequency - frequency)
- print '%f starting worker frequency %d tg %d slot %s' % (curr_time, frequency, tgid, tdma_slot)
+ sys.stderr.write('%f starting worker frequency %d tg %d slot %s\n' % (curr_time, frequency, tgid, tdma_slot))
self.working_frequencies[frequency]['tgids'][tgid] = {'updated': curr_time, 'tdma_slot': tdma_slot}
if not update:
continue
filename = 'tgid-%d-%f.wav' % (tgid, curr_time)
- print '%f update frequency %d tg %d slot %s file %s' % (curr_time, frequency, tgid, tdma_slot, filename)
+ sys.stderr.write('%f update frequency %d tg %d slot %s file %s\n' % (curr_time, frequency, tgid, tdma_slot, filename))
# set demod speed, decoder slot, output file name
demod = worker['demod']
decoder = worker['decoder']
@@ -850,6 +1668,7 @@ class rx_ctl (object):
if xorhash not in self.xor_cache:
self.xor_cache[xorhash] = lfsr.p25p2_lfsr(self.current_nac, tsys.ns_syid, tsys.ns_wacn).xor_chars
decoder.set_xormask(self.xor_cache[xorhash], xorhash, index=index)
+ decoder.set_nac(self.current_nac, index=index)
demod.set_omega(symbol_rate)
decoder.set_output(filename, index=index)
@@ -871,10 +1690,13 @@ class rx_ctl (object):
for frequency in gc_frequencies: # expire working frequencies
self.free_frequency(frequency, curr_time)
- def update_state(self, command, curr_time):
+ def update_state(self, command, curr_time, cmd_data = 0): # def update_state(self, command, curr_time):
if not self.configs:
return # run in "manual mode" if no conf
+ if type(command) is not str and isinstance(command, bytes):
+ command = command.decode()
+
nac = self.current_nac
tsys = self.trunked_systems[nac]
@@ -883,74 +1705,140 @@ class rx_ctl (object):
new_state = None
new_nac = None
new_slot = None
+ new_frequency_type = None
+ uplink = None
if command == 'timeout':
if self.current_state == self.states.CC:
if self.debug > 0:
- sys.stderr.write("[%f] control channel timeout\n" % time.time())
+ sys.stderr.write("%f control channel timeout, current CC %d\n" % (time.time(), tsys.trunk_cc))
tsys.cc_timeouts += 1
- elif self.current_state != self.states.CC and curr_time - self.last_tdma_vf > self.P2_GRACE_TIME:
+ elif self.current_state != self.states.CC and tsys.last_voice_time + 1.0 < curr_time:
if self.debug > 0:
- sys.stderr.write("[%f] voice timeout\n" % time.time())
+ sys.stderr.write("%f voice timeout\n" % time.time())
+ if self.hold_mode is False:
+ self.current_tgid = None
+ tsys.current_srcaddr = 0
new_state = self.states.CC
new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
elif command == 'update':
if self.current_state == self.states.CC:
desired_tgid = None
- if self.tgid_hold_until > curr_time:
+ if (self.tgid_hold is not None) and (self.tgid_hold_until > curr_time):
+ if self.debug > 1:
+ sys.stderr.write("%f hold active tg(%s)\n" % (time.time(), self.tgid_hold))
desired_tgid = self.tgid_hold
- new_frequency, new_tgid, tdma_slot = tsys.find_talkgroup(curr_time, tgid=desired_tgid)
+ elif (self.tgid_hold is not None) and (self.hold_mode == False):
+ self.tgid_hold = None
+ new_frequency, new_tgid, tdma_slot, srcaddr, uplink = tsys.find_talkgroup(curr_time, tgid=desired_tgid, hold=self.hold_mode)
if new_frequency:
+ new_frequency_type = 'vc'
+ if self.debug > 0:
+ tslot = tdma_slot if tdma_slot is not None else '-'
+ sys.stderr.write("%f voice update: tg(%s), freq(%s), slot(%s), prio(%d)\n" % (time.time(), new_tgid, new_frequency, tslot, tsys.get_prio(new_tgid)))
+ new_state = self.states.TO_VC
+ self.current_tgid = new_tgid
+ tsys.current_srcaddr = srcaddr
+ self.tgid_hold = new_tgid
+ self.tgid_hold_until = max(curr_time + self.TGID_HOLD_TIME, self.tgid_hold_until)
+ self.wait_until = curr_time + self.TSYS_HOLD_TIME
+ new_slot = tdma_slot
+ elif 0: # # # # # else: # check for priority tgid preemption
+ new_frequency, new_tgid, tdma_slot, srcaddr, uplink = tsys.find_talkgroup(tsys.talkgroups[self.current_tgid]['time'], tgid=self.current_tgid, hold=self.hold_mode)
+ if new_tgid != self.current_tgid:
if self.debug > 0:
- sys.stderr.write("[%f] voice update: tg(%s), freq(%s), slot(%s)\n" % (time.time(), new_tgid, new_frequency, tdma_slot))
+ tslot = tdma_slot if tdma_slot is not None else '-'
+ sys.stderr.write("%f voice preempt: tg(%s), freq(%s), slot(%s), prio(%d)\n" % (time.time(), new_tgid, new_frequency, tslot, tsys.get_prio(new_tgid)))
+ new_frequency_type = 'vc'
new_state = self.states.TO_VC
self.current_tgid = new_tgid
+ tsys.current_srcaddr = srcaddr
+ self.tgid_hold = new_tgid
+ self.tgid_hold_until = max(curr_time + self.TGID_HOLD_TIME, self.tgid_hold_until)
+ self.wait_until = curr_time + self.TSYS_HOLD_TIME
new_slot = tdma_slot
- elif command == 'tdma_duid3': # tdma termination, no channel release (MAC_HANGTIME)
+ else:
+ new_frequency = None
+ elif command == 'duid3' or command == 'tdma_duid3': # termination, no channel release
if self.current_state != self.states.CC:
self.tgid_hold = self.current_tgid
self.tgid_hold_until = max(curr_time + self.TGID_HOLD_TIME, self.tgid_hold_until)
self.wait_until = curr_time + self.TSYS_HOLD_TIME
- self.last_tdma_vf = curr_time
- elif command == 'duid3' or command == 'duid15' or command == 'tdma_duid15': # fdma/tdma termination with channel release
+ elif command == 'duid15' or command == 'tdma_duid15': # termination with channel release
if self.current_state != self.states.CC:
+ if self.debug > 1:
+ sys.stderr.write("%f %s, tg(%d)\n" % (time.time(), command, self.current_tgid))
+ tsys.current_srcaddr = 0
+ tsys.current_grpaddr = 0
+ self.wait_until = curr_time + self.TSYS_HOLD_TIME
+ self.tgid_hold = self.current_tgid
+ self.tgid_hold_until = max(curr_time + self.TGID_HOLD_TIME, self.tgid_hold_until)
+ if self.hold_mode is False:
+ self.current_tgid = None
new_state = self.states.CC
new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
elif command == 'duid0' or command == 'duid5' or command == 'duid10' or command == 'tdma_duid5':
if self.current_state == self.states.TO_VC:
new_state = self.states.VC
self.tgid_hold = self.current_tgid
self.tgid_hold_until = max(curr_time + self.TGID_HOLD_TIME, self.tgid_hold_until)
self.wait_until = curr_time + self.TSYS_HOLD_TIME
- if command == 'tdma_duid5':
- self.last_tdma_vf = curr_time
- elif command == 'duid7' or command == 'duid12':
+ elif command == 'duid7' or command == 'duid12': # tsbk/pdu should never arrive here...
pass
elif command == 'hold':
- if self.hold_mode is False and self.current_tgid:
- self.tgid_hold = self.current_tgid
- self.tgid_hold_until = curr_time + 86400 * 10000
- self.hold_mode = True
+ self.last_command = {'command': command, 'time': curr_time}
+ if self.hold_mode:
+ new_hold_mode = False
+ else:
+ new_hold_mode = True
+ if new_hold_mode and (cmd_data is None or cmd_data < 1):
if self.debug > 0:
- sys.stderr.write ('set hold until %f tgid %s\n' % (self.tgid_hold_until, self.current_tgid))
- elif self.hold_mode is True:
+ sys.stderr.write ('%f set hold failed, unable to determine TGID\n' % (time.time()))
+ new_hold_mode = False
+ if new_hold_mode is False: # unset hold
self.current_tgid = None
self.tgid_hold = None
self.tgid_hold_until = curr_time
- self.hold_mode = False
+ self.hold_mode = new_hold_mode
+ else: # set hold
+ self.tgid_hold = cmd_data
+ self.tgid_hold_until = curr_time + 86400 * 10000
+ self.hold_mode = new_hold_mode
+ if self.debug > 0:
+ sys.stderr.write ('%f set hold tg(%s) until %f\n' % (time.time(), self.tgid_hold, self.tgid_hold_until))
+ if self.debug > 0:
+ sys.stderr.write ('%f set hold tg(%s) until %f mode %s current tgid %s\n' % (time.time(), self.tgid_hold, self.tgid_hold_until, self.hold_mode, self.current_tgid))
+ if self.current_tgid != self.tgid_hold:
+ self.current_tgid = self.tgid_hold
+ self.current_srcaddr = 0
+ self.current_grpaddr = 0
+ self.current_alg = ""
+ self.current_algid = 128
+ self.current_keyid = 0
+ new_state = self.states.CC
+ new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
elif command == 'set_hold':
+ self.last_command = {'command': command, 'time': curr_time}
if self.current_tgid:
self.tgid_hold = self.current_tgid
self.tgid_hold_until = curr_time + 86400 * 10000
self.hold_mode = True
- print 'set hold until %f' % self.tgid_hold_until
+ if self.debug > 0:
+ sys.stderr.write ('%f set hold until %f\n' % (time.time(), self.tgid_hold_until))
elif command == 'unset_hold':
+ self.last_command = {'command': command, 'time': curr_time}
if self.current_tgid:
+ if self.debug > 0:
+ sys.stderr.write ('%f clear hold tg(%s)\n' % (time.time(), self.tgid_hold))
self.current_tgid = None
self.tgid_hold = None
self.tgid_hold_until = curr_time
self.hold_mode = False
elif command == 'skip' or command == 'lockout':
+ self.last_command = {'command': command, 'time': curr_time}
if self.current_tgid:
end_time = None
if command == 'skip':
@@ -960,51 +1848,88 @@ class rx_ctl (object):
self.tgid_hold = None
self.tgid_hold_until = curr_time
self.hold_mode = False
+ tsys.current_srcaddr = 0
if self.current_state != self.states.CC:
new_state = self.states.CC
new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
else:
- print 'update_state: unknown command: %s\n' % command
+ sys.stderr.write('update_state: unknown command: %s\n' % command)
assert 0 == 1
- tsys.hunt_cc(curr_time)
+ if new_frequency is not None and tsys.trunk_cc != tsys.rfss_chan:
+ sys.stderr.write('warning: trunk control channel frequency %f does not match rfss frequency %f\n' % (tsys.trunk_cc/1000000.0, tsys.rfss_chan/1000000.0))
- if self.wait_until <= curr_time and self.tgid_hold_until <= curr_time and new_state is None:
+ hunted_cc = tsys.hunt_cc(curr_time)
+
+ if self.enabled_nacs is not None and self.current_nac not in self.enabled_nacs:
+ tsys.current_srcaddr = 0
+ tsys.current_grpaddr = 0
+ new_nac = self.find_next_tsys()
+ new_state = self.states.CC
+ elif self.current_state != self.states.CC and self.tgid_hold_until <= curr_time and self.hold_mode is False and new_state is None:
+ if self.debug > 1:
+ sys.stderr.write("%f release tg(%s)\n" % (time.time(), self.current_tgid))
+ self.tgid_hold = None
+ self.current_tgid = None
+ tsys.current_srcaddr = 0
+ tsys.current_grpaddr = 0
+ new_state = self.states.CC
+ new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
+ elif self.wait_until <= curr_time and self.tgid_hold_until <= curr_time and self.hold_mode is False and new_state is None:
self.wait_until = curr_time + self.TSYS_HOLD_TIME
+ tsys.current_srcaddr = 0
+ tsys.current_grpaddr = 0
new_nac = self.find_next_tsys()
new_state = self.states.CC
- if new_nac:
+ if new_nac is not None:
nac = self.current_nac = new_nac
tsys = self.trunked_systems[nac]
new_frequency = tsys.trunk_cc
+ new_frequency_type = 'cc'
+ tsys.current_srcaddr = 0
+ tsys.current_grpaddr = 0
self.current_tgid = None
- if new_frequency:
- self.set_frequency({
- 'freq': new_frequency,
- 'tgid': self.current_tgid,
- 'offset': tsys.offset,
- 'tag': tsys.get_tag(self.current_tgid),
- 'nac': nac,
- 'system': tsys.sysname,
- 'center_frequency': tsys.center_frequency,
- 'tdma': new_slot,
- 'wacn': tsys.ns_wacn,
- 'sysid': tsys.ns_syid})
+ if new_frequency is not None:
+ params = tsys.frequency_change_params(self.current_tgid, new_frequency, nac, new_slot, new_frequency_type, curr_time)
+ if uplink is not None and uplink > 0:
+ params['uplink'] = uplink
+ self.status_msg = 'F %f TG %s %s at %s\n' % (params['freq'] / 1000000.0, params['tgid'], params['tag'], time.asctime())
+ self.set_frequency(params)
- if new_state:
+ if new_state is not None:
self.current_state = new_state
+ def parallel_hunt_cc(self):
+ curr_time = time.time()
+ if curr_time < self.next_hunt_time:
+ return
+ self.next_hunt_time = curr_time + 1.0
+ for nac in self.trunked_systems.keys():
+ tsys = self.trunked_systems[nac]
+ rc = tsys.hunt_cc(curr_time)
+ if not rc:
+ continue
+ tgid = None
+ freq = tsys.trunk_cc
+ new_slot = None
+ new_frequency_type = 'cc'
+ params = tsys.frequency_change_params(tgid, freq, nac, new_slot, new_frequency_type, curr_time)
+ self.status_msg = 'F %f TG %s %s at %s\n' % (params['freq'] / 1000000.0, params['tgid'], params['tag'], time.asctime())
+ self.set_frequency(params)
+
def main():
q = 0x3a000012ae01013348704a54
rc = crc16(q,12)
- print "should be zero: %x" % rc
+ sys.stderr.write('should be zero: %x\n' % rc)
assert rc == 0
q = 0x3a001012ae01013348704a54
rc = crc16(q,12)
- print "should be nonzero: %x" % rc
+ sys.stderr.write('should be nonzero: %x\n' % rc)
assert rc != 0
t = trunked_system(debug=255)
diff --git a/op25/gr-op25_repeater/apps/tsvfile.py b/op25/gr-op25_repeater/apps/tsvfile.py
new file mode 100755
index 0000000..867e331
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tsvfile.py
@@ -0,0 +1,191 @@
+
+# Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Max H. Parke KA1RBI
+#
+# This file is part of OP25
+#
+# OP25 is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# OP25 is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+# License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with OP25; see the file COPYING. If not, write to the Free
+# Software Foundation, Inc., 51 Franklin Street, Boston, MA
+# 02110-1301, USA.
+
+import sys
+import os
+import csv
+
+def get_frequency(f): # return frequency in Hz
+ if f.find('.') == -1: # assume in Hz
+ return int(f)
+ else: # assume in MHz due to '.'
+ return int(float(f) * 1000000)
+
+def get_int_dict(s):
+ # parameter string s is the file name to be read,
+ # except when the first character of s is a digit,
+ # in which case s itself is the comma-separated list of ints
+
+ if s[0].isdigit():
+ return dict.fromkeys([int(d) for d in s.split(',')])
+
+ # create dict by reading from file
+ d = {} # this is the dict
+ with open(s,"r") as f:
+ for v in f:
+ v = v.split("\t",1) # split on tab
+ try:
+ v0 = int(v[0]) # first parameter is tgid or start of tgid range
+ v1 = v0
+ if (len(v) > 1) and (int(v[1]) > v0): # second parameter if present is end of tgid range
+ v1 = int(v[1])
+
+ for tg in range(v0, (v1 + 1)):
+ if tg not in d: # is this a new tg?
+ d[tg] = [] # if so, add to dict (key only, value null)
+ sys.stderr.write('added talkgroup %d from %s\n' % (tg,s))
+
+ except (IndexError, ValueError) as ex:
+ continue
+ f.close()
+ return dict.fromkeys(d)
+
+def utf_ascii(ustr):
+ return (ustr.decode("utf-8")).encode("ascii", "ignore")
+
+class id_registry:
+ def __init__(self):
+ self.cache = {}
+ self.wildcards = {}
+
+ def add(self, id_str, tag, color):
+ if '-' in id_str:
+ a = [int(x) for x in id_str.split('-')]
+ if a[0] >= a[1]:
+ raise AssertionError('invalid ID range in %s' % id_str)
+ for i in range(a[0], a[1]+1):
+ self.cache[i] = {'tag': tag, 'color': color}
+ elif '.' in id_str:
+ rc = id_str.find('.')
+ self.wildcards[id_str] = {'prefix': id_str[:rc], 'len': len(id_str), 'tag': tag, 'color': color, 'type': '.'}
+ elif '*' in id_str:
+ rc = id_str.find('*')
+ self.wildcards[id_str] = {'prefix': id_str[:rc], 'len': 0, 'tag': tag, 'color': color, 'type': '*'}
+ else:
+ self.cache[int(id_str)] = {'tag': tag, 'color': color}
+
+ def lookup(self, id):
+ if id in self.cache.keys():
+ return self.cache[id]
+ id_str = '%d' % id
+ for w in self.wildcards.keys():
+ if not id_str.startswith(self.wildcards[w]['prefix']):
+ continue
+ if self.wildcards[w]['type'] == '.' and len(id_str) != self.wildcards[w]['len']:
+ continue
+ # wildcard matched
+ self.cache[id] = {'tag': self.wildcards[w]['tag'], 'color': self.wildcards[w]['color']}
+ return self.cache[id]
+ # not found in cache, and no wildcard matched
+ self.cache[id] = None
+ return None
+
+ def get_color(self, id):
+ d = self.lookup(id)
+ if not d:
+ return 0
+ return d['color']
+
+ def get_tag(self, id):
+ d = self.lookup(id)
+ if not d:
+ return ""
+ return d['tag']
+
+def load_tsv(tsv_filename):
+ hdrmap = []
+ configs = {}
+ with open(tsv_filename, 'r') as csvfile:
+ sreader = csv.reader(csvfile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
+ for row in sreader:
+ if not hdrmap:
+ # process first line of tsv file - header line
+ for hdr in row:
+ hdr = hdr.replace(' ', '_')
+ hdr = hdr.lower()
+ hdrmap.append(hdr)
+ continue
+ fields = {}
+ for i in range(len(row)):
+ if row[i]:
+ fields[hdrmap[i]] = row[i]
+ if hdrmap[i] != 'sysname':
+ fields[hdrmap[i]] = fields[hdrmap[i]].lower()
+ nac = int(fields['nac'], 0)
+ configs[nac] = fields
+ return configs
+
+def read_tags_file(tags_file, result):
+ import csv
+ with open(tags_file, 'r') as csvfile:
+ sreader = csv.reader(csvfile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
+ for row in sreader:
+ id_str = row[0]
+ txt = row[1]
+ if len(row) >= 3:
+ try:
+ color = int(row[2])
+ except ValueError as ex:
+ color = 0
+ else:
+ color = 0
+ result.add(id_str, txt, color)
+
+def make_config(configs):
+ result_config = {}
+ for nac in configs:
+ result_config[nac] = {'cclist':[], 'offset':0, 'whitelist':None, 'blacklist':{}, 'tgid_map':id_registry(), 'unit_id_map': id_registry(), 'sysname': configs[nac]['sysname'], 'center_frequency': None}
+ for f in configs[nac]['control_channel_list'].split(','):
+ result_config[nac]['cclist'].append(get_frequency(f))
+ if 'offset' in configs[nac]:
+ result_config[nac]['offset'] = int(configs[nac]['offset'])
+ if 'modulation' in configs[nac]:
+ result_config[nac]['modulation'] = configs[nac]['modulation']
+ else:
+ result_config[nac]['modulation'] = 'cqpsk'
+ for k in ['whitelist', 'blacklist']:
+ if k in configs[nac]:
+ result_config[nac][k] = get_int_dict(configs[nac][k])
+ if 'tgid_tags_file' in configs[nac]:
+ fname = configs[nac]['tgid_tags_file']
+ if ',' in fname:
+ l = fname.split(',')
+ tgid_tags_file = l[0]
+ unit_id_tags_file = l[1]
+ else:
+ tgid_tags_file = fname
+ unit_id_tags_file = None
+ result_config[nac]['tgid_tags_file'] = tgid_tags_file
+ result_config[nac]['unit_id_tags_file'] = unit_id_tags_file
+ read_tags_file(tgid_tags_file, result_config[nac]['tgid_map'])
+ if unit_id_tags_file is not None and os.access(unit_id_tags_file, os.R_OK):
+ read_tags_file(unit_id_tags_file, result_config[nac]['unit_id_map'])
+
+ if 'center_frequency' in configs[nac]:
+ result_config[nac]['center_frequency'] = get_frequency(configs[nac]['center_frequency'])
+ return result_config
+
+def main():
+ import json
+ result = make_config(load_tsv(sys.argv[1]))
+ print (json.dumps(result, indent=4, separators=[',',':'], sort_keys=True))
+
+if __name__ == '__main__':
+ main()
diff --git a/op25/gr-op25_repeater/apps/tx/README-fakecc.txt b/op25/gr-op25_repeater/apps/tx/README-fakecc.txt
new file mode 100644
index 0000000..4d629ce
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/README-fakecc.txt
@@ -0,0 +1,31 @@
+
+Generating and transmitting a fake trunking control channel
+===========================================================
+
+1. After editing, run generate-tsbks.py which should generate
+a file named "p25.out".
+
+2. The tool generates the file packed form; it must be unpacked
+ ./unpack.py -i p25.out -o sym-cc925.dat
+
+3. The unpacked file must be referenced in the json cfg file:
+ .
+ .
+ .
+ "source": "symbols:sym-cc925.dat",
+ .
+ .
+ .
+
+NOTE: in generate_tsbks.py, keys starting with "iden_up"
+are used to define a channel band plan with bandwidth(bw),
+channel spacing, and starting frequency in Hz; TX offset is in
+MHz.
+
+NOTE: with rx.py and multi_tx.py in tandem using the udp option,
+the center frequency must be set in the rx.py trunking TSV
+file equal to the device frequency in the multi_tx config.
+
+As always, the control channel and voice channel frequencies
+must fall inside the band defined by the center freqency and
+sampling rate.
diff --git a/op25/gr-op25_repeater/apps/tx/dstar-cfg.dat b/op25/gr-op25_repeater/apps/tx/dstar-cfg.dat
new file mode 100644
index 0000000..a1451c7
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/dstar-cfg.dat
@@ -0,0 +1,41 @@
+#################################################################################
+#
+# config file for DSTAR TX
+#
+#################################################################################
+#
+# This file is part of OP25
+#
+# This is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# This software is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this software; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#################################################################################
+#
+# NOTE
+#
+# Syntax is unforgiving - no whitespace allowed (outside of comments)
+#
+#################################################################################
+# flags - specify values in hex
+flag1=0
+flag2=0
+flag3=0
+# call sign fields - all have an 8-character limit
+rptcall2=DIRECT
+rptcall1=DIRECT
+urcall=CQCQCQ
+# # # # # # # # # # # # set your callsign in next line
+mycall1=mycall
+# appears to be used as a radio model ID - 4-char limit
+mycall2=OP25
diff --git a/op25/gr-op25_repeater/apps/tx/dv_tx.py b/op25/gr-op25_repeater/apps/tx/dv_tx.py
index d3f6082..c841176 100755
--- a/op25/gr-op25_repeater/apps/tx/dv_tx.py
+++ b/op25/gr-op25_repeater/apps/tx/dv_tx.py
@@ -1,8 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#################################################################################
#
-# Multiprotocol Digital Voice TX (C) Copyright 2017 Max H. Parke KA1RBI
+# Multiprotocol Digital Voice TX (C) Copyright 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
#
# This file is part of OP25
#
@@ -25,8 +25,8 @@
import sys
import os
import math
-from gnuradio import gr, gru, audio, eng_notation
-from gnuradio import filter, blocks, analog, digital
+from gnuradio import gr, audio, eng_notation
+from gnuradio import filter, blocks, analog, digital, fft
from gnuradio.eng_option import eng_option
from optparse import OptionParser
@@ -37,18 +37,25 @@ from math import pi
from op25_c4fm_mod import p25_mod_bf
-RC_FILTER = {'dmr': 'rrc', 'p25': 'rc', 'ysf': 'rrc', 'dstar': None}
+sys.path.append('..')
+from gr_gnuplot import float_sink_f
+
+RC_FILTER = {'dmr': 'rrc', 'p25': 'rc', 'ysf': 'rrc', 'dstar': None, 'nxdn48': 'nxdn48', 'nxdn96': 'nxdn96'}
output_gains = {
'dmr': 5.5,
'dstar': 0.95,
- 'p25': 5.0,
- 'ysf': 5.5
+ 'p25': 4.5,
+ 'ysf': 5.5,
+ 'nxdn48': 1.0,
+ 'nxdn96': 1.0
}
gain_adjust = {
'dmr': 3.0,
'dstar': 7.5,
- 'ysf': 5.0
+ 'ysf': 4.0,
+ 'nxdn48': 1.0,
+ 'nxdn96': 1.0
}
gain_adjust_fullrate = {
'p25': 2.0,
@@ -58,7 +65,9 @@ mod_adjust = { # rough values
'dmr': 0.35,
'dstar': 0.075,
'p25': 0.33,
- 'ysf': 0.42
+ 'ysf': 0.42,
+ 'nxdn48': 1.66667,
+ 'nxdn96': 1.93
}
class my_top_block(gr.top_block):
@@ -79,36 +88,40 @@ class my_top_block(gr.top_block):
parser = OptionParser(option_class=eng_option)
parser.add_option("-a", "--args", type="string", default="", help="device args")
+ parser.add_option("-A", "--alt-modulator-rate", type="int", default=50000, help="when mod rate is not a submutiple of IF rate")
parser.add_option("-b", "--bt", type="float", default=0.5, help="specify bt value")
parser.add_option("-c", "--config-file", type="string", default=None, help="specify the config file name")
parser.add_option("-f", "--file1", type="string", default=None, help="specify the input file slot 1")
parser.add_option("-F", "--file2", type="string", default=None, help="specify the input file slot 2 (DMR)")
parser.add_option("-g", "--gain", type="float", default=1.0, help="input gain")
- parser.add_option("-i", "--if-rate", type="float", default=960000, help="output rate to sdr")
+ parser.add_option("-i", "--if-rate", type="int", default=480000, help="output rate to sdr")
parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp")
+ parser.add_option("-k", "--symbol-sink", type="string", default=None, help="write symbols to file (optional)")
parser.add_option("-N", "--gains", type="string", default=None, help="gain settings")
parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm output device name. E.g., hw:0,0 or /dev/dsp")
parser.add_option("-o", "--output-file", type="string", default=None, help="specify the output file")
- parser.add_option("-p", "--protocol", type="choice", default=None, choices=('dmr', 'dstar', 'p25', 'ysf'), help="specify protocol: dmr, dstar, p25, ysf")
+ parser.add_option("-p", "--protocol", type="choice", default=None, choices=('dmr', 'dstar', 'p25', 'ysf', 'nxdn48', 'nxdn96'), help="specify protocol: dmr, dstar, p25, ysf, nxdn48, nxdn96")
parser.add_option("-q", "--frequency-correction", type="float", default=0.0, help="ppm")
parser.add_option("-Q", "--frequency", type="float", default=0.0, help="Hz")
parser.add_option("-r", "--repeat", action="store_true", default=False, help="input file repeat")
+ parser.add_option("-P", "--plot-audio", action="store_true", default=False, help="scope input")
parser.add_option("-R", "--fullrate-mode", action="store_true", default=False, help="ysf fullrate")
- parser.add_option("-s", "--sample-rate", type="int", default=48000, help="output sample rate")
+ parser.add_option("-s", "--modulator-rate", type="int", default=48000, help="must be submultiple of IF rate - see also -A")
+ parser.add_option("-S", "--alsa-rate", type="int", default=48000, help="sound source/sink sample rate")
parser.add_option("-t", "--test", type="string", default=None, help="test pattern symbol file")
parser.add_option("-v", "--verbose", type="int", default=0, help="additional output")
(options, args) = parser.parse_args()
max_inputs = 1
- if options.protocol is None:
- print 'protocol [-p] option missing'
+ if options.protocol is None:
+ print ('protocol [-p] option missing')
sys.exit(0)
- if options.protocol == 'ysf' or options.protocol == 'dmr':
- assert options.config_file # dmr and ysf require config file ("-c FILENAME" option)
+ if options.protocol == 'ysf' or options.protocol == 'dmr' or options.protocol == 'dstar' or options.protocol.startswith('nxdn'):
+ assert options.config_file # dstar, dmr, ysf, and nxdn require config file ("-c FILENAME" option)
- output_gain = output_gains[options.protocol]
+ output_gain = output_gains[options.protocol]
if options.test: # input file is in symbols of size=char
ENCODER = blocks.file_source(gr.sizeof_char, options.test, True)
@@ -124,7 +137,7 @@ class my_top_block(gr.top_block):
ENCODER = op25_repeater.dstar_tx_sb(options.verbose, options.config_file)
elif options.protocol == 'p25':
ENCODER = op25_repeater.vocoder(True, # 0=Decode,True=Encode
- 0, # Verbose flag
+ False, # Verbose flag
0, # flex amount
"", # udp ip address
0, # udp port
@@ -135,7 +148,9 @@ class my_top_block(gr.top_block):
ENCODER.set_gain_adjust(gain_adjust_fullrate['ysf'])
else:
ENCODER.set_gain_adjust(gain_adjust['ysf'])
- if options.protocol == 'p25':
+ elif options.protocol.startswith('nxdn'):
+ ENCODER = op25_repeater.nxdn_tx_sb(options.verbose, options.config_file, options.protocol == 'nxdn96')
+ if options.protocol == 'p25' and not options.test:
ENCODER.set_gain_adjust(gain_adjust_fullrate[options.protocol])
elif not options.test and not options.protocol == 'ysf':
ENCODER.set_gain_adjust(gain_adjust[options.protocol])
@@ -145,13 +160,16 @@ class my_top_block(gr.top_block):
if options.file2 and options.protocol == 'dmr':
nfiles += 1
if nfiles < max_inputs and not options.test:
- AUDIO = audio.source(options.sample_rate, options.audio_input)
- lpf_taps = filter.firdes.low_pass(1.0, options.sample_rate, 3400.0, 3400 * 0.1, filter.firdes.WIN_HANN)
+ AUDIO = audio.source(options.alsa_rate, options.audio_input)
+ lpf_taps = filter.firdes.low_pass(1.0, options.alsa_rate, 3400.0, 3400 * 0.1, filter.firdes.WIN_HANN)
audio_rate = 8000
- AUDIO_DECIM = filter.fir_filter_fff (int(options.sample_rate / audio_rate), lpf_taps)
+ AUDIO_DECIM = filter.fir_filter_fff (int(options.alsa_rate / audio_rate), lpf_taps)
AUDIO_SCALE = blocks.multiply_const_ff(32767.0 * options.gain)
AUDIO_F2S = blocks.float_to_short()
self.connect(AUDIO, AUDIO_DECIM, AUDIO_SCALE, AUDIO_F2S)
+ if options.plot_audio:
+ PLOT_F = float_sink_f()
+ self.connect(AUDIO, PLOT_F)
if options.file1:
IN1 = blocks.file_source(gr.sizeof_short, options.file1, options.repeat)
@@ -172,24 +190,42 @@ class my_top_block(gr.top_block):
else:
self.connect(AUDIO_F2S, ENCODER2)
- MOD = p25_mod_bf(output_sample_rate = options.sample_rate, dstar = (options.protocol == 'dstar'), bt = options.bt, rc = RC_FILTER[options.protocol])
+ MOD = p25_mod_bf(output_sample_rate = options.modulator_rate, dstar = (options.protocol == 'dstar'), bt = options.bt, rc = RC_FILTER[options.protocol])
AMP = blocks.multiply_const_ff(output_gain)
if options.output_file:
OUT = blocks.file_sink(gr.sizeof_float, options.output_file)
elif not options.args:
- OUT = audio.sink(options.sample_rate, options.audio_output)
+ OUT = audio.sink(options.alsa_rate, options.audio_output)
+ if options.symbol_sink:
+ SYMBOL_SINK = blocks.file_sink(gr.sizeof_char, options.symbol_sink)
if options.protocol == 'dmr' and not options.test:
self.connect(DMR, MOD)
+ if options.symbol_sink:
+ self.connect(DMR, SYMBOL_SINK)
else:
self.connect(ENCODER, MOD)
+ if options.symbol_sink:
+ self.connect(ENCODER, SYMBOL_SINK)
if options.args:
self.setup_sdr_output(options, mod_adjust[options.protocol])
- interp = filter.rational_resampler_fff(options.if_rate / options.sample_rate, 1)
- self.attn = blocks.multiply_const_cc(0.25)
- self.connect(MOD, AMP, interp, self.fm_modulator, self.attn, self.u)
+ f1 = float(options.if_rate) / options.modulator_rate
+ i1 = int(options.if_rate / options.modulator_rate)
+ if f1 - i1 > 1e-3:
+ f1 = float(options.if_rate) / options.alt_modulator_rate
+ i1 = int(options.if_rate / options.alt_modulator_rate)
+ if f1 - i1 > 1e-3:
+ print ('*** Error, sdr rate %d not an integer multiple of alt modulator rate %d - ratio=%f' % (options.if_rate, options.alt_modulator_rate, f1))
+ sys.exit(0)
+ a_resamp = filter.pfb.arb_resampler_fff(options.alt_modulator_rate / float(options.modulator_rate))
+ sys.stderr.write('adding resampler for rate change %d ===> %d\n' % (options.modulator_rate, options.alt_modulator_rate))
+ interp = filter.rational_resampler_fff(options.if_rate / options.alt_modulator_rate, 1)
+ self.connect(MOD, AMP, a_resamp, interp, self.fm_modulator, self.u)
+ else:
+ interp = filter.rational_resampler_fff(options.if_rate // options.modulator_rate, 1)
+ self.connect(MOD, AMP, interp, self.fm_modulator, self.u)
else:
self.connect(MOD, AMP, OUT)
@@ -204,22 +240,21 @@ class my_top_block(gr.top_block):
gain_names = self.u.get_gain_names()
for name in gain_names:
range = self.u.get_gain_range(name)
- print "gain: name: %s range: start %d stop %d step %d" % (name, range[0].start(), range[0].stop(), range[0].step())
+ print ("gain: name: %s range: start %d stop %d step %d" % (name, range[0].start(), range[0].stop(), range[0].step()))
if options.gains:
for tuple in options.gains.split(","):
name, gain = tuple.split(":")
gain = int(gain)
- print "setting gain %s to %d" % (name, gain)
+ print ("setting gain %s to %d" % (name, gain))
self.u.set_gain(gain, name)
- print 'setting sample rate'
self.u.set_sample_rate(options.if_rate)
self.u.set_center_freq(options.frequency)
self.u.set_freq_corr(options.frequency_correction)
#self.u.set_bandwidth(options.if_rate)
if __name__ == "__main__":
- print 'Multiprotocol Digital Voice TX (C) Copyright 2017 Max H. Parke KA1RBI'
+ print ('Multiprotocol Digital Voice TX (C) Copyright 2017-2020 Max H. Parke KA1RBI')
try:
my_top_block().run()
except KeyboardInterrupt:
diff --git a/op25/gr-op25_repeater/apps/tx/generate-tsbks.py b/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
index f3c80ed..fa1eb01 100755
--- a/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
+++ b/op25/gr-op25_repeater/apps/tx/generate-tsbks.py
@@ -1,4 +1,4 @@
-#! /usr/bin/python
+#! /usr/bin/python3
from p25craft import make_fakecc_tsdu
@@ -8,9 +8,13 @@ if __name__ == '__main__':
params = {
'wacn' : 0xbee00,
'system_id': 0x290,
- 'cc_freq': 925000000,
- 'vc_freq': 924900000,
+ 'cc_freq': 924975000,
+ 'vc_freq': 924925000,
'nac': 0x293,
'subsystem_id': 1,
- 'site_id': 1}
+ 'site_id': 1,
+ 'iden_up_bw' : 12500,
+ 'iden_up_tx_offset' : 25, # MHz
+ 'iden_up_spacing' : 12500,
+ 'iden_up_frequency' : 902012500}
make_fakecc_tsdu(params)
diff --git a/op25/gr-op25_repeater/apps/tx/multi_tx.py b/op25/gr-op25_repeater/apps/tx/multi_tx.py
index 3f93b19..6c5c6dc 100755
--- a/op25/gr-op25_repeater/apps/tx/multi_tx.py
+++ b/op25/gr-op25_repeater/apps/tx/multi_tx.py
@@ -1,8 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#################################################################################
#
-# Multiprotocol Digital Voice TX (C) Copyright 2017 Max H. Parke KA1RBI
+# Multiprotocol Digital Voice TX (C) Copyright 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
#
# This file is part of OP25
#
@@ -24,14 +24,15 @@
"""
-Transmit four simultaneous RF channels (dmr, p25, dstar, and ysf)
+Transmit M simultaneous RF channels via N devices
"""
import sys
import os
import math
-from gnuradio import gr, gru, audio, eng_notation
-from gnuradio import filter, blocks, analog, digital
+import json
+from gnuradio import gr, audio, eng_notation
+from gnuradio import filter, blocks, analog, digital, fft
from gnuradio.eng_option import eng_option
from optparse import OptionParser
@@ -43,13 +44,28 @@ from math import pi
from op25_c4fm_mod import p25_mod_bf
-class pipeline(gr.hier_block2):
- def __init__(self, protocol=None, config_file=None, mod_adjust=None, gain_adjust=None, output_gain=None, if_freq=0, if_rate=0, verbose=0, fullrate_mode=False, sample_rate=0, bt=0, alt_input=None):
- gr.hier_block2.__init__(self, "dv_modulator",
+_def_symbol_rate = 4800
+_def_bt = 0.5
+
+def byteify(input): # thx so
+ if sys.version[0] != '2': # hack, must be a better way
+ return input
+ if isinstance(input, dict):
+ return {byteify(key): byteify(value)
+ for key, value in input.iteritems()}
+ elif isinstance(input, list):
+ return [byteify(element) for element in input]
+ elif isinstance(input, unicode):
+ return input.encode('utf-8')
+ else:
+ return input
+
+class pipeline_sb(gr.hier_block2):
+ def __init__(self, protocol=None, config_file=None, gain_adjust=None, verbose=0, fullrate_mode=False, alt_input=None):
+ gr.hier_block2.__init__(self, "dv_encoder",
gr.io_signature(1, 1, gr.sizeof_short), # Input signature
- gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
+ gr.io_signature(1, 1, gr.sizeof_char)) # Output signature
- from dv_tx import RC_FILTER
if protocol == 'dmr':
assert config_file
ENCODER = op25_repeater.ambe_encoder_sb(verbose)
@@ -61,10 +77,11 @@ class pipeline(gr.hier_block2):
alt_input = self
self.connect(alt_input, ENCODER2, (DMR, 1))
elif protocol == 'dstar':
- ENCODER = op25_repeater.dstar_tx_sb(verbose, None)
+ assert config_file
+ ENCODER = op25_repeater.dstar_tx_sb(verbose, config_file)
elif protocol == 'p25':
ENCODER = op25_repeater.vocoder(True, # 0=Decode,True=Encode
- 0, # Verbose flag
+ False, # Verbose flag
0, # flex amount
"", # udp ip address
0, # udp port
@@ -72,8 +89,21 @@ class pipeline(gr.hier_block2):
elif protocol == 'ysf':
assert config_file
ENCODER = op25_repeater.ysf_tx_sb(verbose, config_file, fullrate_mode)
+ elif protocol.startswith('nxdn'):
+ assert config_file
+ ENCODER = op25_repeater.nxdn_tx_sb(verbose, config_file, protocol == 'nxdn96')
ENCODER.set_gain_adjust(gain_adjust)
+ if protocol == 'dmr':
+ self.connect(DMR, self)
+ else:
+ self.connect(self, ENCODER, self)
+class mod_pipeline_bc(gr.hier_block2):
+ def __init__(self, protocol=None, mod_adjust=None, output_gain=None, if_freq=0, if_rate=0, verbose=0, sample_rate=0, bt=0):
+ from dv_tx import RC_FILTER
+ gr.hier_block2.__init__(self, "dv_modulator",
+ gr.io_signature(1, 1, gr.sizeof_char), # Input signature
+ gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
MOD = p25_mod_bf(output_sample_rate = sample_rate, dstar = (protocol == 'dstar'), bt = bt, rc = RC_FILTER[protocol])
AMP = blocks.multiply_const_ff(output_gain)
@@ -83,117 +113,231 @@ class pipeline(gr.hier_block2):
FM_MOD = analog.frequency_modulator_fc (k * mod_adjust)
- if protocol == 'dmr':
- self.connect(DMR, MOD)
- else:
- self.connect(self, ENCODER, MOD)
-
- INTERP = filter.rational_resampler_fff(if_rate / sample_rate, 1)
+ INTERP = filter.rational_resampler_fff(if_rate // sample_rate, 1)
MIXER = blocks.multiply_cc()
LO = analog.sig_source_c(if_rate, analog.GR_SIN_WAVE, if_freq, 1.0, 0)
- self.connect(MOD, AMP, INTERP, FM_MOD, (MIXER, 0))
+ self.connect(self, MOD, AMP, INTERP, FM_MOD, (MIXER, 0))
self.connect(LO, (MIXER, 1))
self.connect(MIXER, self)
-class my_top_block(gr.top_block):
- def __init__(self):
- gr.top_block.__init__(self)
- parser = OptionParser(option_class=eng_option)
+class device(object):
+ def __init__(self, config, tb):
+ self.name = config['name']
+ self.sample_rate = config['rate']
+ self.args = config['args']
+ self.frequency = config['frequency']
+ self.tb = tb
+ self.sum = blocks.add_cc()
+ self.sum_count = 0
+ self.output_throttle = None
- parser.add_option("-a", "--args", type="string", default="", help="device args")
- parser.add_option("-A", "--do-audio", action="store_true", default=False, help="live input audio")
- parser.add_option("-b", "--bt", type="float", default=0.5, help="specify bt value")
- parser.add_option("-f", "--file", type="string", default=None, help="specify the input file (mono 8000 sps S16_LE)")
- parser.add_option("-g", "--gain", type="float", default=1.0, help="input gain")
- parser.add_option("-i", "--if-rate", type="float", default=960000, help="output rate to sdr")
- parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp")
- parser.add_option("-N", "--gains", type="string", default=None, help="gain settings")
- parser.add_option("-o", "--if-offset", type="float", default=100000, help="channel spacing (Hz)")
- parser.add_option("-q", "--frequency-correction", type="float", default=0.0, help="ppm")
- parser.add_option("-Q", "--frequency", type="float", default=0.0, help="Hz")
- parser.add_option("-r", "--repeat", action="store_true", default=False, help="input file repeat")
- parser.add_option("-R", "--fullrate-mode", action="store_true", default=False, help="ysf fullrate")
- parser.add_option("-s", "--sample-rate", type="int", default=48000, help="output sample rate")
- parser.add_option("-v", "--verbose", type="int", default=0, help="additional output")
- (options, args) = parser.parse_args()
+ def get_sum_p(self):
+ seq = self.sum_count
+ self.sum_count += 1
+ return (self.sum, seq)
- assert options.file # input file name (-f filename) required
+class channel(object):
+ def __init__(self, config, dev, verbosity, msgq = None):
+ sys.stderr.write('channel (dev %s): %s\n' % (dev.name, config))
+ self.device = dev
+ self.name = config['name']
+ self.symbol_rate = _def_symbol_rate
+ if 'symbol_rate' in config.keys():
+ self.symbol_rate = config['symbol_rate']
+ self.config = config
- max_inputs = 1
+def get_protocol(chan):
+ # try to autodetect protocol, return None if failed
+ if chan.config['filter_type'].startswith('nxdn'):
+ if chan.symbol_rate == 2400:
+ return 'nxdn48'
+ else:
+ return 'nxdn96'
+ elif chan.config['filter_type'] == 'rc':
+ return 'p25'
+ elif chan.config['filter_type'] == 'gmsk':
+ return 'dstar'
+ elif chan.config['filter_type'] != 'rrc':
+ return None
+ if 'dmr' in chan.config['name'].lower():
+ return 'dmr'
+ if 'ysf' in chan.config['name'].lower():
+ return 'ysf'
+ return None
- from dv_tx import output_gains, gain_adjust, gain_adjust_fullrate, mod_adjust
+def get_source(config, k, audio_source):
+ if k not in config.keys():
+ return None
+ s = config[k]
+ if s.startswith('audio:'):
+ return audio_source
+ elif s.startswith('udp:'): # S16_LE at 8000 rate
+ hostinfo = s.split(':')
+ hostname = hostinfo[1]
+ udp_port = int(hostinfo[2])
+ bufsize = 32000
+ return blocks.udp_source(gr.sizeof_short, hostname, udp_port, payload_size = bufsize)
+ else:
+ return blocks.file_source(gr.sizeof_short, s, repeat = True)
- if options.do_audio:
- AUDIO = audio.source(options.sample_rate, options.audio_input)
- lpf_taps = filter.firdes.low_pass(1.0, options.sample_rate, 3400.0, 3400 * 0.1, filter.firdes.WIN_HANN)
+class tx_block(gr.top_block):
+ def __init__(self, verbosity, config):
+ self.verbosity = verbosity
+ gr.top_block.__init__(self)
+
+ self.configure_devices(config['devices'])
+ self.configure_channels(config['channels'])
+
+ audio_chans = [chan for chan in self.channels if chan.config['source'].startswith('audio:')]
+ if len(audio_chans):
+ AUDIO = audio.source(options.alsa_rate, options.audio_input)
+ lpf_taps = filter.firdes.low_pass(1.0, options.alsa_rate, 3400.0, 3400 * 0.1, filter.firdes.WIN_HANN)
audio_rate = 8000
- AUDIO_DECIM = filter.fir_filter_fff (int(options.sample_rate / audio_rate), lpf_taps)
+ AUDIO_DECIM = filter.fir_filter_fff (int(options.alsa_rate / audio_rate), lpf_taps)
AUDIO_SCALE = blocks.multiply_const_ff(32767.0 * options.gain)
AUDIO_F2S = blocks.float_to_short()
self.connect(AUDIO, AUDIO_DECIM, AUDIO_SCALE, AUDIO_F2S)
- alt_input = AUDIO_F2S
+ audio_source = AUDIO_F2S
else:
- alt_input = None
-
- SUM = blocks.add_cc()
- protocols = 'dmr p25 dstar ysf'.split()
- input_repeat = True
- for i in xrange(len(protocols)):
- SOURCE = blocks.file_source(gr.sizeof_short, options.file, input_repeat)
- protocol = protocols[i]
- if (options.fullrate_mode and protocol == 'ysf') or protocol == 'p25':
- gain_adj = gain_adjust_fullrate[protocols[i]]
+ audio_source = None
+
+ from dv_tx import output_gains, gain_adjust, gain_adjust_fullrate, mod_adjust
+
+ for chan in self.channels:
+ protocol = get_protocol(chan)
+ if protocol is None:
+ sys.stderr.write('failed to detect protocol, ignoring: %s\n' % (cfg))
+ continue
+ cfg = chan.config
+ dev = chan.device
+ modulator_rate = 24000 ## FIXME
+ bt = _def_bt
+ if 'bt' in cfg.keys():
+ bt = cfg['bt']
+ MOD = mod_pipeline_bc(
+ protocol = protocol,
+ output_gain = output_gains[protocol],
+ mod_adjust = mod_adjust[protocol],
+ if_freq = cfg['frequency'] - dev.frequency,
+ if_rate = dev.sample_rate,
+ sample_rate = modulator_rate,
+ bt = bt)
+ if cfg['source'].startswith('symbols:'):
+ filename = cfg['source'].split(':')[1]
+ source = blocks.file_source(gr.sizeof_char, filename, repeat=True)
+ self.connect(source, MOD, dev.get_sum_p())
else:
- gain_adj = gain_adjust[protocols[i]]
- if protocols[i] == 'dmr':
- cfg = 'dmr-cfg.dat'
- elif protocols[i] == 'ysf':
- cfg = 'ysf-cfg.dat'
+ source = get_source(cfg, 'source', audio_source)
+ source2 = get_source(cfg, 'source2', audio_source)
+ fullrate_mode = False ### TODO
+ if (fullrate_mode and protocol == 'ysf') or protocol == 'p25':
+ gain_adj = gain_adjust_fullrate[protocol]
+ else:
+ gain_adj = gain_adjust[protocol]
+ cfgfile = None
+ if protocol in 'dmr ysf dstar'.split():
+ cfgfile = '%s-cfg.dat' % (protocol)
+ elif protocol.startswith('nxdn'):
+ cfgfile = 'nxdn-cfg.dat'
+ CHANNEL = pipeline_sb(
+ protocol = protocol,
+ gain_adjust = gain_adj,
+ fullrate_mode = fullrate_mode,
+ alt_input = source2,
+ verbose = self.verbosity,
+ config_file = cfgfile)
+ self.connect(source, CHANNEL, MOD, dev.get_sum_p())
+ for dev in self.devices:
+ assert dev.sum_count > 0 # device must have at least one valid channel
+ dev.amp = blocks.multiply_const_cc(1.0 / float(dev.sum_count))
+ if dev.output_throttle is not None:
+ self.connect(dev.sum, dev.amp, dev.output_throttle, dev.u)
else:
- cfg = None
-
- CHANNEL = pipeline(
- protocol = protocols[i],
- output_gain = output_gains[protocols[i]],
- gain_adjust = gain_adj,
- mod_adjust = mod_adjust[protocols[i]],
- if_freq = i * options.if_offset,
- if_rate = options.if_rate,
- sample_rate = options.sample_rate,
- bt = options.bt,
- fullrate_mode = options.fullrate_mode,
- alt_input = alt_input,
- config_file = cfg)
- self.connect(SOURCE, CHANNEL, (SUM, i))
-
- self.u = osmosdr.sink (options.args)
- AMP = blocks.multiply_const_cc(1.0 / float(len(protocols)))
- self.setup_sdr_output(options)
-
- self.connect(SUM, AMP, self.u)
-
- def setup_sdr_output(self, options):
- gain_names = self.u.get_gain_names()
+ self.connect(dev.sum, dev.amp, dev.u)
+
+ def configure_devices(self, config):
+ self.devices = []
+ for cfg in config:
+ dev = device(cfg, self)
+ if cfg['args'].startswith('udp:'):
+ self.setup_udp_output(dev, cfg)
+ else:
+ self.setup_sdr_output(dev, cfg)
+ self.devices.append(dev)
+
+ def find_device(self, chan):
+ for dev in self.devices:
+ d = abs(chan['frequency'] - dev.frequency)
+ nf = dev.sample_rate // 2
+ if d + 6250 <= nf:
+ return dev
+ return None
+
+ def configure_channels(self, config):
+ self.channels = []
+ for cfg in config:
+ dev = self.find_device(cfg)
+ if dev is None:
+ sys.stderr.write('* * * Frequency %d not within spectrum band of any device - ignoring!\n' % cfg['frequency'])
+ continue
+ chan = channel(cfg, dev, self.verbosity, msgq=None)
+ self.channels.append(chan)
+
+ def setup_udp_output(self, dev, config):
+ dev.output_throttle = blocks.throttle(gr.sizeof_gr_complex, config['rate'])
+ hostinfo = config['args'].split(':')
+ hostname = hostinfo[1]
+ udp_port = int(hostinfo[2])
+ dev.u = blocks.udp_sink(gr.sizeof_gr_complex, hostname, udp_port)
+
+ def setup_sdr_output(self, dev, config):
+ dev.u = osmosdr.sink (config['args'])
+ gain_names = dev.u.get_gain_names()
for name in gain_names:
- range = self.u.get_gain_range(name)
- print "gain: name: %s range: start %d stop %d step %d" % (name, range[0].start(), range[0].stop(), range[0].step())
- if options.gains:
- for tuple in options.gains.split(","):
- name, gain = tuple.split(":")
+ range = dev.u.get_gain_range(name)
+ print ("gain: name: %s range: start %d stop %d step %d" % (name, range[0].start(), range[0].stop(), range[0].step()))
+ if config['gains']:
+ for t in config['gains'].split(","):
+ name, gain = t.split(":")
gain = int(gain)
- print "setting gain %s to %d" % (name, gain)
- self.u.set_gain(gain, name)
+ print ("setting gain %s to %d" % (name, gain))
+ dev.u.set_gain(gain, name)
+
+ print ('setting sample rate %d' % config['rate'])
+ dev.u.set_sample_rate(config['rate'])
+ print ('setting SDR tuning frequency %d' % config['frequency'])
+ dev.u.set_center_freq(config['frequency'])
+ dev.u.set_freq_corr(config['ppm'])
+
+class tx_main(object):
+ def __init__(self):
+ parser = OptionParser(option_class=eng_option)
+
+ parser.add_option("-c", "--config-file", type="string", default=None, help="specify config file name")
+ parser.add_option("-v", "--verbosity", type="int", default=0, help="additional output")
+ parser.add_option("-p", "--pause", action="store_true", default=False, help="block on startup")
+ (options, args) = parser.parse_args()
+
+ # wait for gdb
+ if options.pause:
+ print ('Ready for GDB to attach (pid = %d)' % (os.getpid(),))
+ raw_input("Press 'Enter' to continue...")
+
+ if options.config_file == '-':
+ config = json.loads(sys.stdin.read())
+ else:
+ config = json.loads(open(options.config_file).read())
+ self.tb = tx_block(options.verbosity, config = byteify(config))
- print 'setting sample rate'
- self.u.set_sample_rate(options.if_rate)
- self.u.set_center_freq(options.frequency)
- self.u.set_freq_corr(options.frequency_correction)
+ def run(self):
+ try:
+ self.tb.run()
+ except KeyboardInterrupt:
+ self.tb.stop()
if __name__ == "__main__":
- print 'Multiprotocol Digital Voice TX (C) Copyright 2017 Max H. Parke KA1RBI'
- try:
- my_top_block().run()
- except KeyboardInterrupt:
- tb.stop()
+ print ('Multiprotocol Digital Voice TX (C) Copyright 2017-2020 Max H. Parke KA1RBI')
+ tx = tx_main()
+ tx.run()
diff --git a/op25/gr-op25_repeater/apps/tx/nxdn-cfg.dat b/op25/gr-op25_repeater/apps/tx/nxdn-cfg.dat
new file mode 100644
index 0000000..65cfe80
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/nxdn-cfg.dat
@@ -0,0 +1,42 @@
+#################################################################################
+#
+# config file for NXDN TX
+#
+#################################################################################
+#
+# NXDN Encoder (C) Copyright 2020 Max H. Parke KA1RBI
+#
+# This file is part of OP25
+#
+# This is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# This software is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this software; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#################################################################################
+#
+# NOTE
+#
+# Syntax is unforgiving - no whitespace allowed (outside of comments)
+#
+#################################################################################
+ran=0
+# LICH value for conventional voice frames
+lich=0x56
+# LICH value for FACCH frames (nxdn96 only - used as filler, every other frame)
+lich2=0x50
+# note, trunking downlinks appear to use:
+# lich = 0x37 for voice frames
+# lich2 = 0x31 for FACCH filler frames, nxdn96 only
+# other common lich values: 0x21, 0x29, 0x2f
+# data field sent in SACCH / FACCH
+acch=01 00 22 00 01 00 00 00 00 00
diff --git a/op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py b/op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py
index ace2be3..4291ee4 100755
--- a/op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py
+++ b/op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py
@@ -30,7 +30,7 @@ P25 C4FM pre-modulation block
with additions for RRC (for dmr/ysf) and dstar gmsk
"""
-from gnuradio import gr, gru, eng_notation
+from gnuradio import gr, eng_notation
from gnuradio.digital import modulation_utils
from gnuradio import filter, digital, blocks
from gnuradio.eng_option import eng_option
@@ -49,14 +49,14 @@ _def_span = 13 #desired number of impulse response coeffs, in units of symbols
_def_gmsk_span = 4
_def_bt = 0.25
-def transfer_function_rx():
+def transfer_function_rx(symbol_rate=_def_symbol_rate):
# p25 c4fm de-emphasis filter
# Specs undefined above 2,880 Hz. It would be nice to have a sharper
# rolloff, but this filter is cheap enough....
xfer = [] # frequency domain transfer function
- for f in xrange(0,4800):
+ for f in range(0,symbol_rate):
# D(f)
- t = pi * f / 4800
+ t = pi * f / symbol_rate
if t < 1e-6:
df = 1.0
else:
@@ -64,9 +64,9 @@ def transfer_function_rx():
xfer.append(df)
return xfer
-def transfer_function_tx():
+def transfer_function_tx(symbol_rate=_def_symbol_rate):
xfer = [] # frequency domain transfer function
- for f in xrange(0, 2881): # specs cover 0 - 2,880 Hz
+ for f in range(0, 2881): # specs cover 0 - 2,880 Hz
# H(f)
if f < 1920:
hf = 1.0
@@ -82,9 +82,9 @@ def transfer_function_tx():
xfer.append(pf * hf)
return xfer
-def transfer_function_dmr():
+def transfer_function_dmr(symbol_rate=_def_symbol_rate):
xfer = [] # frequency domain transfer function
- for f in xrange(0, 2881): # specs cover 0 - 2,880 Hz
+ for f in range(0, 2881): # specs cover 0 - 2,880 Hz
if f < 1920:
hf = 1.0
else:
@@ -94,6 +94,43 @@ def transfer_function_dmr():
xfer = np.sqrt(xfer) # root cosine
return xfer
+def _transfer_function_nxdn(symbol_rate, modulator=False):
+ assert symbol_rate == 2400 or symbol_rate == 4800
+ T = 1.0 / symbol_rate
+ a = 0.2 # rolloff
+ fl = int(0.5+(1-a)/(2*T))
+ fh = int(0.5+(1+a)/(2*T))
+
+ xfer = []
+ for f in range(0, symbol_rate):
+ if f < fl:
+ hf = 1.0
+ elif f >= fl and f <= fh:
+ hf = cos((T/(4*a)) * (2*pi*f - pi*(1-a)/T))
+ else:
+ hf = 0.0
+ x = pi * f * T
+ if f <= fh:
+ if x == 0 or sin(x) == 0:
+ df = 1.0
+ else:
+ if modulator:
+ df = sin(x) / x
+ else: # rx mode: demodulator
+ df = x / sin(x)
+ else:
+ df = 0.0
+ xfer.append(hf * df)
+ return xfer
+
+# rx / demod case
+def transfer_function_nxdn(symbol_rate=_def_symbol_rate):
+ return _transfer_function_nxdn(symbol_rate)
+
+# tx / modulator case
+def transfer_function_nxdn_tx(symbol_rate=_def_symbol_rate):
+ return _transfer_function_nxdn(symbol_rate, modulator=True)
+
class c4fm_taps(object):
"""Generate filter coefficients as per P25 C4FM spec"""
def __init__(self, filter_gain = 1.0, sample_rate=_def_output_sample_rate, symbol_rate=_def_symbol_rate, span=_def_span, generator=transfer_function_tx):
@@ -105,8 +142,8 @@ class c4fm_taps(object):
self.generator = generator
def generate(self):
- impulse_response = np.fft.fftshift(np.fft.irfft(self.generator(), self.sample_rate))
- start = np.argmax(impulse_response) - (self.ntaps-1) / 2
+ impulse_response = np.fft.fftshift(np.fft.irfft(self.generator(symbol_rate=self.symbol_rate), self.sample_rate))
+ start = np.argmax(impulse_response) - (self.ntaps-1) // 2
coeffs = impulse_response[start: start+self.ntaps]
gain = self.filter_gain / sum(coeffs)
return coeffs * gain
@@ -122,8 +159,8 @@ class gmsk_taps(object):
self.span = span
self.bt = bt
- self.samples_per_symbol = self.sample_rate / self.symbol_rate
- self.ntaps = self.span * self.samples_per_symbol
+ self.samples_per_symbol = self.sample_rate // self.symbol_rate
+ self.ntaps = self.span * self.samples_per_symbol
def generate(self):
# from gnuradio gr-digital/python/digital/gmsk.py
@@ -175,14 +212,16 @@ class p25_mod_bf(gr.hier_block2):
@type debug: bool
"""
- gr.hier_block2.__init__(self, "p25_c4fm_mod_bf",
+ gr.hier_block2.__init__(self, "p25_c4fm_mod_bf",
gr.io_signature(1, 1, gr.sizeof_char), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
- input_sample_rate = 4800 # P25 baseband symbol rate
- lcm = gru.lcm(input_sample_rate, output_sample_rate)
- self._interp_factor = int(lcm // input_sample_rate)
- self._decimation = int(lcm // output_sample_rate)
+ input_sample_rate = 4800 # P25/ysf/dmr/dstar baseband symbol rate
+ if rc == 'nxdn48':
+ input_sample_rate = 2400 # only exception is nxdn48 = 2400 rate
+
+ intermediate_rate = 48000
+ self._interp_factor = intermediate_rate // input_sample_rate
self.dstar = dstar
self.bt = bt
@@ -199,15 +238,17 @@ class p25_mod_bf(gr.hier_block2):
self.generator = generator
- assert rc is None or rc == 'rc' or rc == 'rrc'
+ assert rc is None or rc == 'rc' or rc == 'rrc' or rc.startswith('nxdn')
if rc:
- coeffs = filter.firdes.root_raised_cosine(1.0, output_sample_rate, input_sample_rate, 0.2, 91)
+ coeffs = filter.firdes.root_raised_cosine(1.0, intermediate_rate, input_sample_rate, 0.2, 91)
if rc == 'rc':
- coeffs = np.convolve(coeffs, coeffs)
+ coeffs = c4fm_taps(sample_rate=intermediate_rate).generate()
elif self.dstar:
- coeffs = gmsk_taps(sample_rate=output_sample_rate, bt=self.bt).generate()
+ coeffs = gmsk_taps(sample_rate=intermediate_rate, bt=self.bt).generate()
+ elif rc.startswith('nxdn'):
+ coeffs = c4fm_taps(sample_rate=intermediate_rate, generator=transfer_function_nxdn_tx, symbol_rate=input_sample_rate).generate()
elif not rc:
- coeffs = c4fm_taps(sample_rate=output_sample_rate, generator=self.generator).generate()
+ coeffs = c4fm_taps(sample_rate=intermediate_rate, generator=self.generator).generate()
self.filter = filter.interp_fir_filter_fff(self._interp_factor, coeffs)
if verbose:
@@ -217,18 +258,18 @@ class p25_mod_bf(gr.hier_block2):
self._setup_logging()
self.connect(self, self.C2S, self.polarity, self.filter)
- if (self._decimation > 1):
- self.decimator = filter.rational_resampler_fff(1, self._decimation)
- self.connect(self.filter, self.decimator, self)
+ if intermediate_rate != output_sample_rate:
+ self.arb_resamp = filter.pfb.arb_resampler_fff(float(output_sample_rate)/intermediate_rate)
+ self.connect(self.filter, self.arb_resamp, self)
else:
self.connect(self.filter, self)
def _print_verbage(self):
- print "\nModulator:"
- print "interpolation: %d decimation: %d" %(self._interp_factor, self._decimation)
+ print ("\nModulator:")
+ print ("interpolation: %d decimation: %d" %(self._interp_factor, self._decimation))
def _setup_logging(self):
- print "Modulation logging turned on."
+ print ("Modulation logging turned on.")
self.connect(self.C2S,
gr.file_sink(gr.sizeof_float, "tx_chunks2symbols.dat"))
self.connect(self.polarity,
diff --git a/op25/gr-op25_repeater/apps/tx/op25_tx.py b/op25/gr-op25_repeater/apps/tx/op25_tx.py
index 3e7afe4..8d67a47 100755
--- a/op25/gr-op25_repeater/apps/tx/op25_tx.py
+++ b/op25/gr-op25_repeater/apps/tx/op25_tx.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# Copyright 2005,2006,2007 Free Software Foundation, Inc.
#
@@ -41,7 +41,7 @@ running this script when using method B.
"""
from gnuradio import gr, eng_notation, blocks, digital
-from gnuradio import audio, filter, analog
+from gnuradio import audio, filter, analog, fft
from gnuradio.eng_option import eng_option
from optparse import OptionParser
from usrpm import usrp_dbid
diff --git a/op25/gr-op25_repeater/apps/tx/p25craft.py b/op25/gr-op25_repeater/apps/tx/p25craft.py
index dd0f0c9..68ae214 100755
--- a/op25/gr-op25_repeater/apps/tx/p25craft.py
+++ b/op25/gr-op25_repeater/apps/tx/p25craft.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
#
# p25craft.py - utility for crafting APCO P25 packets
#
@@ -52,7 +52,7 @@ quiet = False
outfile = ""
flip = 0x000
quiet = True
-outfile = open('p25.out', 'w')
+outfile = open('p25.out', 'wb')
#####################
@@ -99,7 +99,10 @@ def print_spec(data):
byte = 0
for j in range(4):
byte |= data[i+j] << (6 - j*2)
- outfile.write(struct.pack('B1', (byte ^ flip & 0xff)))
+ s=chr(byte ^ flip & 0xff)
+ if sys.version[0] != '2' and type(s) is str:
+ s = s.encode('latin1')
+ outfile.write(s)
# Split an integer into list of bytes.
def split_bytes(data, len):
@@ -194,26 +197,26 @@ def gf6mult(a, b):
# returns an integer
def rs_36_20_17_encode(data):
matrix = (
- (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,074,037,034,006,002,007,044,064,026,014,026,044,054,013,077,005),
- (0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,004,017,050,024,011,005,030,057,033,003,002,002,015,016,025,026),
- (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,007,023,037,046,056,075,043,045,055,021,050,031,045,027,071,062),
- (0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,026,005,007,063,063,027,063,040,006,004,040,045,047,030,075,007),
- (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,023,073,073,041,072,034,021,051,067,016,031,074,011,021,012,021),
- (0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,024,051,025,023,022,041,074,066,074,065,070,036,067,045,064,001),
- (0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,052,033,014,002,020,006,014,025,052,023,035,074,075,075,043,027),
- (0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,055,062,056,025,073,060,015,030,013,017,020,002,070,055,014,047),
- (0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,054,051,032,065,077,012,054,013,035,032,056,012,075,001,072,063),
- (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,074,041,030,041,043,022,051,006,064,033,003,047,027,012,055,047),
- (0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,054,070,011,003,013,022,016,057,003,045,072,031,030,056,035,022),
- (0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,051,007,072,030,065,054,006,021,036,063,050,061,064,052,001,060),
- (0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,001,065,032,070,013,044,073,024,012,052,021,055,012,035,014,072),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,011,070,005,010,065,024,015,077,022,024,024,074,007,044,007,046),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,006,002,065,011,041,020,045,042,046,054,035,012,040,064,065,033),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,034,031,001,015,044,064,016,024,052,016,006,062,020,013,055,057),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,063,043,025,044,077,063,017,017,064,014,040,074,031,072,054,006),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,071,021,070,044,056,004,030,074,004,023,071,070,063,045,056,043),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,002,001,053,074,002,014,052,074,012,057,024,063,015,042,052,033),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,034,035,002,023,021,027,022,033,064,042,005,073,051,046,073,060))
+ (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o74,0o37,0o34,0o06,0o02,0o07,0o44,0o64,0o26,0o14,0o26,0o44,0o54,0o13,0o77,0o05),
+ (0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o04,0o17,0o50,0o24,0o11,0o05,0o30,0o57,0o33,0o03,0o02,0o02,0o15,0o16,0o25,0o26),
+ (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o07,0o23,0o37,0o46,0o56,0o75,0o43,0o45,0o55,0o21,0o50,0o31,0o45,0o27,0o71,0o62),
+ (0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o26,0o05,0o07,0o63,0o63,0o27,0o63,0o40,0o06,0o04,0o40,0o45,0o47,0o30,0o75,0o07),
+ (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o23,0o73,0o73,0o41,0o72,0o34,0o21,0o51,0o67,0o16,0o31,0o74,0o11,0o21,0o12,0o21),
+ (0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o24,0o51,0o25,0o23,0o22,0o41,0o74,0o66,0o74,0o65,0o70,0o36,0o67,0o45,0o64,0o01),
+ (0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0o52,0o33,0o14,0o02,0o20,0o06,0o14,0o25,0o52,0o23,0o35,0o74,0o75,0o75,0o43,0o27),
+ (0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0o55,0o62,0o56,0o25,0o73,0o60,0o15,0o30,0o13,0o17,0o20,0o02,0o70,0o55,0o14,0o47),
+ (0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0o54,0o51,0o32,0o65,0o77,0o12,0o54,0o13,0o35,0o32,0o56,0o12,0o75,0o01,0o72,0o63),
+ (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0o74,0o41,0o30,0o41,0o43,0o22,0o51,0o06,0o64,0o33,0o03,0o47,0o27,0o12,0o55,0o47),
+ (0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0o54,0o70,0o11,0o03,0o13,0o22,0o16,0o57,0o03,0o45,0o72,0o31,0o30,0o56,0o35,0o22),
+ (0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0o51,0o07,0o72,0o30,0o65,0o54,0o06,0o21,0o36,0o63,0o50,0o61,0o64,0o52,0o01,0o60),
+ (0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0o01,0o65,0o32,0o70,0o13,0o44,0o73,0o24,0o12,0o52,0o21,0o55,0o12,0o35,0o14,0o72),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0o11,0o70,0o05,0o10,0o65,0o24,0o15,0o77,0o22,0o24,0o24,0o74,0o07,0o44,0o07,0o46),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0o06,0o02,0o65,0o11,0o41,0o20,0o45,0o42,0o46,0o54,0o35,0o12,0o40,0o64,0o65,0o33),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0o34,0o31,0o01,0o15,0o44,0o64,0o16,0o24,0o52,0o16,0o06,0o62,0o20,0o13,0o55,0o57),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0o63,0o43,0o25,0o44,0o77,0o63,0o17,0o17,0o64,0o14,0o40,0o74,0o31,0o72,0o54,0o06),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0o71,0o21,0o70,0o44,0o56,0o04,0o30,0o74,0o04,0o23,0o71,0o70,0o63,0o45,0o56,0o43),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0o02,0o01,0o53,0o74,0o02,0o14,0o52,0o74,0o12,0o57,0o24,0o63,0o15,0o42,0o52,0o33),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0o34,0o35,0o02,0o23,0o21,0o27,0o22,0o33,0o64,0o42,0o05,0o73,0o51,0o46,0o73,0o60))
assert data < 2**120
codeword = [0,] * 36
for i in range(36):
@@ -227,18 +230,18 @@ def rs_36_20_17_encode(data):
# returns an integer
def rs_24_12_13_encode(data):
matrix = (
- (1,0,0,0,0,0,0,0,0,0,0,0,062,044,003,025,014,016,027,003,053,004,036,047),
- (0,1,0,0,0,0,0,0,0,0,0,0,011,012,011,011,016,064,067,055,001,076,026,073),
- (0,0,1,0,0,0,0,0,0,0,0,0,003,001,005,075,014,006,020,044,066,006,070,066),
- (0,0,0,1,0,0,0,0,0,0,0,0,021,070,027,045,016,067,023,064,073,033,044,021),
- (0,0,0,0,1,0,0,0,0,0,0,0,030,022,003,075,015,015,033,015,051,003,053,050),
- (0,0,0,0,0,1,0,0,0,0,0,0,001,041,027,056,076,064,021,053,004,025,001,012),
- (0,0,0,0,0,0,1,0,0,0,0,0,061,076,021,055,076,001,063,035,030,013,064,070),
- (0,0,0,0,0,0,0,1,0,0,0,0,024,022,071,056,021,035,073,042,057,074,043,076),
- (0,0,0,0,0,0,0,0,1,0,0,0,072,042,005,020,043,047,033,056,001,016,013,076),
- (0,0,0,0,0,0,0,0,0,1,0,0,072,014,065,054,035,025,041,016,015,040,071,026),
- (0,0,0,0,0,0,0,0,0,0,1,0,073,065,036,061,042,022,017,004,044,020,025,005),
- (0,0,0,0,0,0,0,0,0,0,0,1,071,005,055,003,071,034,060,011,074,002,041,050))
+ (1,0,0,0,0,0,0,0,0,0,0,0,0o62,0o44,0o03,0o25,0o14,0o16,0o27,0o03,0o53,0o04,0o36,0o47),
+ (0,1,0,0,0,0,0,0,0,0,0,0,0o11,0o12,0o11,0o11,0o16,0o64,0o67,0o55,0o01,0o76,0o26,0o73),
+ (0,0,1,0,0,0,0,0,0,0,0,0,0o03,0o01,0o05,0o75,0o14,0o06,0o20,0o44,0o66,0o06,0o70,0o66),
+ (0,0,0,1,0,0,0,0,0,0,0,0,0o21,0o70,0o27,0o45,0o16,0o67,0o23,0o64,0o73,0o33,0o44,0o21),
+ (0,0,0,0,1,0,0,0,0,0,0,0,0o30,0o22,0o03,0o75,0o15,0o15,0o33,0o15,0o51,0o03,0o53,0o50),
+ (0,0,0,0,0,1,0,0,0,0,0,0,0o01,0o41,0o27,0o56,0o76,0o64,0o21,0o53,0o04,0o25,0o01,0o12),
+ (0,0,0,0,0,0,1,0,0,0,0,0,0o61,0o76,0o21,0o55,0o76,0o01,0o63,0o35,0o30,0o13,0o64,0o70),
+ (0,0,0,0,0,0,0,1,0,0,0,0,0o24,0o22,0o71,0o56,0o21,0o35,0o73,0o42,0o57,0o74,0o43,0o76),
+ (0,0,0,0,0,0,0,0,1,0,0,0,0o72,0o42,0o05,0o20,0o43,0o47,0o33,0o56,0o01,0o16,0o13,0o76),
+ (0,0,0,0,0,0,0,0,0,1,0,0,0o72,0o14,0o65,0o54,0o35,0o25,0o41,0o16,0o15,0o40,0o71,0o26),
+ (0,0,0,0,0,0,0,0,0,0,1,0,0o73,0o65,0o36,0o61,0o42,0o22,0o17,0o04,0o44,0o20,0o25,0o05),
+ (0,0,0,0,0,0,0,0,0,0,0,1,0o71,0o05,0o55,0o03,0o71,0o34,0o60,0o11,0o74,0o02,0o41,0o50))
assert data < 2**72
codeword = [0,] * 24
for i in range(24):
@@ -252,22 +255,22 @@ def rs_24_12_13_encode(data):
# returns an integer
def rs_24_16_9_encode(data):
matrix = (
- (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,051,045,067,015,064,067,052,012),
- (0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,057,025,063,073,071,022,040,015),
- (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,005,001,031,004,016,054,025,076),
- (0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,073,007,047,014,041,077,047,011),
- (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,075,015,051,051,017,067,017,057),
- (0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,020,032,014,042,075,042,070,054),
- (0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,002,075,043,005,001,040,012,064),
- (0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,024,074,015,072,024,026,074,061),
- (0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,042,064,007,022,061,020,040,065),
- (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,032,032,055,041,057,066,021,077),
- (0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,065,036,025,007,050,016,040,051),
- (0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,064,006,054,032,076,046,014,036),
- (0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,062,063,074,070,005,027,037,046),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,055,043,034,071,057,076,050,064),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,024,023,023,005,050,070,042,023),
- (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,067,075,045,060,057,024,006,026))
+ (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o51,0o45,0o67,0o15,0o64,0o67,0o52,0o12),
+ (0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0o57,0o25,0o63,0o73,0o71,0o22,0o40,0o15),
+ (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0o05,0o01,0o31,0o04,0o16,0o54,0o25,0o76),
+ (0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0o73,0o07,0o47,0o14,0o41,0o77,0o47,0o11),
+ (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0o75,0o15,0o51,0o51,0o17,0o67,0o17,0o57),
+ (0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0o20,0o32,0o14,0o42,0o75,0o42,0o70,0o54),
+ (0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0o02,0o75,0o43,0o05,0o01,0o40,0o12,0o64),
+ (0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0o24,0o74,0o15,0o72,0o24,0o26,0o74,0o61),
+ (0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0o42,0o64,0o07,0o22,0o61,0o20,0o40,0o65),
+ (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0o32,0o32,0o55,0o41,0o57,0o66,0o21,0o77),
+ (0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0o65,0o36,0o25,0o07,0o50,0o16,0o40,0o51),
+ (0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0o64,0o06,0o54,0o32,0o76,0o46,0o14,0o36),
+ (0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0o62,0o63,0o74,0o70,0o05,0o27,0o37,0o46),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0o55,0o43,0o34,0o71,0o57,0o76,0o50,0o64),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0o24,0o23,0o23,0o05,0o50,0o70,0o42,0o23),
+ (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0o67,0o75,0o45,0o60,0o57,0o24,0o06,0o26))
assert data < 2**96
codeword = [0,] * 24
for i in range(24):
@@ -280,12 +283,12 @@ def rs_24_16_9_encode(data):
# argument is an integer
# returns an integer
def golay_24_12_8_encode(data):
- matrix = (040006165, 020003073, 010007550, 04003664, 02001732,
- 01006631, 0403315, 0201547, 0106706, 045227, 024476, 014353)
+ matrix = (0o40006165, 0o20003073, 0o10007550, 0o4003664, 0o2001732,
+ 0o1006631, 0o403315, 0o201547, 0o106706, 0o45227, 0o24476, 0o14353)
assert data < 2**12
codeword = 0
for i in range(12):
- if data & (04000 >> i):
+ if data & (0o4000 >> i):
codeword ^= matrix[i]
return codeword
@@ -461,7 +464,7 @@ def trellis_3_4_encode(input):
# returns an integer
def crc_ccitt(data):
assert data >= 0
- assert data <= 0xffffffffffffffffffffL
+ assert data <= 0xffffffffffffffffffff
g = (1 << 12) | (1 << 5) | 1
crc = 0;
for i in range(79, -1, -1):
@@ -495,7 +498,7 @@ def crc_9(serial, data):
assert serial >= 0
assert serial <= 0x7f
assert data >= 0
- assert data <= 0xffffffffffffffffffffffffffffffffL
+ assert data <= 0xffffffffffffffffffffffffffffffff
data |= (serial << 128)
g = (1 << 6) | (1 << 4) | (1 << 3) | 1
crc = 0;
@@ -623,7 +626,7 @@ def construct_lc(lco, mfid, svcopt, s, tgid, dst, src):
def construct_es(mi, algid, kid):
text_out("\tEncryption Sync Word:\n")
- assert mi <= 0xffffffffffffffffffL
+ assert mi <= 0xffffffffffffffffff
assert algid <= 0xff
assert kid <= 0xffff
@@ -646,7 +649,7 @@ def construct_tsbk(lb, p, opcode, mfid, arg):
assert p <= 0x1
assert opcode <= 0x3f
assert mfid <= 0xff
- assert arg <= 0xffffffffffffffffL
+ assert arg <= 0xffffffffffffffff
tsbk = lb << 95
tsbk |= p << 94
@@ -879,7 +882,7 @@ def construct_hdu(nac, ss, mi, mfid, algid, kid, tgid):
assert nac <= 0xfff
assert ss <= 0x3
- assert mi <= 0xffffffffffffffffffL
+ assert mi <= 0xffffffffffffffffff
assert algid <= 0xff
assert kid <= 0xffff
assert tgid <= 0xffff
@@ -918,7 +921,7 @@ def construct_ldu1(nac, ss, imbe, lsd, lco, mfid, svcopt, s, tgid, dst, src):
assert nac <= 0xfff
assert ss <= 0x3
- assert imbe <= 0xffffffffffffffffffffffffffffffffffffL
+ assert imbe <= 0xffffffffffffffffffffffffffffffffffff
assert lsd <= 0xffffffff
assert lco <= 0xff
assert mfid <= 0xff
@@ -975,9 +978,9 @@ def construct_ldu2(nac, ss, imbe, lsd, mi, algid, kid):
assert nac <= 0xfff
assert ss <= 0x3
- assert imbe <= 0xffffffffffffffffffffffffffffffffffffL
+ assert imbe <= 0xffffffffffffffffffffffffffffffffffff
assert lsd <= 0xffffffff
- assert mi <= 0xffffffffffffffffffL
+ assert mi <= 0xffffffffffffffffff
assert algid <= 0xff
assert kid <= 0xffff
@@ -1087,11 +1090,11 @@ def construct_tsdu(nac, ss, blocks, mfid, opcode, arg):
assert blocks <= 0x3
assert mfid <= 0xff
assert opcode <= 0x3f
- assert arg <= 0xffffffffffffffffL
+ assert arg <= 0xffffffffffffffff
duid = 0x7
- numss = (56 + (blocks * 98) + 34) / 35
+ numss = (56 + (blocks * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1133,11 +1136,11 @@ def construct_tsdu3(nac, ss, blocks, mfid, opcodes, args):
for opcode in opcodes:
assert opcode <= 0x3f
for arg in args:
- assert arg <= 0xffffffffffffffffL
+ assert arg <= 0xffffffffffffffff
duid = 0x7
- numss = (56 + (blocks * 98) + 34) / 35
+ numss = (56 + (blocks * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1197,7 +1200,7 @@ def construct_cpdu(nac, ss, data, length, an, io, sapid,
data <<= (4 * 8)
data |= packet_crc
- numss = (56 + ((blocks + 1) * 98) + 34) / 35
+ numss = (56 + ((blocks + 1) * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1222,7 +1225,7 @@ def construct_cpdu(nac, ss, data, length, an, io, sapid,
for i in range(blocks):
text_out("\tConfirmed Packet Data Unit Block:\n")
cpdu_block = (data >> (16 * 8 *
- (blocks - i - 1))) & 0xffffffffffffffffffffffffffffffffL
+ (blocks - i - 1))) & 0xffffffffffffffffffffffffffffffff
# More sophisticated serial number generation required
# for retransmissions.
@@ -1279,7 +1282,7 @@ def construct_rpdu(nac, ss, data, length, io, rclass, rtype,
else:
blocks = 0
- numss = (56 + ((blocks + 1) * 98) + 34) / 35
+ numss = (56 + ((blocks + 1) * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1301,7 +1304,7 @@ def construct_rpdu(nac, ss, data, length, io, rclass, rtype,
for i in range(blocks):
text_out("\tResponse Packet Data Unit Block:\n")
rpdu_block = (data >> (12 * 8 *
- (blocks - i - 1))) & 0xffffffffffffffffffffffffL
+ (blocks - i - 1))) & 0xffffffffffffffffffffffff
text_out("\t\tData = %024x\n" % rpdu_block)
# I'm assuming 1/2 rate trellis encoding based on the length
@@ -1345,7 +1348,7 @@ def construct_updu(nac, ss, data, length, io, sapid, mfid, llid, dho):
data <<= (4 * 8)
data |= packet_crc
- numss = (56 + ((blocks + 1) * 98) + 34) / 35
+ numss = (56 + ((blocks + 1) * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1365,7 +1368,7 @@ def construct_updu(nac, ss, data, length, io, sapid, mfid, llid, dho):
for i in range(blocks):
text_out("\tUnconfirmed Packet Data Unit Block:\n")
updu_block = (data >> (12 * 8 *
- (blocks - i - 1))) & 0xffffffffffffffffffffffffL
+ (blocks - i - 1))) & 0xffffffffffffffffffffffff
text_out("\t\tData = %024x\n" % updu_block)
symbols.extend(data_interleave(trellis_1_2_encode(
split_dibits(updu_block, 48))))
@@ -1408,7 +1411,7 @@ def construct_ambt(nac, ss, data, length, io, sapid, mfid, llid, opcode, dbtm):
data <<= (4 * 8)
data |= packet_crc
- numss = (56 + ((blocks + 1) * 98) + 34) / 35
+ numss = (56 + ((blocks + 1) * 98) + 34) // 35
ssyms = (ss,) * numss
text_out("\tDUID = %01x\n" % duid)
@@ -1428,7 +1431,7 @@ def construct_ambt(nac, ss, data, length, io, sapid, mfid, llid, opcode, dbtm):
for i in range(blocks):
text_out("\tMultiple Block Trunking Block:\n")
ambt_block = (data >> (12 * 8 *
- (blocks - i - 1))) & 0xffffffffffffffffffffffffL
+ (blocks - i - 1))) & 0xffffffffffffffffffffffff
text_out("\t\tData = %024x\n" % ambt_block)
symbols.extend(data_interleave(trellis_1_2_encode(
split_dibits(ambt_block, 48))))
@@ -1694,17 +1697,17 @@ def make_fakecc_tsdu(params):
opcodes = []
args = []
op, arg = format_iden_up(0,
- int(12.5 / 0.125),
- (25 * 4),
- int(12.5 / 0.125),
- 902012500/5)
+ params['iden_up_bw'] // 125,
+ params['iden_up_tx_offset'] * 4,
+ params['iden_up_spacing'] // 125,
+ params['iden_up_frequency'] // 5)
opcodes.append(op)
args.append(arg)
op, arg = format_network_status_broadcast(
0,
params['wacn'],
params['system_id'],
- (params['cc_freq'] - 902012500) / 12500,
+ (params['cc_freq'] - params['iden_up_frequency']) // params['iden_up_spacing'],
0x70)
opcodes.append(op)
args.append(arg)
@@ -1713,7 +1716,7 @@ def make_fakecc_tsdu(params):
params['system_id'],
params['subsystem_id'],
params['site_id'],
- (params['cc_freq'] - 902012500) / 12500,
+ (params['cc_freq'] - params['iden_up_frequency']) // params['iden_up_spacing'],
0x70)
opcodes.append(op)
args.append(arg)
@@ -1723,7 +1726,7 @@ def make_fakecc_tsdu(params):
mfid = 0
construct_tsdu3(nac, ss, blocks, mfid, opcodes, args)
ga = 666
- ch = (params['vc_freq'] - 902012500) / 12500
+ ch = (params['vc_freq'] - params['iden_up_frequency']) // params['iden_up_spacing']
opcode, args = format_group_voice_channel_grant_update(ch, ga, ch, ga)
construct_tsdu (nac, ss, blocks, mfid, opcode, args)
@@ -1849,7 +1852,7 @@ if __name__ == "__main__":
assert options.nac <= 0xfff
assert options.ss <= 0b11
- assert options.mi <= 0xffffffffffffffffffL
+ assert options.mi <= 0xffffffffffffffffff
assert options.mfid <= 0xff
assert options.algid <= 0xff
assert options.kid <= 0xffff
@@ -1858,10 +1861,10 @@ if __name__ == "__main__":
assert options.src <= 0xffffff
assert options.dst <= 0xffffff
assert options.lsd <= 0xffffffff
- assert options.lsd1 <= 0xffff
- assert options.lsd2 <= 0xffff
+ assert options.lsd1 is None or options.lsd1 <= 0xffff
+ assert options.lsd2 is None or options.lsd2 <= 0xffff
assert options.pri <= 0x7
- assert options.svcopt <= 0xff
+ assert options.svcopt is None or options.svcopt <= 0xff
assert options.ntsbk >= 1
assert options.ntsbk <= 3
assert options.sapid <= 0x3f
@@ -1872,7 +1875,7 @@ if __name__ == "__main__":
assert options.rtype <= 0x7
assert options.rstatus <= 0x7
assert options.ns <= 0x7
- assert options.arg <= 0xffffffffffffffffL
+ assert options.arg <= 0xffffffffffffffff
if options.quiet:
quiet = True
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/1011.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/1011.pattern
new file mode 100644
index 0000000..2f10ee0
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/1011.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/afc1011.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/afc1011.pattern
new file mode 100644
index 0000000..1a11aaf
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/afc1011.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/bercalhex.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/bercalhex.pattern
new file mode 100644
index 0000000..d7ecc70
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/bercalhex.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/busyhex.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/busyhex.pattern
new file mode 100644
index 0000000..52ccd68
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/busyhex.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/idlehex.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/idlehex.pattern
new file mode 100644
index 0000000..89d1d3d
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/idlehex.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/silencehex.pattern b/op25/gr-op25_repeater/apps/tx/testpatterns/silencehex.pattern
new file mode 100644
index 0000000..051c5d2
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/silencehex.pattern
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/1011hex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/1011hex.dat
new file mode 100644
index 0000000..3983736
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/1011hex.dat
@@ -0,0 +1,24 @@
+557 5F5 FF7 7FF 293 554 7BC B19 4D0 DCE 24A 124
+0D4 33C 0BE 1B9 184 4FC C16 296 276 0E4 E24 A10
+90D 433 C0B E1B 918 44C FC1 629 627 60E C00 000
+000 003 892 849 0D4 33C 02F 86E 461 13F C16 294
+89D 839 000 000 001 C38 24A 124 350 CF0 2F8 6E4
+184 4FF 058 A58 9D8 3B0 000 000 007 0E2 4A1 240
+D43 3C0 BE1 B91 844 FF0 162 962 760 E6D E5D 548
+ADE 389 284 90D 433 C08 F86 E46 113 FC1 629 624
+D83 BA1 41C 2D2 BA3 890 A12 435 0CF 02F 86E 460
+44F F05 8A5 89D 839 4C8 FB0 235 A4E 24A 124 350
+33C 0BE 1B9 184 4FF 058 296 276 0EC 000 000 00C
+892 849 0D4 33C 0BE 1B8 461 13F C16 296 276 0E4
+557 5F5 FF7 7FF 293 AB8 A4E FB0 9A8 ACE 24A 124
+0D4 33C 0BE 1B9 184 4FC C16 296 276 0EC E24 A10
+90D 433 C0B E1B 918 44C FC1 629 627 60E 400 000
+000 003 892 849 0D4 33C 02F 86E 461 13F C16 294
+89D 83B 000 000 000 038 24A 124 350 CF0 2F8 6E4
+184 4FF 058 A58 9D8 390 000 000 000 0E2 4A1 240
+D43 3C0 BE1 B91 844 FF0 162 962 760 EE0 E00 000
+000 389 284 90D 433 C08 F86 E46 113 FC1 629 624
+D83 9AE 8B4 8B6 493 890 A12 435 0CF 02F 86E 460
+44F F05 8A5 89D 83B 9A8 F4F 1FD 60E 24A 124 350
+33C 0BE 1B9 184 4FF 058 296 276 0E4 000 000 00C
+892 849 0D4 33C 0BE 1B8 461 13F C16 296 276 0EC
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/afc1011hex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/afc1011hex.dat
new file mode 100644
index 0000000..5da20de
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/afc1011hex.dat
@@ -0,0 +1,24 @@
+557 5F5 FF7 7FF 293 557 7BC B19 4D0 DCE 24A 127
+0D4 33C 0BE 1B9 184 4FF C16 296 276 0E4 E24 A13
+90D 433 C0B E1B 918 44F FC1 629 627 60E C00 003
+000 003 892 849 0D4 33F 02F 86E 461 13F C16 297
+89D 839 000 000 001 C3B 24A 124 350 CF0 2F8 6E7
+184 4FF 058 A58 9D8 3B3 000 000 007 0E2 4A1 243
+D43 3C0 BE1 B91 844 FF3 162 962 760 E6D E5D 54B
+ADE 389 284 90D 433 C0B F86 E46 113 FC1 629 627
+D83 BA1 41C 2D2 BA3 893 A12 435 0CF 02F 86E 463
+44F F05 8A5 89D 839 4CB FB0 235 A4E 24A 124 353
+33C 0BE 1B9 184 4FF 05B 296 276 0EC 000 000 00F
+892 849 0D4 33C 0BE 1BB 461 13F C16 296 276 0E7
+557 5F5 FF7 7FF 293 ABB A4E FB0 9A8 ACE 24A 127
+0D4 33C 0BE 1B9 184 4FF C16 296 276 0EC E24 A13
+90D 433 C0B E1B 918 44F FC1 629 627 60E 400 003
+000 003 892 849 0D4 33F 02F 86E 461 13F C16 297
+89D 83B 000 000 000 03B 24A 124 350 CF0 2F8 6E7
+184 4FF 058 A58 9D8 393 000 000 000 0E2 4A1 243
+D43 3C0 BE1 B91 844 FF3 162 962 760 EE0 E00 003
+000 389 284 90D 433 C0B F86 E46 113 FC1 629 627
+D83 9AE 8B4 8B6 493 893 A12 435 0CF 02F 86E 463
+44F F05 8A5 89D 83B 9AB F4F 1FD 60E 24A 124 353
+33C 0BE 1B9 184 4FF 05B 296 276 0E4 000 000 00F
+892 849 0D4 33C 0BE 1BB 461 13F C16 296 276 0EF
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/bercalhex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/bercalhex.dat
new file mode 100644
index 0000000..12a037c
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/bercalhex.dat
@@ -0,0 +1,24 @@
+557 5E5 FF7 6FF 292 554 7AC B19 5D0 DCF 24A 134
+0D4 23C 0BF 1B9 194 4FC D16 297 276 0F4 E24 B10
+90C 433 C1B E1B 818 44D FC1 639 627 70E C01 000
+010 003 992 848 0D4 32C 02F 96E 460 13F C06 294
+99D 838 000 010 001 D38 24B 124 340 CF0 3F8 6E5
+184 4EF 058 B58 9D9 3B0 010 000 107 0E3 4A1 250
+D43 2C0 BE0 B91 854 FF0 062 963 760 E7D E5D 448
+ADF 389 294 90D 533 C09 F86 E56 113 EC1 628 624
+D93 BA1 51C 2D3 BA3 880 A12 535 0CE 02F 87E 460
+54F F04 8A5 88D 839 5C8 FB1 235 A5E 24A 024 351
+33C 0AE 1B9 084 4FE 058 286 276 1EC 001 000 01C
+892 949 0D5 33C 0AE 1B8 561 13E C16 286 276 1E4
+556 5F5 FE7 7FF 393 AB9 A4E FA0 9A8 BCE 24B 124
+0C4 33C 1BE 1B8 184 4EC C16 396 277 0EC E34 A10
+80D 432 C0B E0B 918 54C FC0 629 637 60E 500 001
+000 013 892 949 0D5 33C 03F 86E 561 13E C16 284
+89D 93B 001 000 010 038 34A 125 350 CE0 2F8 7E4
+185 4FF 048 A58 8D8 391 000 010 000 1E2 4A0 240
+D53 3C0 AE1 B90 844 FE0 162 862 761 EE0 E10 000
+100 388 284 91D 433 D08 F87 E46 103 FC1 729 625
+D83 9BE 8B4 9B6 492 890 A02 435 1CF 02E 86E 470
+44F E05 8A4 89D 82B 9A8 E4F 1FC 60E 25A 124 250
+33D 0BE 1A9 184 5FF 059 296 266 0E4 100 001 00C
+882 849 1D4 33D 0BE 1A8 461 03F C17 296 266 0EC
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/busyhex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/busyhex.dat
new file mode 100644
index 0000000..aa2cc16
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/busyhex.dat
@@ -0,0 +1,24 @@
+557 5F5 FF7 7FF 293 555 7BC B19 4D0 DCE 24A 125
+0D4 33C 0BE 1B9 184 4FD C16 296 276 0E4 E24 A11
+90D 433 C0B E1B 918 44D FC1 629 627 60E C00 001
+000 003 892 849 0D4 33D 02F 86E 461 13F C16 295
+89D 839 000 000 001 C39 24A 124 350 CF0 2F8 6E5
+184 4FF 058 A58 9D8 3B1 000 000 007 0E2 4A1 241
+D43 3C0 BE1 B91 844 FF1 162 962 760 E6D E5D 549
+ADE 389 284 90D 433 C09 F86 E46 113 FC1 629 625
+D83 BA1 41C 2D2 BA3 891 A12 435 0CF 02F 86E 461
+44F F05 8A5 89D 839 4C9 FB0 235 A4E 24A 124 351
+33C 0BE 1B9 184 4FF 059 296 276 0EC 000 000 00D
+892 849 0D4 33C 0BE 1B9 461 13F C16 296 276 0E5
+557 5F5 FF7 7FF 293 AB9 A4E FB0 9A8 ACE 24A 125
+0D4 33C 0BE 1B9 184 4FD C16 296 276 0EC E24 A11
+90D 433 C0B E1B 918 44D FC1 629 627 60E 400 001
+000 003 892 849 0D4 33D 02F 86E 461 13F C16 295
+89D 83B 000 000 000 039 24A 124 350 CF0 2F8 6E5
+184 4FF 058 A58 9D8 391 000 000 000 0E2 4A1 241
+D43 3C0 BE1 B91 844 FF1 162 962 760 EE0 E00 001
+000 389 284 90D 433 C09 F86 E46 113 FC1 629 625
+D83 9AE 8B4 8B6 493 891 A12 435 0CF 02F 86E 461
+44F F05 8A5 89D 83B 9A9 F4F 1FD 60E 24A 124 351
+33C 0BE 1B9 184 4FF 059 296 276 0E4 000 000 00D
+892 849 0D4 33C 0BE 1B9 461 13F C16 296 276 0ED
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/idlehex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/idlehex.dat
new file mode 100644
index 0000000..859ece8
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/idlehex.dat
@@ -0,0 +1,24 @@
+557 5F5 FF7 7FF 293 557 7BC B19 4D0 DCE 24A 127
+0D4 33C 0BE 1B9 184 4FF C16 296 276 0E4 E24 A13
+90D 433 C0B E1B 918 44F FC1 629 627 60E C00 003
+000 003 892 849 0D4 33F 02F 86E 461 13F C16 297
+89D 839 000 000 001 C3B 24A 124 350 CF0 2F8 6E7
+184 4FF 058 A58 9D8 3B3 000 000 007 0E2 4A1 243
+D43 3C0 BE1 B91 844 FF3 162 962 760 E6D E5D 54B
+ADE 389 284 90D 433 C0B F86 E46 113 FC1 629 627
+D83 BA1 41C 2D2 BA3 893 A12 435 0CF 02F 86E 463
+44F F05 8A5 89D 839 4CB FB0 235 A4E 24A 124 353
+33C 0BE 1B9 184 4FF 05B 296 276 0EC 000 000 00F
+892 849 0D4 33C 0BE 1BB 461 13F C16 296 276 0E7
+557 5F5 FF7 7FF 293 ABB A4E FB0 9A8 ACE 24A 127
+0D4 33C 0BE 1B9 184 4FF C16 296 276 0EC E24 A13
+90D 433 C0B E1B 918 44F FC1 629 627 60E 400 003
+000 003 892 849 0D4 33F 02F 86E 461 13F C16 297
+89D 83B 000 000 000 03F 24A 124 350 CF0 2F8 6E7
+184 4FF 058 A58 9D8 393 000 000 000 0E2 4A1 243
+D43 3C0 BE1 B91 844 FF3 162 962 760 EE0 E00 003
+000 389 284 90D 433 C0B F86 E46 113 FC1 629 627
+D83 9AE 8B4 8B6 493 893 A12 435 0CF 02F 86E 463
+44F F05 8A5 89D 83B 9AB F4F 1FD 60E 24A 124 353
+33C 0BE 1B9 184 4FF 05B 296 276 0E4 000 000 00F
+892 849 0D4 33C 0BE 1BB 461 13F C16 296 276 0EF
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/make-bin.py b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/make-bin.py
new file mode 100755
index 0000000..997c956
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/make-bin.py
@@ -0,0 +1,25 @@
+#! /usr/bin/env python
+
+"""
+utility program to make binary symbol files
+
+reads source file (stdin); writes binary file to stdout
+
+"""
+
+import sys
+
+s = sys.stdin.read()
+s= s.replace(' ', '')
+s= s.replace('\n', '')
+s = s.strip()
+
+dibits = ''
+
+while s:
+ s0 = int(s[0], 16)
+ s = s[1:]
+ dibits += chr(s0>>2)
+ dibits += chr(s0&3)
+
+sys.stdout.write(dibits)
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/sources/silencehex.dat b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/silencehex.dat
new file mode 100644
index 0000000..c4cca78
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/sources/silencehex.dat
@@ -0,0 +1,24 @@
+557 5F5 FF7 7FF 8A2 540 FF8 BAA 959 E5A 18B A16
+DE2 E82 693 63D 981 F98 F88 EC6 2B8 011 B10 BA0
+5DE 2E8 269 363 D98 1F8 6F8 8EC 62B 801 800 000
+000 006 C42 E85 DE2 E80 9A4 D8F 660 7E6 F88 EC4
+8AE 004 000 000 001 C6C 10B A17 78B A09 A4D 8F4
+981 F9B E23 B18 AE0 060 000 000 007 1B1 0BA 174
+E2E 826 936 3D9 81F 9BC 88E C62 B80 12D E5D 548
+ADE 6C4 2E8 5DE 2E8 268 4D8 F66 07E 6F8 8EC 628
+E00 6A1 41C 2D2 BA6 C40 BA1 778 BA0 9A4 D8F 660
+1F9 BE2 3B1 8AE 004 4C8 FB0 235 A5B 10B A17 788
+E82 693 63D 981 F9B E20 EC6 2B8 018 000 000 018
+C42 E85 DE2 E82 693 63C 660 7E6 F88 EC6 2B8 010
+557 5F5 FF7 7FF 293 AB8 A4E FB0 9A8 ADB 10B A14
+DE2 E82 693 63D 981 F98 F88 EC6 2B8 019 B10 BA0
+5DE 2E8 269 363 D98 1F8 6F8 8EC 62B 801 000 000
+000 006 C42 E85 DE2 E80 9A4 D8F 660 7E6 F88 EC4
+8AE 006 000 000 000 06C 10B A17 78B A09 A4D 8F4
+981 F9B E23 B18 AE0 040 000 000 000 1B1 0BA 174
+E2E 826 936 3D9 81F 9BC 88E C62 B80 1A0 E00 000
+000 6C4 2E8 5DE 2E8 268 4D8 F66 07E 6F8 8EC 628
+E00 4AE 8B4 8B6 496 C40 BA1 778 BA0 9A4 D8F 660
+1F9 BE2 3B1 8AE 006 9A8 F4F 1FD 61B 10B A17 788
+E82 693 63D 981 F9B E20 EC6 2B8 010 000 000 018
+C42 E85 DE2 E82 693 63C 660 7E6 F88 EC6 2B8 018
diff --git a/op25/gr-op25_repeater/apps/tx/testpatterns/test.wav b/op25/gr-op25_repeater/apps/tx/testpatterns/test.wav
new file mode 100644
index 0000000..f4f1bc6
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/tx/testpatterns/test.wav
Binary files differ
diff --git a/op25/gr-op25_repeater/apps/tx/unpack.py b/op25/gr-op25_repeater/apps/tx/unpack.py
index 7cbf05b..0a8f0ad 100755
--- a/op25/gr-op25_repeater/apps/tx/unpack.py
+++ b/op25/gr-op25_repeater/apps/tx/unpack.py
@@ -1,5 +1,5 @@
-#!/usr/bin/env python
-from gnuradio import gr, gru, audio, eng_notation, blocks
+#!/usr/bin/env python3
+from gnuradio import gr, audio, eng_notation, blocks
from gnuradio.eng_option import eng_option
from optparse import OptionParser
diff --git a/op25/gr-op25_repeater/apps/tx/ysf-cfg.dat b/op25/gr-op25_repeater/apps/tx/ysf-cfg.dat
index b57e151..fb5a358 100644
--- a/op25/gr-op25_repeater/apps/tx/ysf-cfg.dat
+++ b/op25/gr-op25_repeater/apps/tx/ysf-cfg.dat
@@ -48,7 +48,7 @@ voip=0
# call sign data fields (10 byte, except rem12 and rem34 are five byte)
#################################################################################
dest=**********
-src=SRC
+src=KA1RBI
down=down1
up=up1
rem12=rem12
diff --git a/op25/gr-op25_repeater/apps/ui-settings.json b/op25/gr-op25_repeater/apps/ui-settings.json
new file mode 100644
index 0000000..b664cc0
--- /dev/null
+++ b/op25/gr-op25_repeater/apps/ui-settings.json
@@ -0,0 +1,34 @@
+{
+ "valSystemFont": "24",
+ "valTagFont": "24",
+ "valFontStyle": "normal",
+ "sc1": "police pd sheriff so swat law",
+ "sc2": "fd fire",
+ "sc3": "ac amr ccco pw",
+ "sc4": "",
+ "log_len": "2500",
+ "color_main_tag": true,
+ "color_main_sys": false,
+ "smartcolors": true,
+ "log_cc": true,
+ "log_cf": false,
+ "log_tu": false,
+ "log_rx": false,
+ "show_adj": false,
+ "je_joins": true,
+ "je_calls": false,
+ "je_deny": true,
+ "je_log": true,
+ "hide_enc": false,
+ "trailing_zeros": true,
+ "selDispMode": "dark",
+ "acc1": "#790000",
+ "acc2": "#004364",
+ "sysColor": "#3d81e7",
+ "valColor": "#00ffff",
+ "btnColor": "#20ffff",
+ "unk_default": "99",
+ "ani_speed": "250",
+ "showBandPlan": true,
+ "showSlot": true
+} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/apps/util/arb-resample.py b/op25/gr-op25_repeater/apps/util/arb-resample.py
index 56a762f..a0fccbe 100755
--- a/op25/gr-op25_repeater/apps/util/arb-resample.py
+++ b/op25/gr-op25_repeater/apps/util/arb-resample.py
@@ -1,8 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
import sys
import math
-from gnuradio import gr, gru, audio, eng_notation, filter, blocks
+from gnuradio import gr, audio, eng_notation, filter, blocks
from gnuradio import analog, digital
from gnuradio.eng_option import eng_option
from optparse import OptionParser
diff --git a/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py b/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
index 051ddf0..65ccec6 100755
--- a/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
+++ b/op25/gr-op25_repeater/apps/util/cqpsk-demod-file.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# (C) Copyright 2010, 2014 Max H. Parke, KA1RBI
@@ -16,8 +16,8 @@
import sys
import os
import math
-from gnuradio import gr, gru, audio, eng_notation
-from gnuradio import filter, blocks, analog, digital
+from gnuradio import gr, audio, eng_notation
+from gnuradio import filter, blocks, analog, digital, fft
from gnuradio.eng_option import eng_option
from optparse import OptionParser
diff --git a/op25/gr-op25_repeater/include/op25_repeater/CMakeLists.txt b/op25/gr-op25_repeater/include/op25_repeater/CMakeLists.txt
index 0fbd32c..0e3335e 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/CMakeLists.txt
+++ b/op25/gr-op25_repeater/include/op25_repeater/CMakeLists.txt
@@ -25,6 +25,10 @@ install(FILES
vocoder.h
gardner_costas_cc.h
p25_frame_assembler.h
+ frame_assembler.h
ambe_encoder_sb.h
+ ysf_tx_sb.h
+ dstar_tx_sb.h
+ nxdn_tx_sb.h
fsk4_slicer_fb.h DESTINATION include/op25_repeater
)
diff --git a/op25/gr-op25_repeater/include/op25_repeater/ambe_encoder_sb.h b/op25/gr-op25_repeater/include/op25_repeater/ambe_encoder_sb.h
index 1bfe061..22bdf87 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/ambe_encoder_sb.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/ambe_encoder_sb.h
@@ -47,7 +47,7 @@ namespace gr {
* creating new instances.
*/
static sptr make(int versbose_flag);
- virtual void set_gain_adjust(float gain_adjust) {}
+ virtual void set_gain_adjust(float gain_adjust) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/include/op25_repeater/dstar_tx_sb.h b/op25/gr-op25_repeater/include/op25_repeater/dstar_tx_sb.h
index 8564feb..be652d3 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/dstar_tx_sb.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/dstar_tx_sb.h
@@ -48,7 +48,7 @@ namespace gr {
* creating new instances.
*/
static sptr make(int versbose_flag, const char * conf_file);
- virtual void set_gain_adjust(float gain_adjust) {}
+ virtual void set_gain_adjust(float gain_adjust) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/include/op25_repeater/frame_assembler.h b/op25/gr-op25_repeater/include/op25_repeater/frame_assembler.h
new file mode 100644
index 0000000..cb86b00
--- /dev/null
+++ b/op25/gr-op25_repeater/include/op25_repeater/frame_assembler.h
@@ -0,0 +1,62 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2017 Max H. Parke KA1RBI
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_H
+#define INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_H
+
+#include <op25_repeater/api.h>
+#include <gnuradio/block.h>
+#include <gnuradio/msg_queue.h>
+
+namespace gr {
+ namespace op25_repeater {
+
+ /*!
+ * \brief <+description of block+>
+ * \ingroup op25_repeater
+ *
+ */
+ class OP25_REPEATER_API frame_assembler : virtual public gr::block
+ {
+ public:
+ typedef boost::shared_ptr<frame_assembler> sptr;
+
+ /*!
+ * \brief Return a shared_ptr to a new instance of op25_repeater::frame_assembler.
+ *
+ * To avoid accidental use of raw pointers, op25_repeater::frame_assembler's
+ * constructor is in a private implementation
+ * class. op25_repeater::frame_assembler::make is the public interface for
+ * creating new instances.
+ */
+ static sptr make(const char* options, int debug, gr::msg_queue::sptr queue, int msgq_id);
+ virtual void set_xormask(const char*p) = 0;
+ virtual void set_nac(int nac) = 0;
+ virtual void set_slotid(int slotid) = 0;
+ virtual void insert_whitelist(int grpaddr) = 0;
+ virtual void insert_blacklist(int grpaddr) = 0;
+ };
+
+ } // namespace op25_repeater
+} // namespace gr
+
+#endif /* INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_H */
+
diff --git a/op25/gr-op25_repeater/include/op25_repeater/gardner_costas_cc.h b/op25/gr-op25_repeater/include/op25_repeater/gardner_costas_cc.h
index 261ca11..07c0d3f 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/gardner_costas_cc.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/gardner_costas_cc.h
@@ -47,7 +47,14 @@ namespace gr {
* creating new instances.
*/
static sptr make(float samples_per_symbol, float gain_mu, float gain_omega, float alpha, float beta, float max_freq, float min_freq);
- virtual void set_omega(float omega) {}
+ virtual void set_omega(float omega) = 0;
+ virtual float get_freq_error(void) = 0;
+ virtual int get_error_band(void) = 0;
+ virtual void set_muted(bool) = 0;
+ virtual bool is_muted(void) = 0;
+ virtual void set_tdma(bool) = 0;
+ virtual bool is_tdma(void) = 0;
+ virtual void enable_sync_plot(bool) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/include/op25_repeater/nxdn_tx_sb.h b/op25/gr-op25_repeater/include/op25_repeater/nxdn_tx_sb.h
new file mode 100644
index 0000000..8c29fb4
--- /dev/null
+++ b/op25/gr-op25_repeater/include/op25_repeater/nxdn_tx_sb.h
@@ -0,0 +1,58 @@
+/* -*- c++ -*- */
+/*
+ * DMR Encoder (C) Copyright 2017 Max H. Parke KA1RBI
+ * This file is part of OP25
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef INCLUDED_OP25_REPEATER_NXDN_TX_SB_H
+#define INCLUDED_OP25_REPEATER_NXDN_TX_SB_H
+
+#include <op25_repeater/api.h>
+#include <gnuradio/block.h>
+
+namespace gr {
+ namespace op25_repeater {
+
+ /*!
+ * \brief <+description of block+>
+ * \ingroup op25_repeater
+ *
+ */
+ class OP25_REPEATER_API nxdn_tx_sb : virtual public gr::block
+ {
+ public:
+ typedef boost::shared_ptr<nxdn_tx_sb> sptr;
+
+ /*!
+ * \brief Return a shared_ptr to a new instance of op25_repeater::nxdn_tx_sb.
+ *
+ * To avoid accidental use of raw pointers, op25_repeater::nxdn_tx_sb's
+ * constructor is in a private implementation
+ * class. op25_repeater::nxdn_tx_sb::make is the public interface for
+ * creating new instances.
+ */
+ static sptr make(int versbose_flag, const char * conf_file, bool nxdn96_mode);
+ virtual void set_gain_adjust(float gain_adjust) = 0;
+ };
+
+ } // namespace op25_repeater
+} // namespace gr
+
+#endif /* INCLUDED_OP25_REPEATER_NXDN_TX_SB_H */
+
diff --git a/op25/gr-op25_repeater/include/op25_repeater/p25_frame_assembler.h b/op25/gr-op25_repeater/include/op25_repeater/p25_frame_assembler.h
index d2c24ef..9851b8e 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/p25_frame_assembler.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/p25_frame_assembler.h
@@ -47,9 +47,10 @@ namespace gr {
* class. op25_repeater::p25_frame_assembler::make is the public interface for
* creating new instances.
*/
- static sptr make(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma);
- virtual void set_xormask(const char*p) {}
- virtual void set_slotid(int slotid) {}
+ static sptr make(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma, int msgq_id);
+ virtual void set_xormask(const char*p) = 0;
+ virtual void set_nac(int nac) = 0;
+ virtual void set_slotid(int slotid) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/include/op25_repeater/vocoder.h b/op25/gr-op25_repeater/include/op25_repeater/vocoder.h
index ce271e4..e1ec414 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/vocoder.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/vocoder.h
@@ -47,7 +47,7 @@ namespace gr {
* creating new instances.
*/
static sptr make(bool encode_flag, bool verbose_flag, int stretch_amt, char* udp_host, int udp_port, bool raw_vectors_flag);
- virtual void set_gain_adjust(float gain_adjust) {}
+ virtual void set_gain_adjust(float gain_adjust) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/include/op25_repeater/ysf_tx_sb.h b/op25/gr-op25_repeater/include/op25_repeater/ysf_tx_sb.h
index 570fbc3..06d6a64 100644
--- a/op25/gr-op25_repeater/include/op25_repeater/ysf_tx_sb.h
+++ b/op25/gr-op25_repeater/include/op25_repeater/ysf_tx_sb.h
@@ -48,7 +48,7 @@ namespace gr {
* creating new instances.
*/
static sptr make(int versbose_flag, const char * conf_file, bool fullrate_mode);
- virtual void set_gain_adjust(float gain_adjust) {}
+ virtual void set_gain_adjust(float gain_adjust) = 0;
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/lib/CCITTChecksumReverse.cpp b/op25/gr-op25_repeater/lib/CCITTChecksumReverse.cpp
new file mode 100644
index 0000000..0b5b0fb
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/CCITTChecksumReverse.cpp
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2009,2011,2014 by Jonathan Naylor, G4KLX
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "CCITTChecksumReverse.h"
+
+static const unsigned short ccittTab[] = {
+ 0x0000,0x1189,0x2312,0x329b,0x4624,0x57ad,0x6536,0x74bf,
+ 0x8c48,0x9dc1,0xaf5a,0xbed3,0xca6c,0xdbe5,0xe97e,0xf8f7,
+ 0x1081,0x0108,0x3393,0x221a,0x56a5,0x472c,0x75b7,0x643e,
+ 0x9cc9,0x8d40,0xbfdb,0xae52,0xdaed,0xcb64,0xf9ff,0xe876,
+ 0x2102,0x308b,0x0210,0x1399,0x6726,0x76af,0x4434,0x55bd,
+ 0xad4a,0xbcc3,0x8e58,0x9fd1,0xeb6e,0xfae7,0xc87c,0xd9f5,
+ 0x3183,0x200a,0x1291,0x0318,0x77a7,0x662e,0x54b5,0x453c,
+ 0xbdcb,0xac42,0x9ed9,0x8f50,0xfbef,0xea66,0xd8fd,0xc974,
+ 0x4204,0x538d,0x6116,0x709f,0x0420,0x15a9,0x2732,0x36bb,
+ 0xce4c,0xdfc5,0xed5e,0xfcd7,0x8868,0x99e1,0xab7a,0xbaf3,
+ 0x5285,0x430c,0x7197,0x601e,0x14a1,0x0528,0x37b3,0x263a,
+ 0xdecd,0xcf44,0xfddf,0xec56,0x98e9,0x8960,0xbbfb,0xaa72,
+ 0x6306,0x728f,0x4014,0x519d,0x2522,0x34ab,0x0630,0x17b9,
+ 0xef4e,0xfec7,0xcc5c,0xddd5,0xa96a,0xb8e3,0x8a78,0x9bf1,
+ 0x7387,0x620e,0x5095,0x411c,0x35a3,0x242a,0x16b1,0x0738,
+ 0xffcf,0xee46,0xdcdd,0xcd54,0xb9eb,0xa862,0x9af9,0x8b70,
+ 0x8408,0x9581,0xa71a,0xb693,0xc22c,0xd3a5,0xe13e,0xf0b7,
+ 0x0840,0x19c9,0x2b52,0x3adb,0x4e64,0x5fed,0x6d76,0x7cff,
+ 0x9489,0x8500,0xb79b,0xa612,0xd2ad,0xc324,0xf1bf,0xe036,
+ 0x18c1,0x0948,0x3bd3,0x2a5a,0x5ee5,0x4f6c,0x7df7,0x6c7e,
+ 0xa50a,0xb483,0x8618,0x9791,0xe32e,0xf2a7,0xc03c,0xd1b5,
+ 0x2942,0x38cb,0x0a50,0x1bd9,0x6f66,0x7eef,0x4c74,0x5dfd,
+ 0xb58b,0xa402,0x9699,0x8710,0xf3af,0xe226,0xd0bd,0xc134,
+ 0x39c3,0x284a,0x1ad1,0x0b58,0x7fe7,0x6e6e,0x5cf5,0x4d7c,
+ 0xc60c,0xd785,0xe51e,0xf497,0x8028,0x91a1,0xa33a,0xb2b3,
+ 0x4a44,0x5bcd,0x6956,0x78df,0x0c60,0x1de9,0x2f72,0x3efb,
+ 0xd68d,0xc704,0xf59f,0xe416,0x90a9,0x8120,0xb3bb,0xa232,
+ 0x5ac5,0x4b4c,0x79d7,0x685e,0x1ce1,0x0d68,0x3ff3,0x2e7a,
+ 0xe70e,0xf687,0xc41c,0xd595,0xa12a,0xb0a3,0x8238,0x93b1,
+ 0x6b46,0x7acf,0x4854,0x59dd,0x2d62,0x3ceb,0x0e70,0x1ff9,
+ 0xf78f,0xe606,0xd49d,0xc514,0xb1ab,0xa022,0x92b9,0x8330,
+ 0x7bc7,0x6a4e,0x58d5,0x495c,0x3de3,0x2c6a,0x1ef1,0x0f78};
+
+CCCITTChecksumReverse::CCCITTChecksumReverse() :
+m_crc16(0xFFFFU)
+{
+}
+
+CCCITTChecksumReverse::~CCCITTChecksumReverse()
+{
+}
+
+void CCCITTChecksumReverse::update(const unsigned char* data, unsigned int length)
+{
+ assert(data != NULL);
+
+ for (unsigned int i = 0U; i < length; i++)
+ m_crc16 = ((uint16_t)(m_crc8[1U])) ^ ccittTab[m_crc8[0U] ^ data[i]];
+}
+
+void CCCITTChecksumReverse::result(unsigned char* data)
+{
+ assert(data != NULL);
+
+ m_crc16 = ~m_crc16;
+
+ data[0U] = m_crc8[0U];
+ data[1U] = m_crc8[1U];
+}
+
+bool CCCITTChecksumReverse::check(const unsigned char* data)
+{
+ assert(data != NULL);
+
+ unsigned char sum[2U];
+ result(sum);
+
+ return sum[0U] == data[0U] && sum[1U] == data[1U];
+}
+
+void CCCITTChecksumReverse::reset()
+{
+ m_crc16 = 0xFFFFU;
+}
diff --git a/op25/gr-op25_repeater/lib/CCITTChecksumReverse.h b/op25/gr-op25_repeater/lib/CCITTChecksumReverse.h
new file mode 100644
index 0000000..e60f93c
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/CCITTChecksumReverse.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009,2011,2014 by Jonathan Naylor, G4KLX
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#ifndef CCITTChecksumReverse_H
+#define CCITTChecksumReverse_H
+
+#include <stdint.h>
+
+class CCCITTChecksumReverse {
+public:
+ CCCITTChecksumReverse();
+ ~CCCITTChecksumReverse();
+
+ void update(const unsigned char* data, unsigned int length);
+
+ void result(unsigned char* data);
+
+ bool check(const unsigned char* data);
+
+ void reset();
+
+private:
+ union {
+ uint16_t m_crc16;
+ uint8_t m_crc8[2U];
+ };
+};
+
+#endif
diff --git a/op25/gr-op25_repeater/lib/CMakeLists.txt b/op25/gr-op25_repeater/lib/CMakeLists.txt
index d35a5b4..1464230 100644
--- a/op25/gr-op25_repeater/lib/CMakeLists.txt
+++ b/op25/gr-op25_repeater/lib/CMakeLists.txt
@@ -28,10 +28,12 @@ list(APPEND op25_repeater_sources
ambe_encoder_sb_impl.cc
dmr_bs_tx_bb_impl.cc
ysf_tx_sb_impl.cc
+ nxdn_tx_sb_impl.cc
dstar_tx_sb_impl.cc
vocoder_impl.cc
gardner_costas_cc_impl.cc
p25_frame_assembler_impl.cc
+ frame_assembler_impl.cc
fsk4_slicer_fb_impl.cc )
list(APPEND op25_repeater_sources
@@ -52,6 +54,11 @@ list(APPEND op25_repeater_sources
ambe.c
mbelib.c
ambe_encoder.cc
+ rx_sync.cc
+ op25_audio.cc
+ CCITTChecksumReverse.cpp
+ value_string.cc
+ nxdn.cc
)
add_library(gnuradio-op25_repeater SHARED ${op25_repeater_sources})
@@ -61,7 +68,7 @@ else(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
find_library(GR_FILTER_LIBRARY libgnuradio-filter.so )
endif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set(GR_FILTER_LIBRARIES ${GR_FILTER_LIBRARY})
-target_link_libraries(gnuradio-op25_repeater ${Boost_LIBRARIES} ${GNURADIO_RUNTIME_LIBRARIES} ${GR_FILTER_LIBRARIES} imbe_vocoder)
+target_link_libraries(gnuradio-op25_repeater ${Boost_LIBRARIES} gnuradio::gnuradio-runtime ${GR_FILTER_LIBRARIES} imbe_vocoder)
set_target_properties(gnuradio-op25_repeater PROPERTIES DEFINE_SYMBOL "gnuradio_op25_repeater_EXPORTS")
########################################################################
@@ -97,4 +104,21 @@ target_link_libraries(
GR_ADD_TEST(test_op25_repeater test-op25_repeater)
+########################################################################
+# d2460
+########################################################################
+list(APPEND d2460_sources
+ ${CMAKE_CURRENT_SOURCE_DIR}/d2460.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/ambe.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/mbelib.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/ambe_encoder.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/software_imbe_decoder.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/imbe_decoder.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/p25p2_vf.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rs.cc
+)
+
+add_executable(op25-d2460 ${d2460_sources})
+target_link_libraries(op25-d2460 imbe_vocoder)
+
add_subdirectory(imbe_vocoder)
diff --git a/op25/gr-op25_repeater/lib/ambe.c b/op25/gr-op25_repeater/lib/ambe.c
index aa43fb2..4ee5fd4 100644
--- a/op25/gr-op25_repeater/lib/ambe.c
+++ b/op25/gr-op25_repeater/lib/ambe.c
@@ -20,6 +20,18 @@
#include "ambe3600x2250_const.h"
#include "ambe3600x2400_const.h"
+#ifndef M_PI
+# define M_PI 3.14159265358979323846 /* pi */
+#endif
+
+#ifndef M_E
+# define M_E 2.7182818284590452354 /* e */
+#endif
+
+#ifndef M_SQRT2
+# define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
+#endif
+
static int
mbe_dequantizeAmbeParms (mbe_parms * cur_mp, mbe_parms * prev_mp, const int *b, int dstar)
{
@@ -140,7 +152,7 @@ mbe_dequantizeAmbeParms (mbe_parms * cur_mp, mbe_parms * prev_mp, const int *b,
#endif
if (dstar) {
deltaGamma = AmbePlusDg[b2];
- cur_mp->gamma = deltaGamma + ((float) 1.0 * prev_mp->gamma);
+ cur_mp->gamma = deltaGamma + ((float) 0.5 * prev_mp->gamma);
} else {
deltaGamma = AmbeDg[b2];
cur_mp->gamma = deltaGamma + ((float) 0.5 * prev_mp->gamma);
diff --git a/op25/gr-op25_repeater/lib/ambe_encoder.cc b/op25/gr-op25_repeater/lib/ambe_encoder.cc
index b134294..60465d1 100644
--- a/op25/gr-op25_repeater/lib/ambe_encoder.cc
+++ b/op25/gr-op25_repeater/lib/ambe_encoder.cc
@@ -545,6 +545,7 @@ static void encode_49bit(uint8_t outp[49], const int b[9]) {
ambe_encoder::ambe_encoder(void)
: d_49bit_mode(false),
d_dstar_mode(false),
+ d_alt_dstar_interleave(false),
d_gain_adjust(0)
{
mbe_parms enh_mp;
@@ -579,7 +580,7 @@ void ambe_encoder::encode(int16_t samples[], uint8_t codeword[])
encode_ambe(vocoder.param(), b, &cur_mp, &prev_mp, d_dstar_mode, d_gain_adjust);
if (d_dstar_mode) {
- interleaver.encode_dstar(codeword, b);
+ interleaver.encode_dstar(codeword, b, d_alt_dstar_interleave);
} else if (d_49bit_mode) {
encode_49bit(codeword, b);
} else {
diff --git a/op25/gr-op25_repeater/lib/ambe_encoder.h b/op25/gr-op25_repeater/lib/ambe_encoder.h
index 0d5f1a1..0b2706f 100644
--- a/op25/gr-op25_repeater/lib/ambe_encoder.h
+++ b/op25/gr-op25_repeater/lib/ambe_encoder.h
@@ -28,7 +28,8 @@ public:
ambe_encoder(void);
void set_49bit_mode(void);
void set_dstar_mode(void);
- void set_gain_adjust(float gain_adjust) {d_gain_adjust = gain_adjust;}
+ void set_gain_adjust(const float gain_adjust) {d_gain_adjust = gain_adjust;}
+ void set_alt_dstar_interleave(const bool v) { d_alt_dstar_interleave = v; }
private:
imbe_vocoder vocoder;
p25p2_vf interleaver;
@@ -37,6 +38,7 @@ private:
bool d_49bit_mode;
bool d_dstar_mode;
float d_gain_adjust;
+ bool d_alt_dstar_interleave;
};
#endif /* INCLUDED_AMBE_ENCODER_H */
diff --git a/op25/gr-op25_repeater/lib/bch.cc b/op25/gr-op25_repeater/lib/bch.cc
index 7ff4faf..e2e58a7 100644
--- a/op25/gr-op25_repeater/lib/bch.cc
+++ b/op25/gr-op25_repeater/lib/bch.cc
@@ -1,7 +1,7 @@
#include <stdio.h>
#include <vector>
-#include <bch.h>
+#include "bch.h"
/*
* Copyright 2010, KA1RBI
*/
diff --git a/op25/gr-op25_repeater/lib/bit_utils.h b/op25/gr-op25_repeater/lib/bit_utils.h
new file mode 100644
index 0000000..e8c9daa
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/bit_utils.h
@@ -0,0 +1,59 @@
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+#ifndef INCLUDED_OP25_REPEATER_BIT_UTILS_H
+#define INCLUDED_OP25_REPEATER_BIT_UTILS_H
+
+#include <stdint.h>
+
+static inline void store_i(int reg, uint8_t val[], int len) {
+ for (int i=0; i<len; i++){
+ val[i] = (reg >> (len-1-i)) & 1;
+ }
+}
+
+static inline int load_i(const uint8_t val[], int len) {
+ int acc = 0;
+ for (int i=0; i<len; i++){
+ acc = (acc << 1) + (val[i] & 1);
+ }
+ return acc;
+}
+
+static inline uint64_t load_reg64(const uint8_t val[], int len) {
+ uint64_t acc = 0;
+ for (int i=0; i<len; i++){
+ acc = (acc << 1) + (val[i] & 1);
+ }
+ return acc;
+}
+
+static inline void dibits_to_bits(uint8_t * bits, const uint8_t * dibits, const int n_dibits) {
+ for (int i=0; i<n_dibits; i++) {
+ bits[i*2] = (dibits[i] >> 1) & 1;
+ bits[i*2+1] = dibits[i] & 1;
+ }
+}
+
+static inline void bits_to_dibits(uint8_t* dest, const uint8_t* src, int n_dibits) {
+ for (int i=0; i<n_dibits; i++) {
+ dest[i] = src[i*2] * 2 + src[i*2+1];
+ }
+}
+
+#endif /* INCLUDED_OP25_REPEATER_BIT_UTILS_H */
diff --git a/op25/gr-op25_repeater/lib/check_frame_sync.h b/op25/gr-op25_repeater/lib/check_frame_sync.h
index d361f19..bf2498c 100644
--- a/op25/gr-op25_repeater/lib/check_frame_sync.h
+++ b/op25/gr-op25_repeater/lib/check_frame_sync.h
@@ -6,7 +6,7 @@
static inline bool check_frame_sync(uint64_t x, int err_threshold, int len) {
int errs=0;
- static const uint64_t mask = (1LL<<len)-1;
+ const uint64_t mask = (1LL<<len)-1LL;
x = x & mask;
// source: https://en.wikipedia.org/wiki/Hamming_weight
static const uint64_t m1 = 0x5555555555555555; //binary: 0101...
diff --git a/op25/gr-op25_repeater/lib/crc16.h b/op25/gr-op25_repeater/lib/crc16.h
new file mode 100644
index 0000000..77f9dd6
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/crc16.h
@@ -0,0 +1,35 @@
+/*
+ * This file is part of OP25
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef INCLUDED_CRC16_H
+#define INCLUDED_CRC16_H
+
+static inline uint16_t crc16(const uint8_t buf[], int len) {
+ uint32_t poly = (1<<12) + (1<<5) + (1<<0);
+ uint32_t crc = 0;
+ for(int i=0; i<len; i++) {
+ uint8_t bit = buf[i] & 1;
+ crc = ((crc << 1) | bit) & 0x1ffff;
+ if (crc & 0x10000)
+ crc = (crc & 0xffff) ^ poly;
+ }
+ crc = crc ^ 0xffff;
+ return crc & 0xffff;
+}
+#endif /* INCLUDED_CRC16_H */
diff --git a/op25/gr-op25_repeater/lib/d2460.cc b/op25/gr-op25_repeater/lib/d2460.cc
new file mode 100644
index 0000000..16b87f9
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/d2460.cc
@@ -0,0 +1,362 @@
+#include <stdio.h>
+#include <time.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <errno.h>
+#include <termios.h>
+#include <string.h>
+#include <fcntl.h>
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <sys/param.h>
+
+#include <netinet/in.h>
+
+#include <stdint.h>
+
+#include "mbelib.h"
+#include "ambe.h"
+#include "p25p2_vf.h"
+#include "imbe_decoder.h"
+#include "software_imbe_decoder.h"
+#include "imbe_vocoder/imbe_vocoder.h"
+#include "ambe_encoder.h"
+
+static const float GAIN_ADJUST=7.0; /* attenuation (dB) */
+
+typedef uint16_t Uns;
+static const Uns RC_OK=0;
+
+static const char prodid[] = "OP25 ";
+static const char verstring[] = "1.0";
+
+static ambe_encoder encoder;
+static software_imbe_decoder software_decoder;
+static p25p2_vf interleaver;
+static mbe_parms cur_mp;
+static mbe_parms prev_mp;
+static mbe_parms enh_mp;
+
+static const Uns DV3K_START_BYTE = 0x61;
+enum
+{
+ DV3K_CONTROL_RATEP = 0x0A,
+ DV3K_CONTROL_CHANFMT = 0x15,
+ DV3K_CONTROL_PRODID = 0x30,
+ DV3K_CONTROL_VERSTRING = 0x31,
+ DV3K_CONTROL_RESET = 0x33,
+ DV3K_CONTROL_READY = 0x39
+};
+static const Uns DV3K_AMBE_FIELD_CHAND = 0x01;
+static const Uns DV3K_AMBE_FIELD_CMODE = 0x02;
+static const Uns DV3K_AMBE_FIELD_TONE = 0x08;
+static const Uns DV3K_AUDIO_FIELD_SPEECHD = 0x00;
+static const Uns DV3K_AUDIO_FIELD_CMODE = 0x02;
+
+#pragma DATA_ALIGN(dstar_state, 2)
+static Uns bitstream[72];
+
+static Uns get_byte(Uns offset, Uns *p)
+{
+ Uns word = p[offset >> 1];
+ return (offset & 1) ? (word >> 8) : (word & 0xff);
+}
+
+static void set_byte(Uns offset, Uns *p, Uns byte)
+{
+ p[offset >> 1] =
+ (offset & 1) ? (byte << 8) | (p[offset >> 1] & 0xff)
+ : (p[offset >> 1] & 0xff00) | (byte & 0xff);
+}
+
+static Uns get_word(Uns offset, Uns *p)
+{
+ return get_byte(offset + 1, p) | (get_byte(offset, p) << 8);
+}
+
+static void set_word(Uns offset, Uns *p, Uns word)
+{
+ set_byte(offset, p, word >> 8);
+ set_byte(offset + 1, p, word & 0xff);
+}
+
+static void set_cstring(Uns offset, Uns *p, const char *str)
+{
+ do
+ set_byte(offset++, p, *str);
+ while (*str++ != 0);
+}
+
+static Uns pkt_check_ratep(Uns offset, Uns *p)
+{
+ static const Uns ratep[] = {
+ 0x01, 0x30, 0x07, 0x63, 0x40, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x48 };
+ Uns i;
+ for (i = 0; i < sizeof(ratep); ++i)
+ if (get_byte(offset + i, p) != ratep[i])
+ return 0;
+ return 1;
+}
+
+static void pack(Uns bits, Uns offset, Uns *p, Uns *bitstream)
+{
+ Uns i;
+ Uns byte = 0;
+ for (i = 0; i < bits; ++i)
+ {
+ byte |= bitstream[i] << (7 - (i & 7));
+ if ((i & 7) == 7)
+ {
+ set_byte(offset++, p, byte);
+ byte = 0;
+ }
+ }
+ if (i & 7)
+ set_byte(offset, p, byte);
+}
+
+static void unpack(Uns bits, Uns offset, Uns *bitstream, Uns *p)
+{
+ Uns i;
+ Uns byte;
+ for (i = 0; i < bits; ++i)
+ {
+ if ((i & 7) == 0)
+ byte = get_byte(offset++, p);
+ bitstream[i] = (byte >> (7 - (i & 7))) & 1;
+ }
+}
+
+static int response_len = -1;
+
+static void bksnd(void*task, Uns bid, Uns len)
+{
+ response_len = len;
+}
+
+static void vocoder_setup(void) {
+ encoder.set_dstar_mode();
+ encoder.set_gain_adjust(GAIN_ADJUST);
+ encoder.set_alt_dstar_interleave(true);
+ mbe_initMbeParms (&cur_mp, &prev_mp, &enh_mp);
+}
+
+static void dump(unsigned char *p, ssize_t n)
+{
+ int i;
+ for (i = 0; i < n; ++i)
+ printf("%02x%c", p[i], i % 16 == 15 ? '\n' : ' ');
+ if (i % 16)
+ printf("\n");
+}
+
+static Uns pkt_process(Uns*pkt, Uns cnt)
+{
+ Uns bid=0;
+ Uns len = cnt << 1;
+ Uns payload_length;
+ Uns i;
+ Uns cmode = 0;
+ Uns tone = 0;
+ uint8_t codeword[72];
+ int b[9];
+ int K;
+ int rc = -1;
+
+ if (len < 4 || cnt > 256)
+ goto fail;
+
+ if (get_byte(0, pkt) != DV3K_START_BYTE)
+ goto fail;
+
+ payload_length = get_word(1, pkt);
+ if (payload_length == 0)
+ goto fail;
+ if (4 + payload_length > len)
+ goto fail;
+
+ switch (get_byte(3, pkt))
+ {
+ case 0:
+ switch (get_byte(4, pkt))
+ {
+ case DV3K_CONTROL_RATEP:
+ if (payload_length != 13)
+ goto fail;
+ if (!pkt_check_ratep(5, pkt))
+ goto fail;
+ set_word(1, pkt, 1);
+ bksnd(NULL, bid, 3);
+ return RC_OK;
+ case DV3K_CONTROL_CHANFMT:
+ if (payload_length != 3)
+ goto fail;
+ if (get_word(5, pkt) != 0x0001)
+ goto fail;
+ set_word(1, pkt, 2);
+ set_byte(5, pkt, 0);
+ bksnd(NULL, bid, 3);
+ return RC_OK;
+ case DV3K_CONTROL_PRODID:
+ set_word(1, pkt, 8);
+ set_cstring(5, pkt, prodid);
+ bksnd(NULL, bid, 6);
+ return RC_OK;
+ case DV3K_CONTROL_VERSTRING:
+ set_word(1, pkt, 5);
+ set_cstring(5, pkt, verstring);
+ bksnd(NULL, bid, 5);
+ return RC_OK;
+ case DV3K_CONTROL_RESET:
+ if (payload_length != 1)
+ goto fail;
+ vocoder_setup();
+ set_byte(4, pkt, DV3K_CONTROL_READY);
+ bksnd(NULL, bid, 3);
+ return RC_OK;
+ default:
+ goto fail;
+ }
+ case 1:
+ switch (payload_length)
+ {
+ case 17:
+ if (get_byte(18, pkt) != DV3K_AMBE_FIELD_TONE)
+ goto fail;
+ tone = get_word(19, pkt);
+ /* FALLTHROUGH */
+ case 14:
+ if (get_byte(15, pkt) != DV3K_AMBE_FIELD_CMODE)
+ goto fail;
+ cmode = get_word(16, pkt);
+ /* FALLTHROUGH */
+ case 11:
+ if (get_byte(4, pkt) != DV3K_AMBE_FIELD_CHAND)
+ goto fail;
+ if (get_byte(5, pkt) != 72)
+ goto fail;
+ unpack(72, 6, bitstream, pkt);
+ break;
+ default:
+ goto fail;
+ }
+
+ for (i = 0; i < 72; i++) {
+ codeword[i] = bitstream[i];
+ }
+ interleaver.decode_dstar(codeword, b, true);
+ if (b[0] >= 120) {
+ memset(6+(char*)pkt, 0, 320); // silence
+ // FIXME: add handling for tone case (b0=126)
+ } else {
+ rc = mbe_dequantizeAmbe2400Parms(&cur_mp, &prev_mp, b);
+ printf("B\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
+ K = 12;
+ if (cur_mp.L <= 36)
+ K = int(float(cur_mp.L + 2.0) / 3.0);
+ software_decoder.decode_tap(cur_mp.L, K, cur_mp.w0, &cur_mp.Vl[1], &cur_mp.Ml[1]);
+ audio_samples *samples = software_decoder.audio();
+ int16_t snd;
+ for (i=0; i < 160; i++) {
+ if (samples->size() > 0) {
+ snd = (int16_t)(samples->front());
+ samples->pop_front();
+ } else {
+ snd = 0;
+ }
+ set_word(6 + (i << 1), pkt, snd);
+ }
+ mbe_moveMbeParms (&cur_mp, &prev_mp);
+ }
+
+ set_word(1, pkt, 322);
+ set_byte(3, pkt, 2);
+ set_byte(4, pkt, DV3K_AUDIO_FIELD_SPEECHD);
+ set_byte(5, pkt, 160);
+ bksnd(NULL, bid, 165);
+ return RC_OK;
+ case 2:
+ if (payload_length != 322 && payload_length != 325)
+ goto fail;
+ if (get_byte(4, pkt) != DV3K_AUDIO_FIELD_SPEECHD)
+ goto fail;
+ if (get_byte(5, pkt) != 160)
+ goto fail;
+ if (payload_length == 325)
+ {
+ if (get_byte(326, pkt) != DV3K_AUDIO_FIELD_CMODE)
+ goto fail;
+ cmode = get_word(323, pkt);
+ }
+ int16_t samples[160];
+ for (i=0; i < 160; i++) {
+ samples[i] = (int16_t) get_word(6 + (i << 1), pkt);
+ }
+ encoder.encode(samples, codeword);
+ for (i = 0; i < 72; i++) {
+ bitstream[i] = codeword[i];
+ }
+ set_word(1, pkt, 11);
+ set_byte(3, pkt, 1);
+ set_byte(4, pkt, DV3K_AMBE_FIELD_CHAND);
+ set_byte(5, pkt, 72);
+ pack(72, 6, pkt, bitstream);
+ bksnd(NULL, bid, 8);
+ return RC_OK;
+ default:
+ goto fail;
+ }
+
+fail:
+ bksnd(NULL, bid, 0);
+ return RC_OK;
+}
+
+int main()
+{
+ int sockfd;
+ const ssize_t size_max = 1024;
+ ssize_t size_in, size_out;
+ char buf_in[size_max], buf_out[size_max];
+ socklen_t length = sizeof(struct sockaddr_in);
+ struct sockaddr_in sa = { 0 };
+ Uns rc;
+
+ vocoder_setup();
+
+ if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
+ exit(2);
+
+ sa.sin_family = AF_INET;
+ sa.sin_port = htons(2460);
+ sa.sin_addr.s_addr = htonl(INADDR_ANY);
+
+ if (bind(sockfd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
+ exit(3);
+
+ while (1)
+ {
+ if ((size_in = recvfrom(sockfd, buf_in, size_max,
+ 0, (struct sockaddr *)&sa, &length)) < 0)
+ exit(4);
+
+ if (size_in & 1)
+ buf_in[size_in++] = 0;
+
+ rc = pkt_process((Uns*)buf_in, size_in >> 1);
+ if (response_len <= 0)
+ exit(9);
+
+ size_out = 4 + ntohs(*(short *)&buf_in[1]);
+ if (sendto(sockfd, buf_in, size_out, 0, (struct sockaddr *)&sa,
+ sizeof(struct sockaddr_in)) != size_out)
+ exit(7);
+ }
+
+ return 0;
+}
diff --git a/op25/gr-op25_repeater/lib/dmr_bs_tx_bb_impl.cc b/op25/gr-op25_repeater/lib/dmr_bs_tx_bb_impl.cc
index 3609c58..52972a4 100644
--- a/op25/gr-op25_repeater/lib/dmr_bs_tx_bb_impl.cc
+++ b/op25/gr-op25_repeater/lib/dmr_bs_tx_bb_impl.cc
@@ -80,7 +80,7 @@ static bool crc8_ok(const uint8_t bits[], unsigned int len) {
return (crc == crc8(bits,len));
}
-static inline int store_i(int reg, uint8_t val[], int len) {
+static inline void store_i(int reg, uint8_t val[], int len) {
for (int i=0; i<len; i++){
val[i] = (reg >> (len-1-i)) & 1;
}
@@ -186,8 +186,6 @@ static void generate_cach(uint8_t at, uint8_t tc, uint8_t lcss, const uint8_t ca
int tact = hamming_7_4[ (at << 3) | (tc << 2) | lcss ];
//printf ("tact %d %x\n", tact, tact);
//print_result("cach_payload_bits", cach_bits, 17);
- static const uint8_t cach_tact_bits[] = {0, 4, 8, 12, 14, 18, 22};
- static const uint8_t cach_payload_bits[] = {1,2,3,5,6,7,9,10,11,13,15,16,17,19,20,21,23};
for (int i=0; i<7; i++) {
result[cach_tact_bits[i]] = (tact >> (6-i)) & 1;
}
diff --git a/op25/gr-op25_repeater/lib/dmr_const.h b/op25/gr-op25_repeater/lib/dmr_const.h
index 0ea6ca0..31196a0 100644
--- a/op25/gr-op25_repeater/lib/dmr_const.h
+++ b/op25/gr-op25_repeater/lib/dmr_const.h
@@ -21,11 +21,24 @@
#ifndef INCLUDED_OP25_REPEATER_DMR_CONST_H
#define INCLUDED_OP25_REPEATER_DMR_CONST_H
+#include <stdint.h>
+
static const int hamming_7_4[] = {
0, 11, 22, 29, 39, 44, 49, 58,
69, 78, 83, 88, 98, 105, 116, 127,
};
-
+
+static const int hamming_7_4_decode[] = {
+ 0, 0, 0, 1, 0, 8, 2, 4, 0, 1, 1, 1, 5, 3, 9, 1,
+ 0, 6, 2, 10, 2, 3, 2, 2, 11, 3, 7, 1, 3, 3, 2, 3,
+ 0, 6, 12, 4, 5, 4, 4, 4, 5, 13, 7, 1, 5, 5, 5, 4,
+ 6, 6, 7, 6, 14, 6, 2, 4, 7, 6, 7, 7, 5, 3, 7, 15,
+ 0, 8, 12, 10, 8, 8, 9, 8, 11, 13, 9, 1, 9, 8, 9, 9,
+ 11, 10, 10, 10, 14, 8, 2, 10, 11, 11, 11, 10, 11, 3, 9, 15,
+ 12, 13, 12, 12, 14, 8, 12, 4, 13, 13, 12, 13, 5, 13, 9, 15,
+ 14, 6, 12, 10, 14, 14, 14, 15, 11, 13, 7, 15, 14, 15, 15, 15
+};
+
static const int hamming_17_12[] = {
0, 37, 74, 111, 148, 177, 222, 251,
269, 296, 327, 354, 409, 444, 467, 502,
@@ -822,9 +835,62 @@ static const int hamming_16_11[] = {
static const uint8_t dmr_bs_voice_sync[24] = {
1,3,1,1,1,1,3,3,3,1,1,3,3,1,3,3,1,3,1,1,3,3,1,3
};
+static const uint64_t DMR_VOICE_SYNC_MAGIC = 0x755fd7df75f7LL;
+static const uint64_t DMR_IDLE_SYNC_MAGIC = 0xdff57d75df5dLL;
static const uint8_t dmr_bs_idle_sync[24] = {
3,1,3,3,3,3,1,1,1,3,3,1,1,3,1,1,3,1,3,3,1,1,3,1
};
+static const uint8_t cach_tact_bits[] = {0, 4, 8, 12, 14, 18, 22};
+static const uint8_t cach_payload_bits[] = {1,2,3,5,6,7,9,10,11,13,15,16,17,19,20,21,23};
+
+static const uint16_t _pc[] = {0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0};
+
+static const uint32_t slookup_16_11[] = {0, 1, 2, 0, 4, 0, 0, 32, 8, 0, 0, 512, 0, 64, 2048, 0, 16, 0, 0, 32768, 0, 1024, 256, 0, 0, 128, 16384, 0, 4096, 0, 0, 8192};
+static const uint32_t masks_16_11[] = {62864, 31432, 15716, 60194, 42721};
+static const uint32_t nmasks_16_11 = 5;
+
+static const uint32_t slookup_16_7[] = {0, 1, 2, 3, 4, 5, 6, 0, 8, 9, 10, 0, 12, 0, 0, 32832, 16, 17, 18, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0, 0, 16640, 0, 32, 33, 34, 0, 36, 0, 0, 0, 40, 0, 0, 6144, 0, 0, 0, 0, 48, 0, 0, 576, 0, 0, 0, 0, 0, 0, 0, 0, 33280, 0, 0, 0, 64, 65, 66, 0, 68, 0, 0, 32776, 72, 0, 0, 32772, 0, 32770, 32769, 32768, 80, 0, 0, 544, 0, 12288, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32784, 96, 0, 0, 528, 0, 1152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32800, 0, 514, 513, 512, 0, 0, 0, 516, 0, 0, 0, 520, 0, 0, 10240, 0, 128, 129, 130, 0, 132, 0, 0, 0, 136, 0, 0, 0, 0, 0, 0, 0, 144, 0, 0, 0, 0, 0, 1536, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 0, 0, 0, 0, 1088, 0, 0, 0, 24576, 33792, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8448, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 1056, 0, 0, 0, 2304, 0, 0, 0, 0, 0, 32896, 0, 0, 0, 0, 0, 0, 0, 18432, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1028, 4352, 0, 1025, 1024, 0, 1026, 0, 0, 0, 0, 0, 1032, 0, 0, 0, 0, 0, 640, 0, 1040, 0, 0, 0, 0, 0, 0, 20480, 0, 0, 0, 256, 257, 258, 0, 260, 0, 0, 5120, 264, 0, 0, 0, 0, 0, 16400, 0, 272, 0, 0, 0, 0, 0, 16392, 0, 0, 0, 16388, 0, 16386, 0, 16384, 16385, 288, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3072, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8320, 0, 0, 0, 0, 0, 0, 16416, 0, 320, 0, 0, 0, 0, 0, 0, 0, 0, 2176, 0, 0, 0, 0, 0, 33024, 0, 49152, 9216, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16448, 0, 0, 0, 4224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16896, 0, 0, 0, 0, 0, 768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 384, 0, 0, 0, 0, 0, 34816, 0, 0, 2112, 0, 0, 0, 0, 0, 0, 0, 4608, 0, 0, 0, 0, 0, 8224, 0, 0, 0, 0, 0, 0, 16512, 0, 0, 0, 4160, 0, 0, 0, 0, 8208, 0, 0, 0, 0, 0, 36864, 0, 0, 0, 0, 0, 8196, 0, 8194, 8193, 8192, 0, 0, 2560, 0, 0, 0, 0, 8200, 0, 2056, 4128, 0, 8704, 0, 0, 0, 2049, 2048, 0, 2050, 0, 2052, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2064, 0, 0, 0, 0, 0, 0, 4098, 0, 4096, 4097, 0, 1280, 4100, 0, 0, 2080, 4104, 0, 0, 0, 0, 0, 0, 0, 4112, 0, 0, 0, 0, 8256, 40960, 0, 0, 17408, 0, 0, 0, 0};
+static const uint32_t masks_16_7[] = {30976, 15488, 40512, 13856, 25104, 51208, 58372, 61954, 44545};
+static const uint32_t nmasks_16_7 = 9;
+
+static const uint32_t slookup_17_12[] = {0, 1, 2, 0, 4, 32, 0, 2048, 8, 0, 64, 0, 0, 256, 4096, 0, 16, 1024, 0, 0, 128, 0, 0, 0, 0, 0, 512, 65536, 8192, 16384, 0, 32768};
+static const uint32_t masks_17_12[] = {124560, 127816, 63908, 105026, 118049};
+static const uint32_t nmasks_17_12 = 5;
+
+static inline int64_t _hamming_decode(const uint32_t r_codeword, const int n, const int k, const uint32_t *slookup, const uint32_t *masks, const uint32_t nmasks, const int *encode_tab) {
+ uint32_t syn = 0;
+ for (uint32_t i=0; i<nmasks; i++) {
+ uint32_t acc = masks[i] & r_codeword;
+ uint32_t sum = 0;
+ for (; acc > 0; acc >>= 8) {
+ sum += _pc[acc & 0xff];
+ }
+ syn = (syn << 1) + (sum & 1);
+ }
+ if (syn == 0)
+ return (r_codeword >> (n - k)); // decode, no error case
+ uint32_t sl = slookup[syn];
+ if (sl == 0)
+ return -1; // decode failed
+ uint32_t decoded = (r_codeword ^ sl) >> (n - k); // corrected but not yet trusted result
+ uint32_t encoded = encode_tab[decoded]; // re-encode and verify codewords match
+ if ((r_codeword ^ sl) == encoded)
+ return decoded; // decode OK with 1 error corrected
+ return -2; // decode verification failed
+}
+
+static inline int64_t hamming_17_12_decode(const uint32_t r_codeword) {
+ return _hamming_decode(r_codeword, 17, 12, slookup_17_12, masks_17_12, nmasks_17_12, hamming_17_12);
+}
+
+static inline int64_t hamming_16_11_decode(const uint32_t r_codeword) {
+ return _hamming_decode(r_codeword, 16, 11, slookup_16_11, masks_16_11, nmasks_16_11, hamming_16_11);
+}
+
+static inline int64_t hamming_16_7_decode(const uint32_t r_codeword) {
+ return _hamming_decode(r_codeword, 16, 7, slookup_16_7, masks_16_7, nmasks_16_7, hamming_16_7);
+}
+
#endif /* INCLUDED_OP25_REPEATER_DMR_CONST_H */
diff --git a/op25/gr-op25_repeater/lib/dstar_header.h b/op25/gr-op25_repeater/lib/dstar_header.h
new file mode 100644
index 0000000..034bb26
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/dstar_header.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2010,2011,2015 by Jonathan Naylor, G4KLX
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+/* from OpenDV/DStarRepeater */
+
+#ifndef INCLUDED_DSTAR_HEADER_H
+#define INCLUDED_DSTAR_HEADER_H
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "CCITTChecksumReverse.h"
+#include "bit_utils.h"
+
+static inline uint8_t rev_byte(const uint8_t b) {
+ uint8_t rc = 0;
+ for (int i=0; i<8; i++) {
+ rc |= ((b >> i) & 1) << (7-i);
+ }
+ return(rc);
+}
+
+static inline void make_dstar_header(
+ uint8_t header_data_buf[480], // result (bits)
+ const uint8_t flag1, const uint8_t flag2, const uint8_t flag3,
+ const char RptCall2[],
+ const char RptCall1[],
+ const char YourCall[],
+ const char MyCall1[],
+ const char MyCall2[])
+{
+ uint8_t m_headerData[60];
+ static const unsigned int SLOW_DATA_BLOCK_SIZE = 6U;
+ static const unsigned int SLOW_DATA_FULL_BLOCK_SIZE = SLOW_DATA_BLOCK_SIZE * 10U;
+ static const unsigned char SLOW_DATA_TYPE_HEADER = 0x50U;
+
+ ::memset(m_headerData, 'f', SLOW_DATA_FULL_BLOCK_SIZE);
+
+ m_headerData[0U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[1U] = flag1;
+ m_headerData[2U] = flag2;
+ m_headerData[3U] = flag3;
+ m_headerData[4U] = RptCall2[0];
+ m_headerData[5U] = RptCall2[1];
+
+ m_headerData[6U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[7U] = RptCall2[2];
+ m_headerData[8U] = RptCall2[3];
+ m_headerData[9U] = RptCall2[4];
+ m_headerData[10U] = RptCall2[5];
+ m_headerData[11U] = RptCall2[6];
+
+ m_headerData[12U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[13U] = RptCall2[7];
+ m_headerData[14U] = RptCall1[0];
+ m_headerData[15U] = RptCall1[1];
+ m_headerData[16U] = RptCall1[2];
+ m_headerData[17U] = RptCall1[3];
+
+ m_headerData[18U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[19U] = RptCall1[4];
+ m_headerData[20U] = RptCall1[5];
+ m_headerData[21U] = RptCall1[6];
+ m_headerData[22U] = RptCall1[7];
+ m_headerData[23U] = YourCall[0];
+
+ m_headerData[24U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[25U] = YourCall[1];
+ m_headerData[26U] = YourCall[2];
+ m_headerData[27U] = YourCall[3];
+ m_headerData[28U] = YourCall[4];
+ m_headerData[29U] = YourCall[5];
+
+ m_headerData[30U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[31U] = YourCall[6];
+ m_headerData[32U] = YourCall[7];
+ m_headerData[33U] = MyCall1[0];
+ m_headerData[34U] = MyCall1[1];
+ m_headerData[35U] = MyCall1[2];
+
+ m_headerData[36U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[37U] = MyCall1[3];
+ m_headerData[38U] = MyCall1[4];
+ m_headerData[39U] = MyCall1[5];
+ m_headerData[40U] = MyCall1[6];
+ m_headerData[41U] = MyCall1[7];
+
+ m_headerData[42U] = SLOW_DATA_TYPE_HEADER | 5U;
+ m_headerData[43U] = MyCall2[0];
+ m_headerData[44U] = MyCall2[1];
+ m_headerData[45U] = MyCall2[2];
+ m_headerData[46U] = MyCall2[3];
+
+ CCCITTChecksumReverse cksum;
+ cksum.update(m_headerData + 1U, 5U);
+ cksum.update(m_headerData + 7U, 5U);
+ cksum.update(m_headerData + 13U, 5U);
+ cksum.update(m_headerData + 19U, 5U);
+ cksum.update(m_headerData + 25U, 5U);
+ cksum.update(m_headerData + 31U, 5U);
+ cksum.update(m_headerData + 37U, 5U);
+ cksum.update(m_headerData + 43U, 4U);
+
+ unsigned char checkSum[2U];
+ cksum.result(checkSum);
+
+ m_headerData[47U] = checkSum[0];
+
+ m_headerData[48U] = SLOW_DATA_TYPE_HEADER | 1U;
+ m_headerData[49U] = checkSum[1];
+
+ for (int i=0; i<SLOW_DATA_FULL_BLOCK_SIZE; i+=3) {
+ store_i(rev_byte(m_headerData[i] ^ 0x70), header_data_buf+i*8, 8);
+ store_i(rev_byte(m_headerData[i+1] ^ 0x4f), header_data_buf+((i+1)*8), 8);
+ store_i(rev_byte(m_headerData[i+2] ^ 0x93), header_data_buf+((i+2)*8), 8);
+ }
+}
+
+#endif /* INCLUDED_DSTAR_HEADER_H */
diff --git a/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.cc b/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.cc
index c89ce12..c0d2cce 100644
--- a/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.cc
+++ b/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.cc
@@ -29,7 +29,8 @@
#include "p25p2_vf.h"
#include "dstar_tx_sb_impl.h"
// #include "dstar_const.h"
-#include <op25_imbe_frame.h>
+#include "op25_imbe_frame.h"
+#include "dstar_header.h"
#include <vector>
#include <stdint.h>
@@ -52,6 +53,15 @@ static inline void print_result(char title[], const uint8_t r[], int len) {
}
#endif
+static inline void sstring(const char s[], char dest[8]) {
+ memset(dest, ' ', 8);
+ memcpy(dest, s, std::min(strlen(s), (size_t)8));
+ for (int i=0; i<8; i++) {
+ if (dest[i] < ' ')
+ dest [i] = ' ';
+ }
+}
+
static const uint8_t FS[24] = { 1,0,1,0,1,0,1,0,1,0,1,1,0,1,0,0,0,1,1,0,1,0,0,0 };
static const uint8_t FS_DUMMY[24] = { 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1 };
@@ -102,8 +112,13 @@ dstar_tx_sb_impl::config()
FILE * fp1 = fopen(d_config_file, "r");
char line[256];
char * cp;
- // TODO: add code to generate slow speed datastream
- return;
+ int flag1, flag2, flag3;
+ char rptcall1[8];
+ char rptcall2[8];
+ char urcall[8];
+ char mycall1[8];
+ char mycall2[8];
+
if (!fp1) {
fprintf(stderr, "dstar_tx_sb_impl:config: failed to open %s\n", d_config_file);
return;
@@ -112,12 +127,25 @@ dstar_tx_sb_impl::config()
cp = fgets(line, sizeof(line) - 2, fp1);
if (!cp) break;
if (line[0] == '#') continue;
-#if 0
- if (memcmp(line, "ft=", 3) == 0)
- sscanf(&line[3], "%d", &d_ft);
-#endif
+ if (memcmp(line, "flag1=", 6) == 0)
+ sscanf(&line[6], "%x", &flag1);
+ else if (memcmp(line, "flag2=", 6) == 0)
+ sscanf(&line[6], "%x", &flag2);
+ else if (memcmp(line, "flag3=", 6) == 0)
+ sscanf(&line[6], "%x", &flag3);
+ else if (memcmp(line, "rptcall2=", 9) == 0)
+ sstring(&line[9], rptcall2);
+ else if (memcmp(line, "rptcall1=", 9) == 0)
+ sstring(&line[9], rptcall1);
+ else if (memcmp(line, "urcall=", 7) == 0)
+ sstring(&line[7], urcall);
+ else if (memcmp(line, "mycall1=", 8) == 0)
+ sstring(&line[8], mycall1);
+ else if (memcmp(line, "mycall2=", 8) == 0)
+ sstring(&line[8], mycall2);
}
fclose(fp1);
+ make_dstar_header(d_dstar_header_data, flag1 & 0xff, flag2 & 0xff, flag3 & 0xff, rptcall2, rptcall1, urcall, mycall1, mycall2);
}
void
@@ -151,7 +179,7 @@ dstar_tx_sb_impl::general_work (int noutput_items,
if (d_frame_counter == 0)
memcpy(out+72, FS, 24);
else
- memcpy(out+72, FS_DUMMY, 24);
+ memcpy(out+72, d_dstar_header_data+((d_frame_counter-1) * 24), 24);
d_frame_counter = (d_frame_counter + 1) % 21;
in += 160;
nconsumed += 160;
diff --git a/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.h b/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.h
index 4451702..6570161 100644
--- a/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.h
+++ b/op25/gr-op25_repeater/lib/dstar_tx_sb_impl.h
@@ -60,6 +60,7 @@ namespace gr {
const char * d_config_file;
ambe_encoder d_encoder;
int d_frame_counter;
+ uint8_t d_dstar_header_data[480];
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/lib/ezpwd/asserter b/op25/gr-op25_repeater/lib/ezpwd/asserter
new file mode 100644
index 0000000..5e0a19e
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/asserter
@@ -0,0 +1,128 @@
+#ifndef _EZPWD_ASSERTER
+#define _EZPWD_ASSERTER
+
+#include <algorithm>
+#include <cstring>
+#include <iostream>
+#include <iomanip>
+#include <sstream>
+
+namespace ezpwd {
+
+#define ISEQUAL( ... ) isequal(__FILE__, __LINE__, __VA_ARGS__ )
+#define ISTRUE( ... ) istrue( __FILE__, __LINE__, __VA_ARGS__ )
+#define ISFALSE( ... ) isfalse(__FILE__, __LINE__, __VA_ARGS__ )
+#define ISNEAR( ... ) isnear( __FILE__, __LINE__, __VA_ARGS__ )
+#define FAILURE( ... ) failure(__FILE__, __LINE__, __VA_ARGS__ )
+
+ struct asserter {
+ bool failed; // The last test failed
+ int failures; // Total number of failures
+ std::string out; // Last failure
+
+ asserter()
+ : failed( false )
+ , failures( 0 )
+ , out()
+ {
+ ;
+ }
+
+ //
+ // output( <std::ostream> ) -- Output description of last failed test (or nothing if successful)
+ // <std::ostream> << <asserter>
+ //
+ std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ return lhs << out;
+ }
+
+ //
+ // (bool) <asserter> -- Return status of last test
+ //
+ operator bool()
+ {
+ return failed;
+ }
+
+ template < typename T >
+ asserter &istrue( const char *file, int line, const T &a, const std::string &comment = std::string() )
+ {
+ return isequal( file, line, !!a, true, comment );
+ }
+
+ template < typename T >
+ asserter &isfalse( const char *file, int line, const T &a, const std::string &comment = std::string() )
+ {
+ return isequal( file, line, !!a, false, comment );
+ }
+
+ template < typename T >
+ asserter &isequal( const char *file, int line, const T &a, const T &b, const std::string &comment = std::string() )
+ {
+ if ( ! ( a == b )) {
+ std::ostringstream oss;
+ oss << a << " != " << b;
+ return failure( file, line, oss.str(), comment );
+ }
+ return success();
+ }
+
+ template < typename T >
+ asserter &isnear( const char *file, int line, const T &a, const T &b, const T &delta, const std::string &comment = std::string() )
+ {
+ T difference;
+ difference = ( a < b
+ ? T( b - a )
+ : T( a - b ));
+ if ( ! ( difference < ( delta < T( 0 ) ? T( -delta ) : T( delta )))) {
+ std::ostringstream oss;
+ oss << std::setprecision( 13 ) << a << " != " << b << " +/- " << delta;
+ return failure( file, line, oss.str(), comment );
+ }
+ return success();
+ }
+
+ asserter &failure( const char *file, int line, const std::string &comparison,
+ const std::string &comment = std::string() )
+ {
+ ++failures;
+ const char *needle = "/";
+ const char *slash = std::find_end( file, file + strlen( file ),
+ needle, needle + strlen( needle ));
+ if ( slash == file + strlen( file ))
+ slash = file;
+ else
+ slash += 1;
+
+ std::ostringstream oss;
+ oss
+ << std::setw( 24 ) << slash << ", "
+ << std::setw( -5 ) << line
+ << "; FAILURE: " << comparison
+ << ( comment.size() ? ": " : "" ) << comment
+ << std::endl;
+ out = oss.str();
+ failed = true;
+ return *this;
+ }
+
+ asserter &success()
+ {
+ out.clear();
+ failed = false;
+ return *this;
+ }
+ }; // class asserter
+} // namespace ezpwd
+
+std::ostream &operator<<(
+ std::ostream &lhs,
+ ezpwd::asserter &rhs )
+{
+ return rhs.output( lhs );
+}
+
+#endif // _EZPWD_ARRAY
diff --git a/op25/gr-op25_repeater/lib/ezpwd/bch b/op25/gr-op25_repeater/lib/ezpwd/bch
new file mode 100644
index 0000000..eb45db6
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/bch
@@ -0,0 +1,485 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2017, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. The Djelic BCH code
+ * under djelic/ and the c++/ezpwd/bch_base wrapper is redistributed under the terms of the GPLv2+,
+ * regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_BCH
+#define _EZPWD_BCH
+
+#include <sstream>
+#include "rs_base" // Basic DEBUG, EZPWD_... preprocessor stuff, ezpwd::log_, etc.
+#include "bch_base"
+
+namespace ezpwd {
+ //
+ // ezpwd::bch_base -- Interface to underlying Djelic Linux Kernel API
+ // ezpwd::bch<SYMBOLS, CORRECTION> -- General BCH codec types; min. CORRECTION capacity, undefined PAYLOAD
+ //
+ // These implementations retain the original Djelic Linux Kernel API; specifically, they find
+ // a BCH codec of the given Galois order M (ie. has codewords of size 2**M-1), and at least the
+ // target bit-error correction capacity T. They may correct more than T errors, and the number
+ // of parity ECC bits will be selected by the algorithm. You need to compute the maximum
+ // non-parity payload by computing _bch->n - _bch->ecc_bits.
+ //
+ // The data and parity bits must always be on separate blocks of int8_t/uint8_t-sized data
+ // in the container. This is required because the underlying API must break the data and parity
+ // out as separate arrays for processing. So, if the computed ecc_bits is not evenly divisible
+ // by 8, some care must be taken to ensure that it is packed into exactly ecc_bytes of data at
+ // the end of the supplied container. Alternatively, it can be kept in a separate container.
+ // This is probably safest, as the bch_base/bch/BCH classes will never attempt to resize the
+ // data/parity containers when supplied separately.
+ //
+ // Like the Reed-Solomon APIs, the bch_base/bch/BCH APIs will alter the size of a variable
+ // container in encode(...), to add the BCH ECC "parity" data (eg. std::vector, std::string).
+ // Fixed containers (eg. std::array) are never resized, and it is assumed that ecc_bytes of
+ // parity data exist at the end of the container.
+ //
+ class bch_base {
+ public:
+ ezpwd::bch_control *_bch;
+
+ bch_base( const bch_base & ) = delete; // no copy-constructor
+
+ bch_base(
+ size_t m,
+ size_t t,
+ unsigned int prim_poly = 0 )
+ : _bch( ezpwd::init_bch( int( m ), int( t ), prim_poly ))
+ {
+ ;
+ }
+
+ virtual ~bch_base()
+ {
+ ezpwd::free_bch( this->_bch );
+ }
+
+ size_t ecc_bytes()
+ const
+ {
+ return _bch->ecc_bytes;
+ }
+ size_t ecc_bits()
+ const
+ {
+ return _bch->ecc_bits;
+ }
+
+ size_t t()
+ const
+ {
+ return _bch->t;
+ }
+
+ //
+ // <ostream> << bch_base -- output codec in standard BCH( N, N-ECC, T ) form
+ //
+ virtual std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ return lhs << *this->_bch;
+ }
+
+ //
+ // encode -- container interfaces
+ //
+ // Returns number of ECC *bits* initialized (to be consistent w/ decode, which returns
+ // number of bit errors corrected).
+ //
+ int encode(
+ std::string &data )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ data.resize( data.size() + ecc_bytes() );
+ return encode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ));
+ }
+
+ int encode(
+ const std::string &data,
+ std::string &parity )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<const uT *, const uT *>
+ cuTpair;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ parity.resize( ecc_bytes() );
+ return encode( cuTpair( (const uT *)&data.front(), (const uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ));
+ }
+
+ template < typename T >
+ int encode(
+ std::vector<T> &data )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ data.resize( data.size() + ecc_bytes() );
+ return encode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ));
+ }
+
+ template < typename T >
+ int encode(
+ const std::vector<T>&data,
+ std::vector<T> &parity )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<const uT *, const uT *>
+ cuTpair;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ parity.resize( ecc_bytes() );
+ return encode( cuTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ));
+ }
+
+ template < typename T, size_t N >
+ int encode(
+ std::array<T,N> &data,
+ int pad = 0 ) // ignore 'pad' symbols at start of array
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return encode( uTpair( (uT *)&data.front() + pad, (uT *)&data.front() + data.size() ));
+ }
+
+
+ //
+ // encode -- denote data+parity or data, parity using pairs of uint8_t iterators
+ // encode -- base implementation, in terms of uint8_t pointers
+ //
+ virtual int encode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data )
+ const
+ {
+ return encode( data.first, data.second - data.first - ecc_bytes(), data.second - ecc_bytes() );
+ }
+
+ virtual int encode(
+ const std::pair<const uint8_t *, const uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity )
+ const
+ {
+ if ( size_t( parity.second - parity.first ) != ecc_bytes() ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "BCH: parity length incompatible with number of ECC bytes", -1 );
+ }
+ return encode( data.first, data.second - data.first, parity.first );
+ }
+
+ virtual int encode(
+ const uint8_t *data,
+ size_t len,
+ uint8_t *parity )
+ const
+ {
+ memset( parity, 0, ecc_bytes() ); // Djelic encode_bch requires ECC to be initialized to 0
+ ezpwd::encode_bch( this->_bch, data, len, parity );
+ return int( ecc_bits() );
+ }
+
+ //
+ // decode -- container interface, w/ optional corrected bit-error positions reported
+ //
+ // Does not correct errors in parity!
+ //
+ int decode(
+ std::string &data,
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ position );
+ }
+
+ int decode(
+ std::string &data,
+ std::string &parity,
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ),
+ position );
+ }
+
+ template < typename T >
+ int decode(
+ std::vector<T> &data,
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ position );
+ }
+
+ template < typename T >
+ int decode(
+ std::vector<T> &data,
+ std::vector<T> &parity,
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ),
+ position );
+ }
+
+ template < typename T, size_t N >
+ int decode(
+ std::array<T,N> &data,
+ int pad = 0, // ignore 'pad' symbols at start of array
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front() + pad, (uT *)&data.front() + data.size() ),
+ position );
+ }
+
+ //
+ // decode -- denote data+parity or data, parity using pairs of uint8_t iterators
+ // decode -- decode and correct BCH codeword, returning number of corrections, or -1 if failed
+ //
+ // Corrects data in-place (unlike the basic Djelic Linux Kernel API, which only returns
+ // error positions. For consistency with ezpwd::rs..., we report all error positions as
+ // std::vector<int>, even though the underlying Djelic API reports them as arrays of
+ // unsigned int.
+ //
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ std::vector<int> *position= 0 )
+ const
+ {
+ return decode( data.first, data.second - data.first - ecc_bytes(), data.second - ecc_bytes(),
+ position );
+ }
+
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity,
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( size_t( parity.second - parity.first ) != ecc_bytes() ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "BCH: parity length incompatible with number ECC bytes", -1 );
+ }
+ return decode( data.first, data.second - data.first, parity.first,
+ position );
+ }
+ virtual int decode(
+ uint8_t *data,
+ size_t len,
+ uint8_t *parity,
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( position )
+ position->resize( t() * 2 ); // may be able to correct beyond stated capacity!
+ int corrects = ezpwd::correct_bch(
+ this->_bch, data, len, parity, 0, 0,
+ position ? (unsigned int *)&(*position)[0] : 0 );
+ if ( position && corrects >= 0 )
+ position->resize( corrects );
+ return corrects;
+ }
+
+ //
+ // {en,de}coded -- returns an encoded/corrected copy of the provided container
+ //
+ // NOTE:
+ //
+ // Must return exceptions on failure; If exceptions inhibited, returns a
+ // default-constructed instance of the supplied data container. This may be sufficient to
+ // reliably deduce failure; if not, this interface should not be used.
+ //
+ // Overloads decoded to also allow recovery of corrected error positions and count.
+ //
+ template <typename C>
+ C encoded(
+ C data )
+ const
+ {
+ if ( encode( data ) < 0 )
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "BCH: Could not encode data", C() );
+ return data;
+ }
+
+ template <typename C>
+ C decoded(
+ C data )
+ const
+ {
+ if ( decode( data ) < 0 )
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "BCH: Could not decode data", C() );
+ return data;
+ }
+
+ template <typename C>
+ C decoded(
+ C data,
+ std::vector<int> &position )
+ const
+ {
+ if ( decode( data, &position ) < 0 )
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "BCH: Could not decode data", C() );
+ return data;
+ }
+
+ }; // class bch_base
+
+ template < size_t SYMBOLS, size_t CORRECTION >
+ class bch
+ : public bch_base
+ {
+ public:
+ bch()
+ : bch_base( ezpwd::log_<SYMBOLS + 1>::value, CORRECTION )
+ {
+ ;
+ }
+
+ virtual ~bch()
+ {
+ ;
+ }
+ }; // class bch
+
+ //
+ // std::ostream << ezpwd::bch_base
+ //
+ // Output a BCH codec description in standard form eg. BCH( 255, 239, 2 )
+ //
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::bch_base
+ &rhs )
+ {
+ return rhs.output( lhs );
+ }
+
+ //
+ // ezpwd::BCH<SYMBOLS, PAYLOAD, CAPACITY> -- Standard BCH codec types
+ //
+ // Specify and create a standard BCH codec with exactly the specified capacities. We create
+ // the undering BCH codec using SYMBOLS and CORRECTION capacity; the actual correction capacity
+ // T, the number of PARITY bits and hence PAYLOAD (CAPACITY - PARITY) is selected automatically
+ // by the underlying Djelic Linux Kernel BCH codec API. For this interface, we demand that the
+ // caller *knows* all of these values at compile time, however, mostly for future optimization
+ // purposes. We validate them, and fail the constructor if they don't match. See bch_test for
+ // an enumeration of all possible BCH codecs.
+ //
+ // In the future, this API may be re-implemented to not use the generic BCH API, but a more
+ // optimized locally-defined implementation that leverages the fixed SYMBOLS, PAYLOAD and
+ // CORRECTION capacities to produce more optimal code.
+ //
+ template < size_t SYMBOLS, size_t PAYLOAD, size_t CORRECTION >
+ class BCH
+ : public bch<SYMBOLS, CORRECTION>
+ {
+ public:
+ static const size_t M = ezpwd::log_<SYMBOLS + 1>::value; // Galois field order; eg. 255 --> 8
+ static const size_t N = SYMBOLS;
+ static const size_t T = CORRECTION;
+ static const size_t LOAD = PAYLOAD;
+
+ BCH()
+ : bch<SYMBOLS, CORRECTION>()
+ {
+ if ( this->_bch->t != T || this->_bch->n != N
+ || this->_bch->n - this->_bch->ecc_bits != LOAD ) {
+ std::ostringstream err;
+ this->output( err )
+ << " specified doesn't match underlying " << *this->_bch << " produced.";
+ EZPWD_RAISE_OR_ABORT( std::runtime_error, err.str().c_str() );
+ }
+ }
+
+ virtual ~BCH()
+ {
+ ;
+ }
+
+ //
+ // <ostream> << BCH<...> -- output codec in standard BCH( N, N-ECC, T ) form
+ //
+ virtual std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ return lhs
+ << "BCH( " << std::setw( 3 ) << N
+ << ", " << std::setw( 3 ) << LOAD
+ << ", " << std::setw( 3 ) << T
+ << " )";
+ }
+ }; // class BCH
+
+
+ //
+ // std::ostream << ezpwd::BCH<...>
+ //
+ // Output a BCH codec description in standard form eg. BCH( 255, 239, 2 )
+ //
+ // NOTE: clang/gcc disagree on the scoping of operator<< template/non-template functions...
+ //
+ template <size_t SYMBOLS, size_t PAYLOAD, size_t CORRECTION>
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::BCH<SYMBOLS, PAYLOAD, CORRECTION>
+ &rhs )
+ {
+ return rhs.output( lhs );
+ }
+
+} // namespace ezpwd
+
+#endif // _EZPWD_BCH
diff --git a/op25/gr-op25_repeater/lib/ezpwd/bch_base b/op25/gr-op25_repeater/lib/ezpwd/bch_base
new file mode 100644
index 0000000..0aa0592
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/bch_base
@@ -0,0 +1,219 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2017, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. The Djelic BCH code
+ * under djelic/ and the c++/ezpwd/bch_base wrapper is redistributed under the terms of the GPLv2+,
+ * regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_BCH_BASE
+#define _EZPWD_BCH_BASE
+
+#include <iostream>
+#include <iomanip>
+#include <vector>
+
+//
+// Presently, we simply import the Linux Kernel's "C" BCH API directly into the ezpwd:: namespace In
+// order to compile, you must (at least) run "make djelic" in the base directory of the
+// https://github.com/pjkundert/bch.git repo.
+//
+namespace ezpwd {
+ /**
+ * struct bch_control - BCH control structure
+ * @m: Galois field order
+ * @n: maximum codeword size in bits (= 2^m-1)
+ * @t: error correction capability in bits
+ * @ecc_bits: ecc exact size in bits, i.e. generator polynomial degree (<=m*t)
+ * @ecc_bytes: ecc max size (m*t bits) in bytes
+ * @a_pow_tab: Galois field GF(2^m) exponentiation lookup table
+ * @a_log_tab: Galois field GF(2^m) log lookup table
+ * @mod8_tab: remainder generator polynomial lookup tables
+ * @ecc_buf: ecc parity words buffer
+ * @ecc_buf2: ecc parity words buffer
+ * @xi_tab: GF(2^m) base for solving degree 2 polynomial roots
+ * @syn: syndrome buffer
+ * @cache: log-based polynomial representation buffer
+ * @elp: error locator polynomial
+ * @poly_2t: temporary polynomials of degree 2t
+ */
+
+ /**
+ * init_bch - initialize a BCH encoder/decoder
+ * @m: Galois field order, should be in the range 5-15
+ * @t: maximum error correction capability, in bits
+ * @prim_poly: user-provided primitive polynomial (or 0 to use default)
+ *
+ * Returns:
+ * a newly allocated BCH control structure if successful, NULL otherwise
+ *
+ * This initialization can take some time, as lookup tables are built for fast
+ * encoding/decoding; make sure not to call this function from a time critical
+ * path. Usually, init_bch() should be called on module/driver init and
+ * free_bch() should be called to release memory on exit.
+ *
+ * You may provide your own primitive polynomial of degree @m in argument
+ * @prim_poly, or let init_bch() use its default polynomial.
+ *
+ * Once init_bch() has successfully returned a pointer to a newly allocated
+ * BCH control structure, ecc length in bytes is given by member @ecc_bytes of
+ * the structure.
+ */
+
+ /**
+ * encode_bch - calculate BCH ecc parity of data
+ * @bch: BCH control structure
+ * @data: data to encode
+ * @len: data length in bytes
+ * @ecc: ecc parity data, must be initialized by caller
+ *
+ * The @ecc parity array is used both as input and output parameter, in order to
+ * allow incremental computations. It should be of the size indicated by member
+ * @ecc_bytes of @bch, and should be initialized to 0 before the first call.
+ *
+ * The exact number of computed ecc parity bits is given by member @ecc_bits of
+ * @bch; it may be less than m*t for large values of t.
+ */
+
+ /**
+ * decode_bch - decode received codeword and find bit error locations
+ * @bch: BCH control structure
+ * @data: received data, ignored if @calc_ecc is provided
+ * @len: data length in bytes, must always be provided
+ * @recv_ecc: received ecc, if NULL then assume it was XORed in @calc_ecc
+ * @calc_ecc: calculated ecc, if NULL then calc_ecc is computed from @data
+ * @syn: hw computed syndrome data (if NULL, syndrome is calculated)
+ * @errloc: output array of error locations
+ *
+ * Returns:
+ * The number of errors found, or -EBADMSG if decoding failed, or -EINVAL if
+ * invalid parameters were provided
+ *
+ * Depending on the available hw BCH support and the need to compute @calc_ecc
+ * separately (using encode_bch()), this function should be called with one of
+ * the following parameter configurations -
+ *
+ * by providing @data and @recv_ecc only:
+ * decode_bch(@bch, @data, @len, @recv_ecc, NULL, NULL, @errloc)
+ *
+ * by providing @recv_ecc and @calc_ecc:
+ * decode_bch(@bch, NULL, @len, @recv_ecc, @calc_ecc, NULL, @errloc)
+ *
+ * by providing ecc = recv_ecc XOR calc_ecc:
+ * decode_bch(@bch, NULL, @len, NULL, ecc, NULL, @errloc)
+ *
+ * by providing syndrome results @syn:
+ * decode_bch(@bch, NULL, @len, NULL, NULL, @syn, @errloc)
+ *
+ * Once decode_bch() has successfully returned with a positive value, error
+ * locations returned in array @errloc should be interpreted as follows -
+ *
+ * if (errloc[n] >= 8*len), then n-th error is located in ecc (no need for
+ * data correction)
+ *
+ * if (errloc[n] < 8*len), then n-th error is located in data and can be
+ * corrected with statement data[errloc[n]/8] ^= 1 << (errloc[n] % 8);
+ *
+ * Note that this function does not perform any data correction by itself, it
+ * merely indicates error locations.
+ */
+
+ /**
+ * init_bch - initialize a BCH encoder/decoder
+ * @m: Galois field order, should be in the range 5-15
+ * @t: maximum error correction capability, in bits
+ * @prim_poly: user-provided primitive polynomial (or 0 to use default)
+ *
+ * Returns:
+ * a newly allocated BCH control structure if successful, NULL otherwise
+ *
+ * This initialization can take some time, as lookup tables are built for fast
+ * encoding/decoding; make sure not to call this function from a time critical
+ * path. Usually, init_bch() should be called on module/driver init and
+ * free_bch() should be called to release memory on exit.
+ *
+ * You may provide your own primitive polynomial of degree @m in argument
+ * @prim_poly, or let init_bch() use its default polynomial.
+ *
+ * Once init_bch() has successfully returned a pointer to a newly allocated
+ * BCH control structure, ecc length in bytes is given by member @ecc_bytes of
+ * the structure.
+ */
+
+ extern "C" {
+ #include "../../djelic_bch.h"
+ }
+
+ //
+ // correct_bch -- corrects data (but not parity!), as suggested by decode_bch, above
+ //
+ // A convenience interface that defaults all of the not strictly required parameters, and
+ // automatically corrects bit-errors in data *and* the supplied parity. Does not attempt to
+ // correct bit errors found in the parity data. If not supplied, 'errloc' is allocated
+ // internally; otherwise, it is assumed to be of at least size bch->t (the minimum error
+ // correction capacity of the BCH codec).
+ //
+ // However, beware -- at larger values of T, the actual correction capacity of the BCH codec
+ // could be greater than the requested T. Therefore, it is recommended that you always supply a
+ // larger than required errloc array; recommend T*2?
+ //
+ inline
+ int correct_bch(
+ struct bch_control *bch,
+ uint8_t *data,
+ unsigned int len,
+ uint8_t *recv_ecc,
+ const uint8_t *calc_ecc= 0,
+ const unsigned int *syn = 0,
+ unsigned int *errloc = 0 ) // must be sized at least bch->t; often, greater!
+ {
+ unsigned int _errloc[511]; // much larger than the correction capacity of largest supported BCH codec
+ if ( ! errloc )
+ errloc = _errloc;
+ int err = decode_bch( bch, data, len, recv_ecc, calc_ecc, syn, errloc );
+ if ( err > 0 ) {
+ // A +'ve number of bit-error correction locations were found
+ for ( int n = 0; n < err; ++n ) {
+ /**
+ * if (errloc[n] < 8*len), then n-th error is located in data and can be corrected
+ * with statement data[errloc[n]/8] ^= 1 << (errloc[n] % 8). If in the parity, it
+ * is assumed to be located at the end of the data, so offset by 'len' bytes.
+ */
+ if ( errloc[n] < 8*len ) {
+ data[errloc[n] / 8] ^= 1 << ( errloc[n] % 8 );
+ } else if ( recv_ecc && errloc[n] < 8 * len + 8 * bch->ecc_bytes ) {
+ recv_ecc[errloc[n] / 8 - len]
+ ^= 1 << ( errloc[n] % 8 );
+ }
+ }
+ }
+ return err;
+ }
+
+ //
+ // <ostream> << <ezpwd::bch_control> -- output codec in standard BCH( N, N-ECC, T ) form
+ //
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::bch_control
+ &bch )
+ {
+ return lhs
+ << "BCH( " << std::setw( 3 ) << bch.n
+ << ", " << std::setw( 3 ) << bch.n - bch.ecc_bits
+ << ", " << std::setw( 3 ) << bch.t
+ << " )";
+ }
+
+} // namespace ezpwd
+
+#endif // _EZPWD_BCH_BASE
diff --git a/op25/gr-op25_repeater/lib/ezpwd/corrector b/op25/gr-op25_repeater/lib/ezpwd/corrector
new file mode 100644
index 0000000..23a36a0
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/corrector
@@ -0,0 +1,506 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2014, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. c++/ezpwd/rs_base
+ * is redistributed under the terms of the LGPL, regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_CORRECTOR
+#define _EZPWD_CORRECTOR
+
+#include "rs"
+#include "serialize"
+
+namespace ezpwd {
+
+ //
+ // best_avg -- collect <password>,<confidence> guesses, and return the unambiguous best one
+ //
+ typedef std::map<std::string, std::pair<int, int>> // (<password>, (<count>, <avgsum>))
+ best_avg_base_t;
+ class best_avg
+ : public best_avg_base_t
+ {
+ public:
+ using best_avg_base_t::begin;
+ using best_avg_base_t::end;
+ using best_avg_base_t::insert;
+ using best_avg_base_t::find;
+ using best_avg_base_t::iterator;
+ using best_avg_base_t::const_iterator;
+ using best_avg_base_t::value_type;
+ using best_avg_base_t::mapped_type;
+ //
+ // add -- add the given pct to the current average for <string> str
+ //
+ iterator add(
+ const std::string &str,
+ int pct )
+ {
+ iterator i = find( str );
+ if ( i == end() )
+ i = insert( i, value_type( str, mapped_type() ));
+ i->second.first += 1;
+ i->second.second += pct;
+ return i;
+ }
+
+ //
+ // best -- return the unambiguously best value (average is >, or == but longer), or end()
+ //
+ const_iterator best()
+ const
+ {
+ const_iterator top = end();
+ bool uni = false;
+ for ( const_iterator i = begin(); i != end(); ++i ) {
+ if ( top == end()
+ or i->second.second/i->second.first > top->second.second/top->second.first
+ or ( i->second.second/i->second.first == top->second.second/top->second.first
+ and i->first.size() > top->first.size())) {
+ top = i;
+ uni = true;
+ } else if ( i->second.second/i->second.first == top->second.second/top->second.first
+ and i->first.size() == top->first.size()) {
+ uni = false;
+ }
+ }
+ return uni ? top : end();
+ }
+
+ //
+ // evaluation -- process a (<password>,(<count>,<avgsum>)) into (<average>,<password>)
+ // sort -- return a multimap indexed by <average> --> <string>
+ // output -- output the <string>: <average>, sorted by average
+ //
+ static std::pair<const int,const std::string &>
+ evaluation( const value_type &val )
+ {
+ return std::pair<const int,const std::string &>( val.second.second/val.second.first, val.first );
+ }
+ typedef std::multimap<const int,const std::string &>
+ sorted_t;
+ sorted_t sort()
+ const
+ {
+ sorted_t dst;
+ std::transform( begin(), end(), std::inserter( dst, dst.begin() ), evaluation );
+ return dst;
+ }
+ std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ for ( auto i : sort() )
+ lhs << std::setw( 16 ) << i.second
+ << ": " << std::setw( 3 ) << i.first
+ << std::endl;
+ return lhs;
+ }
+ };
+} // namespace ezpwd
+
+std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::best_avg &rhs )
+{
+ return rhs.output( lhs );
+}
+
+namespace ezpwd {
+ //
+ // ezpwd::corrector -- Apply statistical corrections to a string, returning the confidence
+ //
+ // All methods are static; no instance is required, as this is primarily used to create
+ // external language APIs.
+ //
+ template <
+ size_t PARITY,
+ size_t N = 64,
+ typename SERIAL = serialize::base< N, serialize::ezpwd< N >>>
+ class corrector {
+ public:
+ static
+ std::ostream &output(
+ std::ostream &lhs )
+ {
+ lhs << "corrector<PARITY=" << PARITY << ",N=" << N << ",SERIAL=" << SERIAL() << ">";
+ return lhs;
+ }
+
+ //
+ // parity(<string>) -- Returns 'PARITY' base-N symbols of R-S parity to the supplied password
+ //
+ static std::string parity(
+ const std::string &password )
+ {
+ std::string parity;
+ rscodec.encode( password, parity );
+ SERIAL::encode( parity );
+ return parity;
+ }
+
+ //
+ // encode(<string>) -- append PARITY base-N parity symbols to password
+ //
+ // The supplied password buffer size must be sufficient to contain PARITY additional
+ // symbols, plus the terminating NUL. Returns the resultant encoded password size
+ // (excluding the NUL).
+ //
+ static size_t encode(
+ std::string &password )
+ {
+ password += parity( password );
+ return password.size();
+ }
+
+ static size_t encode(
+ char *password,
+ size_t size ) // maximum available size
+ {
+ size_t len = ::strlen( password ); // length w/o terminating NUL
+ if ( len + PARITY + 1 > size )
+ throw std::runtime_error( "ezpwd::rspwd::encode password buffer has insufficient capacity" );
+ std::string par = parity( std::string( password, password + len ));
+ if ( par.size() != PARITY )
+ throw std::runtime_error( "ezpwd::rspwd::encode computed parity with incorrect size" );
+ std::copy( par.begin(), par.end(), password + len );
+ len += PARITY;
+ password[len] = 0;
+ return len;
+ }
+
+ //
+ // decode(<string>[,...]) -- Applies R-S error correction on the encoded string, removing parity
+ //
+ // Up to 'PARITY' Reed-Solomon parity symbols are examined, to determine if the supplied
+ // string is a valid R-S codeword and hence very likely to be correct. Optionally supply a
+ // vector of erasure positions.
+ //
+ // An optional 'minimum' final password length may be provided; no R-S parity is assumed
+ // to exist in the first 'minimum' password characters (default: PARITY). This prevents
+ // accidentally finding valid R-S codewords in passwords of known minimum length; validation
+ // codes, for example. Likewise, the optional 'maximum' allows us to limit the number of
+ // parity symbols that may be assumed to be missing from the end of the codeword.
+ //
+ // Returns a confidence strength rating, which is the ratio:
+ //
+ // 100 - ( errors * 2 + erasures ) * 100 / parity
+ //
+ // if an R-S codeword was solved, and 0 otherwise. If a codeword is solved, but the number
+ // of errors and erasures corrected indicates that all parity was consumed, the caller may
+ // opt to not use the corrected string, because there is a chance that our R-S polynomial
+ // was overwhelmed with errors and actually returned an incorrect codeword. Therefore,
+ // solving a codeword using all available parity results in 100 - PARITY * 100 / PARITY ==
+ // 0, which indicates that there is no certainty of correctness; all R-S parity resources
+ // were used in error/erasure recover, with none left to confirm that the result is actually
+ // correct. If only zero-strength results are achieved, the longest will be returned (the
+ // full, original string).
+ //
+ // Supports the following forms of error/erasure:
+ //
+ // 0) Full parity. All data and parity supplied, and an R-S codeword is solved.
+ //
+ // 1) Partial parity. All data and some parity supplied; remainder are deemed erasures.
+ //
+ // If PARITY > 2, then up to PARITY/2-1 trailing parity terms are marked as erasures.
+ // If the R-S codeword is solved and a safe number of errors are found, then we can have
+ // reasonable confidence that the string is correct.
+ //
+ // 1a) Erase errors. Permute the combinations of up to PARITY-1 erasures.
+ //
+ // o) Raw password. No parity terms supplied; not an R-S codeword
+ //
+ // If none of the error/erasure forms succeed, the password is returned unmodified.
+ //
+ // If a non-zero 'minimum' or 'maximum' are provided, they constrain the possible
+ // resultant password sizes that will be attempted.
+ //
+ static
+ int decode(
+ std::string &password,
+ const std::vector<int>
+ &erasures,
+ size_t minimum = PARITY,//always deemed at least 1
+ size_t maximum = 0 ) // if 0, no limit
+ {
+ int confidence;
+ best_avg best;
+
+ // Full/Partial parity. Apply some parity erasure if we have some erasure/correction
+ // capability while maintaining at least one excess parity symbol for verification.
+ // This can potentially result in longer password being returned, if the R-S decoder
+ // accidentally solves a codeword.
+ //
+ // For example, if PARITY=3 (or 4) then (PARITY+1)/2 == 2, and we would only attempt up
+ // to 1 parity erasure. This would leave 1 parity symbol to replace the 1 erasure, and
+ // 1 remaining to validate the integrity of the password.
+ //
+ // The password must be long enough to contain at least 1 non-parity symbol, and the
+ // designated number of non-erased parity symbols! However, by convention we'll demand
+ // that the password contain at least PARITY symbols -- any less, and we can
+ // accidentally correct the few remaining password symbols.
+ //
+ // Also, if any parity symbols won't decode (eg. were entered in error), we must deem
+ // them to be erasures, too, and if the number of erasures exceeds the capacity of the
+ // R-S codec, it'll fail (throw an exception, or at best solve with 0 confidence).
+ for ( size_t era = 0 // how many parity symbols to deem erased
+ ; era < (PARITY+1)/2
+ ; ++era ) {
+ if ( password.size() < ( minimum ? minimum : 1 ) + PARITY - era ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected too short password \""
+ << password << std::string( era, '_' )
+ << "\"" << " (" << era << " parity skipped)"
+ << std::endl;
+#endif
+ continue; // too few password symbols to start checking parity
+ }
+
+ if ( maximum and password.size() > maximum + PARITY - era ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected too long password \""
+ << password << std::string( era, '_' )
+ << "\"" << " (" << era << " parity skipped)"
+ << std::endl;
+#endif
+ continue; // too few parity symbols erased to start checking parity
+ }
+
+ // Copy password, adding 'era' additional NULs
+ std::string fixed( password.size() + era, 0 );
+ std::copy( password.begin(), password.end(), fixed.begin() );
+
+ // Decode the base-N parity, denoting any invalid (mistyped or trailing NUL) symbols
+ // as erasures (adjust erasure offsets to be from start of password, not start of
+ // parity). All newly added 'era' symbols will be NUL, and will be invalid. After
+ // decoding parity, if we've slipped below our minimum R-S capacity threshold
+ // (ie. because of mistyped parity symbols), don't attempt.
+ std::vector<int> all_era;
+ SERIAL::decode( fixed.begin() + fixed.size() - PARITY,
+ fixed.begin() + fixed.size(), &all_era, 0,
+ serialize::ws_invalid, serialize::pd_invalid );
+ if ( all_era.size() >= (PARITY+1)/2 ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected low parity password \""
+ << password << std::string( era, '_' )
+ << "\"" << " (" << all_era.size() << " parity erasures + "
+ << era << " skipped)"
+ << std::endl;
+#endif
+ continue; // Too many missing parity symbols
+ }
+ if ( all_era.size() + erasures.size() > PARITY ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected hi erasure password \""
+ << password << std::string( era, '_' )
+ << "\"" << " (" << all_era.size() + erasures.size() << " total erasures + "
+ << era << " skipped)"
+ << std::endl;
+#endif
+ continue; // Total erasures beyond capacity
+ }
+ for ( auto &o : all_era )
+ o += fixed.size() - PARITY;
+ std::copy( erasures.begin(), erasures.end(), std::back_inserter( all_era ));
+
+ // Enough parity to try to decode. A successful R-S decode with 0 (remaining)
+ // confidence indicates a successfully validated R-S codeword! Use it (ex. parity).
+ try {
+ std::vector<int> position;
+ int corrects= rscodec.decode( fixed, all_era, &position );
+ confidence = strength<PARITY>( corrects, all_era, position );
+ fixed.resize( fixed.size() - PARITY );
+ if ( confidence >= 0 )
+ best.add( fixed, confidence );
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Reed-Solomon w/ " << era << " of " << PARITY
+ << " parity erasures " << std::setw( 3 ) << confidence
+ << "% confidence: \"" << password
+ << "\" ==> \"" << fixed
+ << "\" (corrects: " << corrects
+ << ", erasures at " << all_era
+ << ", fixed at " << position << "): "
+ << std::endl
+ << best;
+#endif
+ } catch ( std::exception &exc ) {
+#if defined( DEBUG ) && DEBUG >= 2 // should see only when ezpwd::reed_solomon<...>::decode fails
+ output( std::cout ) << " invalid part parity password: " << exc.what() << std::endl;
+#endif
+ }
+ }
+
+ // Partial parity, but below threshold for usable error detection. For the first 1 to
+ // (PARITY+1)/2 parity symbols (eg. for PARITY == 3, (PARITY+1)/2 == 1 ), we cannot
+ // perform meaningful error or erasure detection. However, if we see that the terminal
+ // symbols match the R-S symbols we expect from a correct password, we'll ascribe a
+ // partial confidence due to the matching parity symbols.
+ //
+ // password: sock1t
+ // w/ 3 parity: sock1tkeB
+ // password ----^^^^^^
+ // ^^^--- parity
+ //
+ for ( size_t era = (PARITY+1)/2 // how many parity symbols are not present
+ ; era < PARITY
+ ; ++era ) {
+ if ( password.size() < ( minimum ? minimum : 1 ) + PARITY - era ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected too short password \""
+ << password << std::string( era, '_' )
+ << "\""
+ << std::endl;
+#endif
+ continue; // too few password symbols to start checking parity
+ }
+ if ( maximum and password.size() > maximum + PARITY - era ) {
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Rejected too long password \""
+ << password << std::string( era, '_' )
+ << "\"" << " (" << era << " parity skipped)"
+ << std::endl;
+#endif
+ continue; // too few parity symbols erased to start checking parity
+ }
+ std::string fixed = password;
+ size_t len = password.size() - ( PARITY - era );
+ fixed.resize( len );
+ encode( fixed );
+ auto differs = std::mismatch( fixed.begin(), fixed.end(), password.begin() );
+ size_t par_equ = differs.second - password.begin();
+ if ( par_equ < len || par_equ > len + PARITY )
+ throw std::runtime_error( "miscomputed R-S parity matching length" );
+ par_equ -= len;
+
+ // At least one parity symbol is requires to give any confidence
+ if ( par_equ > 0 ) {
+ std::string basic( fixed.begin(), fixed.begin() + len );
+ confidence = par_equ * 100 / PARITY; // each worth a normal parity symbol
+ best.add( basic, confidence );
+#if defined( DEBUG ) && DEBUG >= 1
+ output( std::cout )
+ << " Check Chars. w/ " << era << " of " << PARITY
+ << " parity missing " << std::setw( 3 ) << confidence
+ << "% confidence: \"" << password
+ << "\" ==> \"" << basic
+ << " (from computed: \"" << fixed << "\")"
+ << ": "
+ << std::endl
+ << best;
+#endif
+ }
+ }
+
+ // Select the best guess and return its confidence. Otherwise, use raw password? If no
+ // error/erasure attempts succeeded (if no 'best' w/ confidence >= 0), then we'll use
+ // the raw password w/ 0 confidence, if it meets the minimum/maximum length
+ // requirements.
+ confidence = -1;
+ if ( password.size() >= ( minimum ? minimum : 1 )
+ and ( maximum == 0 or password.size() <= maximum ))
+ confidence = 0;
+
+ typename best_avg::const_iterator
+ bi = best.best();
+#if defined( DEBUG )
+ output( std::cout )
+ << " Selected " << ( bi != best.end() ? "corrected" : "unmodified" )
+ << " password \"" << ( bi != best.end() ? bi->first : password )
+ << "\" of length " << ( minimum ? minimum : 1) << "-" << maximum
+ << " (vs. \"" << password
+ << "\") w/ confidence " << (bi != best.end() ? bi->second.second : confidence )
+ << "%, from: "
+ << std::endl
+ << best;
+#endif
+ if ( bi != best.end() ) {
+ auto better = best.evaluation( *bi ); // --> (<average>,<password>)
+ password = better.second;
+ confidence = better.first;
+ }
+ return confidence;
+ }
+
+ static
+ int decode(
+ std::string &password,
+ size_t minimum = PARITY,
+ size_t maximum = 0 )
+ {
+ return decode( password, std::vector<int>(), minimum, maximum );
+ }
+
+ //
+ // decode(<char*>,<size_t>,<size_t>,<size_t>) -- C interface to decode(<string>)
+ //
+ // Traditional C interface. The provided NUL-terminated password+parity is decoded
+ // (parity removed), and the confidence % is returned.
+ //
+ // If any failure occurs, a -'ve value will be returned, and the supplied password
+ // buffer will be used to contain an error description.
+ //
+ static int decode(
+ char *password, // NUL terminated
+ size_t siz, // available size
+ size_t minimum = PARITY,//minimum resultant password length
+ size_t maximum = 0 ) // maximum ''
+ {
+ std::string corrected( password );
+ int confidence;
+ try {
+ confidence = decode( corrected, minimum, maximum );
+ if ( corrected.size() + 1 > siz )
+ throw std::runtime_error( "password buffer has insufficient capacity" );
+ std::copy( corrected.begin(), corrected.end(), password );
+ password[corrected.size()] = 0;
+ } catch ( std::exception &exc ) {
+ confidence = -1;
+ ezpwd::streambuf_to_buffer sbf( password, siz );
+ std::ostream( &sbf ) << "corrector<" << PARITY << "> failed: " << exc.what();
+ }
+ return confidence;
+ }
+
+ //
+ // rscodec -- A ?-bit RS(N-1,N-1-PARITY) Reed-Solomon codec
+ //
+ // Encodes and decodes R-S symbols over the lower 6 bits of the supplied data. Requires
+ // that the last N (parity) symbols of the data are in the range [0,63]. The excess bits on
+ // the data symbols are masked and restored during decoding.
+ //
+ static const ezpwd::RS<N-1,N-1-PARITY>
+ rscodec;
+ };
+
+ template < size_t PARITY, size_t N, typename SERIAL >
+ const ezpwd::RS<N-1,N-1-PARITY>
+ corrector<PARITY,N,SERIAL>::rscodec;
+
+} // namespace ezpwd
+
+template < size_t PARITY, size_t N, typename SERIAL >
+std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::corrector<PARITY,N,SERIAL>
+ &rhs )
+{
+ return rhs.output( lhs );
+}
+
+#endif // _EZPWD_CORRECTOR
diff --git a/op25/gr-op25_repeater/lib/ezpwd/definitions b/op25/gr-op25_repeater/lib/ezpwd/definitions
new file mode 100644
index 0000000..1ecf9a4
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/definitions
@@ -0,0 +1,9 @@
+//
+// C++ Definitions -- include once in a single C++ compilation unit
+//
+#ifndef _EZPWD_DEFINITIONS
+#define _EZPWD_DEFINITIONS
+
+#include "serialize_definitions"
+
+#endif // _EZPWD_DEFINITIONS \ No newline at end of file
diff --git a/op25/gr-op25_repeater/lib/ezpwd/ezcod b/op25/gr-op25_repeater/lib/ezpwd/ezcod
new file mode 100644
index 0000000..8fe0a90
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/ezcod
@@ -0,0 +1,725 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2014, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. c++/ezpwd/rs_base
+ * is redistributed under the terms of the LGPL, regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_EZCOD
+#define _EZPWD_EZCOD
+
+#include <math.h> // M_PI
+#include <cmath>
+#include <cctype>
+
+#include <cstdint>
+#include <ezpwd/rs>
+#include <ezpwd/output>
+#include <ezpwd/serialize>
+
+//
+// EZCOD 3:10 location code w/ Reed-Solomon Error Correction, and average 3m accuracy
+//
+// - each successive symbol provides greater precision
+// - codes nearby each-other are identical in leading characters
+// - average 3m precision achieved in 9 symbols
+// - more than 4 base-10 digits of precision in both lat and lon after the decimal
+// - from 1 to 3 symbols of Reed-Solomon parity
+// - 1 parity symbol supplies validation w/ strength equivalent to a check character
+// - 2 parity symbols provides correction of 1 lost symbol (no errors)
+// - 3 parity symbols provides correction of any 1 error, with verification,
+// or recovery of up to any 3 lost symbols (with no other errors)
+//
+
+//
+// To achieve at least 4 decimal digits of precision after the decimal point, we must have
+// defined lat to within 1 part in 1,800,000, and lon to within 1 part in 3,600,000. As each symbol
+// supplies bits, we'll refine the computed lat/lon further, reducing the outstanding fraction of
+// "parts" yet to be defined.
+//
+// bits
+// symbols latitude longitude
+// bits mul parts bits mul parts
+// 1 2 4 4 3 8 8
+// 2 2 4 16 3 8 64
+// 3 3 8 128 2 4 256 // not quite integer lat/lon accuracy
+//
+// 4 2 4 512 3 8 2,048
+// 5 3 8 4,096 2 4 8,192
+// 6 2 4 16,384 3 8 65,536
+//
+// 7 3 8 131,072 2 4 262,144
+// 8 2 4 524,288 3 8 2,097,152
+// 9 3 8 4,194,304 2 4 8,388,608 parts resolution in 3:10 code
+// over [-90, 90] over [-180,180] yields ~3m resolution
+//
+// vs. 1,800,000 3,600,000 parts resolution in 10:10 code
+// over [-90, 90] over [-180,180] yields ~10m resolution
+//
+// Therefore, within 9 symbols we define lat and lon with better than double the precision of
+// 10:10 code's 4 decimal digits after the decimal point. This yields an approximate lineal
+// precision of 40,075,000m / 8,388,608 == ~5m in both dimensions at the equator, vs. 40,075,000m /
+// 3,600,000 == ~11m for 10:10 codes.
+//
+// The 10:10 code provides a single check character, which provides about P(1-1/32) certainty
+// that the provided code is correct. With EZCOD 3:10/11/12 codes, we provide varying levels of
+// detection/correction strength.
+//
+// - 1 parity symbol: act as a check character (like 10:10 codes), or provide 1 symbol of erasure
+// (lost symbol) recovery with no excess parity for validation.
+//
+// - 2 parity symbols: provide 1 symbol of erasure correction (w/ no other errors) with 1 excess parity
+// symbol for validation, or 1 symbol of error detection with no excess parity for validation.
+//
+// - 3 parity symbols: correct 1 error anywhere w/ 1 excess parity symbol for validation, or up
+// to 3 erasures with no excess parity for validation.
+//
+// Therefore, we'll provide Reed-Solomon RS(31,28-30) error correction (5 bit symbols,
+// indicating 31 symbols in the field, and from 1 to 3 roots, therefore up to 28 data symbols in the
+// field) over the 9 lat/lon data symbols.
+//
+//
+// MINIMIZING ERROR
+//
+// Each input lat/lon coordinate will be effectively truncated by the encoding procedure to the
+// level of precision (parts) encoded by each symbol. Subsequent symbols then add their (smaller)
+// parts to increase precision.
+//
+// After the last symbol, we know that the actual input coordinates where somewhere
+// within the rectangle:
+//
+// [0,0] -> [0,lon_precision] -> [lat_precision,lon_precision] -> [lat_precision,0]
+//
+// At first glance, the best way is to perform rounding instead of truncation on ecoding, by
+// simply adding 1/2 of the precision. Then, the unmodified output lat/lon decoded represents the
+// point nearest actual input coordinate. However, this is NOT ideal. Remember -- the decoding may
+// not have access to all the symbols! We want to minimize the error even if only some of the
+// symbols are available. Thus, we must apply a correction on decoding.
+//
+// One way gain rounding instead of truncation on decoding is, after adding the last symbol's
+// precision, to add 50% of the value represented by the first bit of the next (missing) symbol's
+// precision parts. This would be analogous to receiving the first 2 digits of a 3 digit number:
+//
+// original: 123
+// received: 12_
+// range: [120,130)
+// guessed: 125 (add 1/2 of the parts represented by the missing digit)
+//
+// If this is done, then the resulting coordinate would be in the middle of the rectangle of
+// possible input lat/lon values that could have resulted in the encoded value. This also works if
+// we don't receive and decode all of the symbols; We'll end up with a lat/lon in the middle of the
+// (large) rectangle of possible input coordinates.
+//
+
+
+namespace ezpwd {
+
+ class ezcod_base {
+ public:
+ double latitude; // [-90,+90] angle, degrees
+ double latitude_error; // total error bar, in meters
+ double longitude; // [-180,180]
+ double longitude_error; // total error bar, in meters
+ double accuracy; // linear accuracy radius, in meters
+ int confidence; // % parity in excess of last decode
+ double certainty; // and the associated probability
+
+ explicit ezcod_base(
+ double _lat = 0,
+ double _lon = 0 )
+ : latitude( _lat )
+ , latitude_error( 0 )
+ , longitude( _lon )
+ , longitude_error( 0 )
+ , accuracy( 0 )
+ , confidence( 100 )
+ , certainty( 1 )
+ {
+ ;
+ }
+ virtual ~ezcod_base()
+ {
+ ;
+ }
+
+ typedef std::pair<unsigned char, unsigned char>
+ symbols_t;
+ virtual symbols_t symbols()
+ const
+ = 0;
+ virtual std::ostream &output(
+ std::ostream &lhs )
+ const
+ = 0;
+ virtual std::string encode(
+ unsigned _preci = 0 ) // override precision
+ const
+ = 0;
+ virtual int decode(
+ const std::string &_ezcod )
+ = 0;
+ };
+} // namespace ezpwd
+
+inline std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::ezcod_base
+ &rhs )
+{
+ return rhs.output( lhs );
+}
+
+namespace ezpwd {
+
+ //
+ // ezcod<P,L> -- defaults to 1 PARITY and 9 location symbols (3m) of PRECISION
+ //
+ template < unsigned P=1, unsigned L=9 >
+ class ezcod
+ : public ezcod_base {
+
+ private:
+ typedef std::array<symbols_t, 12>
+ bits_t;
+ static const bits_t bits;
+ typedef std::array<std::pair<uint32_t, uint32_t>, 12>
+ parts_t;
+ static const parts_t parts;
+
+#if defined( DEBUG )
+ public:
+#endif
+ static const ezpwd::RS<31,31-P>
+ rscodec;
+
+ public:
+ static constexpr const unsigned PARITY = P; // specified symbols of R-S parity
+ static constexpr const unsigned PRECISION = L; // default symbols of location precision
+ static constexpr const unsigned CHUNK = 3; // default chunk size
+
+ static constexpr const char SEP_NONE = -1;
+ static constexpr const char SEP_DEFAULT = 0;
+ static constexpr const char SEP_DOT = '.';
+ static constexpr const char SEP_BANG = '!';
+ static constexpr const char SEP_SPACE = ' ';
+
+ static constexpr const char CHK_NONE = -1;
+ static constexpr const char CHK_DEFAULT = 0;
+ static constexpr const char CHK_DASH = '-';
+ static constexpr const char CHK_SPACE = ' ';
+
+ unsigned precision;
+ unsigned chunk; // Location symbol chunk sizes
+ char separator; // Separator between location and parity symbols
+ char space; // Fill space between location symbol chunks
+
+ //
+ // ezcod<P,L>() -- supply non-defaults for location precision, chunk size, etc.
+ //
+ explicit ezcod(
+ double _lat = 0,
+ double _lon = 0,
+ unsigned _preci = 0,
+ unsigned _chunk = 0,
+ char _seper = 0,
+ char _space = 0 )
+ : ezcod_base( _lat, _lon )
+ , precision( _preci ? _preci : PRECISION )
+ , chunk( _chunk ? _chunk : CHUNK )
+ , separator( _seper )
+ , space( _space )
+ {
+ if ( P < 1 )
+ throw std::runtime_error( "ezpwd::ezcod:: At least one parity symbol must be specified" );
+ if ( precision < 1 || precision > bits.max_size() )
+ throw std::runtime_error( std::string( "ezpwd::ezcod:: Only 1-" )
+ + std::to_string( bits.max_size() )
+ + " location symbol may be specified" );
+ }
+ explicit ezcod(
+ const std::string &_ezcod,
+ unsigned _preci = 0,
+ unsigned _chunk = 0,
+ char _seper = 0,
+ char _space = 0 )
+ : ezcod( 0, 0, _preci, _chunk, _seper, _space )
+ {
+ decode( _ezcod );
+ }
+ virtual ~ezcod()
+ {
+ ;
+ }
+
+ //
+ // symbols -- return working parity and location precision
+ //
+ virtual ezcod_base::symbols_t
+ symbols()
+ const
+ {
+ return ezcod_base::symbols_t( P, precision );
+ }
+
+ virtual std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ std::streamsize prec = lhs.precision();
+ std::ios_base::fmtflags
+ flg = lhs.flags();
+ lhs.precision( 10 );
+ std::string uni = "m ";
+ double acc = accuracy;
+ double dec = 2;
+ if ( acc > 1000 ) {
+ uni = "km";
+ acc /= 1000;
+ } else if ( acc < 1 ) {
+ uni = "mm";
+ acc *= 1000;
+ }
+ if ( acc >= 100 )
+ dec = 0;
+ else if ( acc >= 10 )
+ dec = 1;
+
+ lhs << encode( precision )
+ << " (" << std::setw( 3 ) << confidence
+ << "%) == " << std::showpos << std::fixed << std::setprecision( 10 ) << std::setw( 15 ) << latitude
+ << ", " << std::showpos << std::fixed << std::setprecision( 10 ) << std::setw( 15 ) << longitude
+ << " +/- " << std::noshowpos << std::fixed << std::setprecision( dec ) << std::setw( 6 ) << acc << uni;
+ lhs.precision( prec );
+ lhs.flags( flg );
+ return lhs;
+ }
+
+ //
+ // encode() -- encode the lat/lon to 'precision' symbols EZCOD representation
+ //
+ virtual std::string encode(
+ unsigned _preci = 0 ) // override precision
+ const
+ {
+ // Convert lat/lon into a fraction of number of parts assigned to each
+ double lat_frac= ( latitude + 90 ) / 180;
+ if ( lat_frac < 0 || lat_frac > 1 )
+ throw std::runtime_error( "ezpwd::ezcod::encode: Latitude not in range [-90,90]" );
+ double lon_frac= ( longitude + 180 ) / 360;
+ if ( lon_frac < 0 || lon_frac > 1 )
+ throw std::runtime_error( "ezpwd::ezcod::encode: Longitude not in range [-180,180]" );
+ if ( _preci == 0 )
+ _preci = precision;
+ if ( _preci < 1 || _preci > bits.max_size() )
+ throw std::runtime_error( std::string( "ezpwd::ezcod:: Only 1-" )
+ + std::to_string( bits.max_size() )
+ + " location symbol may be specified" );
+
+ // Compute the integer number of lat/lon parts represented by each coordinate, for the
+ // specified level of precision, and then truncate to the range [0,..._parts),
+ // eg. Latitude 90 --> 89.999...
+ uint32_t lat_parts = parts[_preci-1].first; // [ -90,90 ] / 4,194,304 parts in 9 symbols
+ uint32_t lon_parts = parts[_preci-1].second; // [-180,180] / 8,388,608 parts ''
+
+ uint32_t lat_rem = std::min( lat_parts-1, uint32_t( lat_parts * lat_frac ));
+ uint32_t lon_rem = std::min( lon_parts-1, uint32_t( lon_parts * lon_frac ));
+
+ // Initial loop condition; lat/lon multiplier is left at the base multiplier of the
+ // previous loop. Then, loop computing the units multiplier, and hten removing the most
+ // significant bits (multiples of the units multiplier). They will both reach 1
+ unsigned int lat_mult= lat_parts;
+ unsigned int lon_mult= lon_parts;
+
+ std::string res;
+ res.reserve( _preci // approximate result length
+ + ( chunk && chunk < _preci
+ ? _preci / chunk - 1
+ : 0 )
+ + 1 + P );
+ for ( auto &b : bits ) {
+ unsigned char lat_bits= b.first;
+ unsigned char lon_bits= b.second;
+ lat_mult >>= lat_bits;
+ lon_mult >>= lon_bits;
+ if ( ! lat_mult || ! lon_mult )
+ break;
+
+ // Each set of bits represents the number of times the current multiplier (after
+ // division by the number of bits we're outputting) would go into the remainder.
+ // Eg. If _mult was 1024, and _rem is 123 and _bits is 3, we're going to put out
+ // the next 3 bits of the value 199. The last value ended removing all multiples of
+ // 1024. So, we first get the new multiplier: 1024 >> 3 == 128. So, we're
+ // indicating, as a 3-bit value, how many multiples of 128 there are in the value
+ // 199: 199 / 128 == 1, so the 3-bit value we output is 001
+ uint32_t lat_val = lat_rem / lat_mult;
+ lat_rem -= lat_val * lat_mult;
+
+ uint32_t lon_val = lon_rem / lon_mult;
+ lon_rem -= lon_val * lon_mult;
+
+ res += char( ( lat_val << lon_bits ) | lon_val );
+ }
+
+ // Add the R-S parity symbols and base-32 encode, add parity separator and chunk
+ rscodec.encode( res );
+ serialize::base32::encode( res );
+ switch( separator ) {
+ case SEP_NONE:
+ break;
+ case SEP_DOT: default:
+ res.insert( _preci, 1, SEP_DOT );
+ break;
+ case SEP_BANG:
+ case SEP_SPACE:
+ res.insert( _preci, 1, separator );
+ break;
+ }
+ if ( space != CHK_NONE && chunk && chunk < _preci ) {
+ for ( unsigned c = _preci / chunk - 1; c > 0; --c ) {
+ switch ( space ) {
+ case CHK_NONE:
+ break;
+ case CHK_SPACE: default:
+ res.insert( c * chunk, 1, CHK_SPACE );
+ break;
+ case CHK_DASH:
+ res.insert( c * chunk, 1, space );
+ break;
+ }
+ }
+ }
+
+ return res;
+ }
+
+ //
+ // deserialize -- Extract base-32, skip whitespace, mark invalid symbols as erasures
+ // validate -- Remove base-32 encoding, validate and remove parity, returning confidence
+ // decode -- Attempt to decode a lat/lon, returning the confidence percentage
+ //
+ // If data but no parity symbols are supplied, no error checking is performed, and the
+ // confidence returned will be 0%. No erasures within the supplied data are allowed (as
+ // there is no capacity to correct them), and an exception will be thrown.
+ //
+ // If parity is supplied, then erasures are allowed. So long as the total number of
+ // erasures is <= the supplied parity symbols, then the decode will proceed (using the
+ // parity symbols to fill in the erasures), and the returned confidence will reflect the
+ // amount of unused parity capacity. Each erasure consumes one parity symbol to repair.
+ //
+ // We'll allow question-mark or any of the slash characters: "_/\?" to indicate an
+ // erasure. Either of the "!." symbol may be used to indicates the split between location
+ // symbols and parity symbols, and must be in a position that corresponds to the indicated
+ // number of location (this->precision) and parity 'P' symbols. Whitespace symbols and dash
+ // are ignored: " -".
+ //
+ // Thus, an EZCOD like "R3U 1JU QUY!0" may only be decoded by an ezcod<P=1>. Without
+ // the "!" or ".", it could be an ezcod<P=2> w/precision == 8 -- there's no way to know for
+ // sure. If no explicit position-parity separator is given, then we assume the default:
+ // this->precision location symbols, then up to P parity symbols. If additional parity
+ // symbols are supplied after the separator, then However, an ezcod...<P=3>
+ //
+ // If an explicit "!" or "." separator IS provided, then we will attempt to decode the
+ // position with the given number of position symbols, and up to P parity symbols.
+ //
+ // NOTE
+ //
+ // Due to a perhaps unexpected feature of R-S codewords, a codeword with MORE parity
+ // can be successfully decoded by an R-S codec specifying LESS parity symbols. It so
+ // happens that the data plus (excess) parity + (remaining) parity is STILL a valid codeword
+ // (so long as the R-S Galois parameters are identical).
+ //
+ // Therefore, EZCODs with more parity are accepted by EZCOD parsers configured for less
+ // parity. Of course, they will have less error/erasure correction strength -- using the
+ // correctly configured EZCOD codec expecting more R-S parity will maximize the value of all
+ // the supplied parity.
+ //
+ // The full amount of parity (ie. everything after the location/parity separator) is
+ // discarded in all cases, before the EZCOD location is decoded.
+ //
+ private:
+
+ unsigned deserialize(
+ std::string &dec,
+ std::vector<int> &erasure,
+ std::vector<char> &invalid )
+ const
+ {
+ serialize::base32::decode( dec, &erasure, &invalid );
+
+ // The special symbol '!' or '.' indicates the end of the EZCOD location symbols and the
+ // beginning of parity: ensure the symbol counts are consistent with the encoding. By
+ // default the parity symbols begin at offset precision. If we see more than precision
+ // symbols, we assume that the Lth and subsequent symbols are parity. If a
+ // location/parity separator is provided, it must be at position this->precision!
+ // Return offset of start of parity in codeword.
+ unsigned parbeg = this->PRECISION; // Parity begins after Location, by default
+ for ( unsigned i = 0; i < invalid.size(); ++i ) {
+ switch ( invalid[i] ) {
+ case '!': case '.':
+ // Remember the offset of the first parity symbol (it'll be in the position of
+ // the last '!' or '.' symbol we're about to erase), and adjust the indices of
+ // any erasures following.
+ parbeg = erasure[i];
+ dec.erase( parbeg, 1 );
+ invalid.erase( invalid.begin() + i );
+ erasure.erase( erasure.begin() + i );
+ for ( unsigned j = i; j < erasure.size(); ++j )
+ erasure[j] -= 1;
+ break;
+ case '_': case '/': case '\\': case '?':
+ break;
+ default:
+ throw std::runtime_error( std::string( "ezpwd::ezcod::decode: invalid symbol presented: '" )
+ + invalid[i] + "'" );
+ }
+ }
+#if defined( DEBUG ) && DEBUG >= 1
+ std::cout << " --> 0x" << std::vector<uint8_t>( dec.begin(), dec.begin() + std::min( size_t( parbeg ), dec.length()) )
+ << " + 0x" << std::vector<uint8_t>( dec.begin() + std::min( size_t( parbeg ), dec.length()),
+ dec.begin() + dec.length() )
+ << " parity" << std::endl;
+#endif
+ return parbeg;
+ }
+
+ int validate(
+ std::string &dec )
+ const
+ {
+ // Compute and return validity (which may later be assigned to this->confidence)
+ int validity = 0; // if no R-S parity provided
+
+#if defined( DEBUG ) && DEBUG >= 1
+ std::cout << *this << " validate( " << dec << " ) ";
+#endif
+ std::vector<int> erasure;
+ std::vector<char> invalid;
+ unsigned parbeg = deserialize( dec, erasure, invalid );
+
+ if ( dec.size() > parbeg || erasure.size() > 0 ) {
+ // Some R-S parity symbol(s) were provided (or erasures were marked). See if we can
+ // successfully decode/correct, or (at least) use one parity symbol as a check
+ // character. If we identify more erasures than R-S parity, we must fail; we can't
+ // recover the data. This will of course be the case if we have *any* erasures in
+ // the data, and no parity.
+ unsigned parity = 0;
+ if ( dec.size() > parbeg )
+ parity = dec.size() - parbeg;
+ while ( dec.size() < parbeg + P ) {
+ erasure.push_back( dec.size() );
+ dec.resize( dec.size() + 1 );
+ }
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout << " --> erasures: " << erasure.size() << " vs. parity: " << parity
+ << ": " << std::vector<uint8_t>( dec.begin(), dec.end() ) << std::endl;
+#endif
+ if ( erasure.size() > parity ) {
+ // We cannot do R-S decoding; not enough parity symbols to even cover erasures.
+ // If parity symbol(s) were provided ('parity' > 0), and all erasures were due the
+ // missing remaining parity symbols, we can use the existing parity symbol(s) as
+ // "check character(s)", by simply re-encoding the supplied non-parity data, and
+ // see if the generated parity symbol(s) match the supplied parity. This has
+ // basically the same strength as the 10:10 code's check character.
+ if ( parity + erasure.size() == P ) {
+ // All erasures must be at end, in remaining parity symbols!
+ std::string chk( dec.begin(), dec.begin() + parbeg );
+ rscodec.encode( chk );
+ // each parity symbol provided must match the corresponding encoded chk symbol
+ for ( unsigned i = 0; i < parity; ++i )
+ if ( dec[parbeg+i] != chk[parbeg+i] )
+ throw std::runtime_error( "ezpwd::ezcod::decode: Error correction failed; check character mismatch" );
+ // Check character(s) matched; erasure.size()/P of confidence gone
+ validity = ezpwd::strength<P>( erasure.size(), erasure, erasure );
+ } else
+ throw std::runtime_error( "ezpwd::ezcod::decode: Error correction failed; too many erasures" );
+ } else {
+ // We can try R-S decoding; we have (at least) enough parity to try to recover
+ // any missing symbol(s).
+ std::vector<int>position;
+ int corrects= rscodec.decode( dec, erasure, &position );
+ if ( corrects < 0 )
+ throw std::runtime_error( "ezpwd::ezcod::decode: Error correction failed; R-S decode failed" );
+ // Compute confidence, from spare parity capacity. Since R-S decode will not
+ // return the position of erasures that turn out (by accident) to be correct,
+ // but they have consumed parity capacity, we re-add them into the correction
+ // position vector. If the R-S correction reports more corrections than the
+ // parity can possibly have handled correctly, (eg. 2 reported erasures and an
+ // unexpected error), then the decode is almost certainly incorrect; fail.
+ validity = ezpwd::strength<P>( corrects, erasure, position );
+ if ( validity < 0 )
+ throw std::runtime_error( "ezpwd::ezcod::decode: Error correction failed; R-S decode overwhelmed" );
+ }
+ if ( dec.size() > parbeg )
+ dec.resize( parbeg ); // Discard any parity symbols
+ }
+ return validity;
+ }
+
+ public:
+ virtual int decode( const std::string &str )
+ {
+ // Decode the R-S encoding, computing the confidence. Will raise an exception on any
+ // error. Don't change this->confidence, this->latitude, ... until there is no longer a
+ // chance of exception.
+ std::string decoded( str );
+ int validity= validate( decoded );
+
+ // Unpack the supplied location data; we'll take as much as we are given, up to the
+ // maximum possible 12 symbols supported (9 symbols yielding ~3m resolution).
+ uint32_t lat_tot = 0;
+ uint32_t lon_tot = 0;
+
+ uint32_t lat_mult= 1;
+ uint32_t lon_mult= 1;
+
+ auto di = decoded.begin();
+ for ( auto &b : bits ) {
+ if ( di == decoded.end() )
+ break;
+ unsigned char c = *di++;
+
+ unsigned char lat_bits= b.first;
+ unsigned char lon_bits= b.second;
+
+ uint32_t lat_val = c >> lon_bits;
+ uint32_t lon_val = c & (( 1 << lon_bits ) - 1 );
+
+ lat_mult <<= lat_bits;
+ lat_tot <<= lat_bits;
+ lat_tot += lat_val;
+
+ lon_mult <<= lon_bits;
+ lon_tot <<= lon_bits;
+ lon_tot += lon_val;
+ }
+
+ // Convert the sum of lat/lon parts back into degrees, and round the (truncated) value
+ // to the middle of the error rectangle. This allows us to minimize error even if we
+ // didn't have access to all of the origin symbols to decode. The absolute error bar as
+ // a proportional factor [0,1) for lat/lon is at most the scale of the last parts
+ // multiplier used. We'll use this later to compute the error in meters; for example,
+ // if the last value we added worked out to be worth units of 25m of the circumference,
+ // then we must now be within [0,25m) of the original point.
+ double lat_err = 1.0 / lat_mult;
+ double lon_err = 1.0 / lon_mult;
+ latitude = 180 * ( double( lat_tot ) / lat_mult + lat_err / 2 ) - 90;
+ longitude = 360 * ( double( lon_tot ) / lon_mult + lon_err / 2 ) - 180;
+
+ // Remember the decoded location precision for future encoding (overrides the default).
+ // Compute the certainty probability (0.0,1.0] given the number of parity symbols in
+ // excess: Given a base-32 symbol: 1 - 1 / ( 32 ^ P ) where P is the number of
+ // unconsumed parity.
+ precision = decoded.size();
+ confidence = validity;
+ certainty = 0.0;
+ if ( PARITY * confidence / 100 )
+ certainty = 1.0 - 1.0 / std::pow( double( 32.0 ),
+ double( PARITY * confidence / 100 ));
+
+ // Compute the resolution error (in m.) of the decoded lat/lon and compute the minimum
+ // accuracy -- the radius of the circle around the computed latitude/longitude, inside
+ // which the original latitude/longitude must have been.
+ //
+ // original latitude error bar
+ // \ /
+ // o -
+ // | longitude error bar
+ // | /
+ // |--x--|
+ // /|
+ // / |
+ // computed -
+ //
+ // The maximum distance is the length of the diagonal of the error rectangle defined by
+ // 1/2 the latitude/longitude error bars.
+ //
+ double lon_circ= 1 * M_PI * 6371000;
+ double lat_circ= 2 * M_PI * 6371000 * std::cos( latitude * M_PI / 180 );
+ latitude_error = lat_err * lon_circ;
+ longitude_error = lon_err * lat_circ;
+
+ accuracy = sqrt( latitude_error / 2 * latitude_error / 2
+ + longitude_error / 2 * longitude_error / 2 );
+ return confidence;
+ }
+ }; // class ezcod
+
+
+ //
+ // ezcod::rscodec -- Reed-Solomon parity codec
+ // ezcod::bits -- distribution of lat/lon precision in each code symbol
+ //
+ // Quickly establishes an extra bit of precision for Longitude, and then evenly distributes
+ // future precision between lat/lon, always maintaining extra precision for Longitude.
+ //
+ template < unsigned P, unsigned L >
+ const ezpwd::RS<31,31-P> ezcod<P,L>::rscodec;
+
+ // Number of lat/lon bits represented for each location symbol
+ template < unsigned P, unsigned L >
+ const typename ezcod<P,L>::bits_t
+ ezcod<P,L>::bits = {
+ {
+ // bits per symbol lat lon
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ ezcod<P,L>::bits_t::value_type( 3, 2 ),
+ // -- --
+ // 7 8
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ ezcod<P,L>::bits_t::value_type( 3, 2 ),
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ // -- --
+ // 14 16
+ ezcod<P,L>::bits_t::value_type( 3, 2 ),
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ ezcod<P,L>::bits_t::value_type( 3, 2 ),
+ // -- --
+ // 22 23
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ ezcod<P,L>::bits_t::value_type( 3, 2 ),
+ ezcod<P,L>::bits_t::value_type( 2, 3 ),
+ // -- --
+ // 29 31
+ }
+ };
+
+ // Total number of parts that lat/lon is subdivided into, for that number of location symbols.
+ template < unsigned P, unsigned L >
+ const typename ezcod<P,L>::parts_t
+ ezcod<P,L>::parts = {
+ {
+ // parts per symbol lat parts lon parts lat lon bits
+ ezcod<P,L>::parts_t::value_type( 1UL << 2, 1UL << 3 ), // 2, 3
+ ezcod<P,L>::parts_t::value_type( 1UL << 4, 1UL << 6 ), // 2, 3
+ ezcod<P,L>::parts_t::value_type( 1UL << 7, 1UL << 8 ), // 3, 2
+ // -- --
+ // 7 8
+ ezcod<P,L>::parts_t::value_type( 1UL << 9, 1UL << 11 ), // 2, 3
+ ezcod<P,L>::parts_t::value_type( 1UL << 12, 1UL << 13 ), // 3, 2
+ ezcod<P,L>::parts_t::value_type( 1UL << 14, 1UL << 16 ), // 2, 3
+ // -- --
+ // 14 16
+ ezcod<P,L>::parts_t::value_type( 1UL << 17, 1UL << 18 ), // 3, 2
+ ezcod<P,L>::parts_t::value_type( 1UL << 19, 1UL << 21 ), // 2, 3
+ ezcod<P,L>::parts_t::value_type( 1UL << 22, 1UL << 23 ), // 3, 2
+ // -- --
+ // 22 23
+ ezcod<P,L>::parts_t::value_type( 1UL << 24, 1UL << 26 ), // 2, 3
+ ezcod<P,L>::parts_t::value_type( 1UL << 27, 1UL << 28 ), // 3, 2
+ ezcod<P,L>::parts_t::value_type( 1UL << 29, 1UL << 31 ), // 2, 3
+ // -- --
+ // 29 31
+ }
+ };
+} // namespace ezpwd
+
+#endif // _EZPWD_EZCOD
diff --git a/op25/gr-op25_repeater/lib/ezpwd/output b/op25/gr-op25_repeater/lib/ezpwd/output
new file mode 100644
index 0000000..230be80
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/output
@@ -0,0 +1,344 @@
+#ifndef _EZPWD_OUTPUT
+#define _EZPWD_OUTPUT
+
+#include <cstdio>
+#include <streambuf>
+#include <iostream>
+#include <cctype>
+#include <iomanip>
+#include <sstream>
+#include <set>
+#include <map>
+#include <vector>
+
+//
+// ezpwd::hexchr -- escape/hexify char c, output using func/meth f, in width w >= 2
+// ezpwd::hexify -- hexify something that can be converted to an unsigned char
+// ezpwd::hexout -- hexify each element in the range (beg,end], limited by stream's width
+//
+// std::ostream << ezpwd::hexify( c ) // output any char escaped/hex
+// std::ostream << ezpwd::hexout( beg, end ) // output any char iterator to ostream
+// std::ostream << std::vector<unsigend char>
+// std::ostream << std::array<unsigend char, N>
+// ezpwd::hexchr( c, [](unsigned char c){...;} )// output escaped/hex char via functor
+// ezpwd::hexout( beg, end, FILE* ) // output any char iterator to FILE*
+//
+// Output unprintable unsigned char data in hex, escape printable/whitespace data.
+//
+namespace ezpwd {
+
+ struct hexify {
+ unsigned char c;
+ std::streamsize w;
+ explicit hexify(
+ unsigned char _c,
+ std::streamsize _w = 2 )
+ : c( _c )
+ , w( _w )
+ { ; }
+ explicit hexify(
+ char _c,
+ std::streamsize _w = 2 )
+ : c( (unsigned char)_c )
+ , w( _w )
+ { ; }
+ };
+ struct hexstr {
+ const std::string &s;
+ explicit hexstr(
+ const std::string &_s )
+ : s( _s )
+ { ; }
+ };
+
+ template <typename F> // a functor taking a char
+ void
+ hexchr( unsigned char c, F f = []( unsigned char c ) { std::cout.put( c );}, size_t w = 2 )
+ {
+ for ( ; w > 2; --w )
+ f( ' ' );
+ if ( std::isprint( c ) || std::isspace( c )
+ || c == '\0' || c == '\a' || c == '\b' || c == 0x1B ) { // '\e' is not standard
+ switch ( c ) {
+ case 0x00: f( '\\' ); f( '0' ); break; // NUL
+ case 0x07: f( '\\' ); f( 'a' ); break; // BEL
+ case 0x08: f( '\\' ); f( 'b' ); break; // BS
+ case 0x09: f( '\\' ); f( 't' ); break; // HT
+ case 0x0A: f( '\\' ); f( 'n' ); break; // LF
+ case 0x0B: f( '\\' ); f( 'v' ); break; // VT
+ case 0x0C: f( '\\' ); f( 'f' ); break; // FF
+ case 0x0D: f( '\\' ); f( 'r' ); break; // CR
+ case 0x1B: f( '\\' ); f( 'e' ); break; // ESC
+ case '\"': f( '\\' ); f( '"' ); break; // "
+ case '\'': f( '\\' ); f( '\''); break; // '
+ case '\\': f( '\\' ); f( '\\'); break; // '\'
+ default: f( ' ' ); f( c ); // space, any other printable character
+ }
+ } else {
+ f( "0123456789ABCDEF"[( c >> 4 ) & 0x0f ] );
+ f( "0123456789ABCDEF"[( c >> 0 ) & 0x0f ] );
+ }
+ }
+
+
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::hexify&rhs )
+ {
+ ezpwd::hexchr( rhs.c, [ &lhs ]( unsigned char c ) { lhs.put( c ); }, rhs.w );
+ return lhs;
+ }
+
+ template < typename iter_t >
+ inline
+ std::ostream &hexout(
+ std::ostream &lhs,
+ const iter_t &beg,
+ const iter_t &end )
+ {
+ std::streamsize wid = lhs.width( 0 );
+ int col = 0;
+ for ( auto i = beg; i != end; ++i ) {
+ if ( wid && col == wid ) {
+ lhs << std::endl;
+ col = 0;
+ }
+ lhs << hexify( *i );
+ ++col;
+ }
+ return lhs;
+ }
+
+ template < typename iter_t >
+ inline
+ std::FILE *hexout(
+ const iter_t &beg,
+ const iter_t &end,
+ std::FILE *lhs )
+ {
+ for ( auto i = beg; i != end; ++i ) {
+ ezpwd::hexchr( *i, [ lhs ]( unsigned char c ) { std::fputc( c, lhs ); } );
+ }
+ return lhs;
+ }
+
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::hexstr&rhs )
+ {
+ return ezpwd::hexout( lhs, rhs.s.begin(), rhs.s.end() );
+ }
+} // namespace ezpwd
+
+namespace std {
+ template < size_t S >
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::array<unsigned char,S>
+ &rhs )
+ {
+ return ezpwd::hexout( lhs, rhs.begin(), rhs.end() );
+ }
+
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::vector<unsigned char>
+ &rhs )
+ {
+ return ezpwd::hexout( lhs, rhs.begin(), rhs.end() );
+ }
+
+ //
+ // <ostream&> << pair<T,U>
+ // <ostream&> << set<T> -- sorted by T
+ // <ostream&> << map<T,U> -- sorted by T (key)
+ // <ostream&> << vector<T>
+ //
+ // Handle output of various container types.
+ //
+ // Output pairs and sets of pairs, respecting specified widths (as appropriate). For example
+ // a set of pairs of integeters 's', if output as "... << std::setw( 13 ) << s;", would yield:
+ //
+ // ( 1, 2) ( 3, 4) ...
+ //
+
+ template <class T, class U>
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::pair<T,U> &rhs )
+ {
+ std::streamsize w = std::max( std::streamsize( 0 ),
+ std::streamsize( lhs.width() - 3 ));
+ lhs << std::setw( 0 )
+ << '(' << std::setw( w / 2 ) << rhs.first
+ << ',' << std::setw( w - w / 2 ) << rhs.second
+ << ')';
+ return lhs;
+ }
+
+ template <class T>
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::set<T> &rhs )
+ {
+ std::streamsize w = lhs.width(); // If width is set, use if for each item
+ for ( typename std::set<T>::const_iterator
+ si = rhs.begin()
+ ; si != rhs.end()
+ ; ++si ) {
+ if ( si != rhs.begin())
+ lhs << ' ';
+ lhs << std::setw( w ) << *si;
+ }
+ lhs << std::setw( 0 ); // If container empty, must clear
+ return lhs;
+ }
+
+template <class T, class U>
+std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::map<T,U>&rhs )
+{
+ std::streamsize w = lhs.width(); // If width is set, use if for each item
+ std::vector<T> key;
+ for ( typename std::map<T,U>::const_iterator
+ mi = rhs.begin()
+ ; mi != rhs.end()
+ ; ++mi )
+ key.push_back( mi->first );
+ std::sort( key.begin(), key.end() );
+ for ( typename std::vector<T>::const_iterator
+ ki = key.begin()
+ ; ki != key.end()
+ ; ++ki ) {
+ if ( ki != key.begin())
+ lhs << ' ';
+ lhs << std::setw( w ) << *rhs.find( *ki );
+ }
+ lhs << std::setw( 0 ); // If container empty, must clear
+ return lhs;
+}
+
+template <class T>
+std::ostream &operator<<(
+ std::ostream &lhs,
+ const std::vector<T> &rhs )
+{
+ for( size_t i = 0; i < rhs.size(); ++i ) {
+ if ( i )
+ lhs << ", ";
+ lhs << rhs[i];
+ }
+
+ return lhs;
+}
+} // namespace std
+
+//
+// ezpwd::buf_t -- describe a C string buffer, to allow C++ output operations
+// ezpwd::streambuf_to_buf_t -- output charcters, always NUL terminated
+//
+// <buf_t> << ... -- Copy the <string> into the C <char*,size_t> buffer, always NUL terminating
+//
+// Copies <string> contents into buffer, and always NUL-terminates. Returns advanced buf_t (NOT
+// including the terminating NUL, suitable for repeating ... << <string> operations.
+//
+// std::ostream( &<streambuf_to_buf_t> ) << ...
+//
+// Use standard ostream operations to send output to a C buffer, always NUL
+// terminating, and never exceeding capacity.
+//
+namespace ezpwd {
+
+ typedef std::pair<char *,size_t>
+ buf_t;
+
+ class streambuf_to_buffer
+ : public std::streambuf {
+ private:
+ char *_buf;
+ size_t _siz;
+ public:
+ //
+ // streambuf_to_buf_t -- remember buf_t details
+ // ~streambuf_to_buf_t -- no virtual destructor required; nothing to clean up
+ //
+ streambuf_to_buffer(
+ char *buf,
+ size_t siz )
+ : _buf( buf )
+ , _siz( siz )
+ {
+ if ( _siz > 0 )
+ *_buf = 0;
+ }
+ explicit streambuf_to_buffer(
+ const buf_t &buf )
+ : streambuf_to_buffer( buf.first, buf.second )
+ {
+ ;
+ }
+
+ //
+ // overflow -- Append c, always NUL terminating
+ //
+ virtual int overflow(
+ int c )
+ {
+ if ( _siz <= 1 )
+ return EOF; // No room for c and NUL; EOF
+ if ( EOF == c )
+ return 0; // EOF provided; do nothing
+ --_siz;
+ *_buf++ = char( c );
+ *_buf = 0;
+ return c;
+ }
+ }; // class streambuf_to_buffer
+
+} // namespace ezpwd
+
+namespace std {
+
+ inline
+ ezpwd::buf_t operator<<(
+ const ezpwd::buf_t &buf,
+ const std::string &str )
+ {
+ if ( buf.first && str.size() + 1 <= buf.second ) {
+ std::copy( str.begin(), str.end(), buf.first );
+ buf.first[str.size()] = 0;
+ return ezpwd::buf_t( buf.first + str.size(), buf.second - str.size() );
+ } else if ( buf.first && buf.second ) {
+ std::copy( str.begin(), str.begin() + buf.second - 1, buf.first );
+ buf.first[buf.second-1] = 0;
+ return ezpwd::buf_t( buf.first + buf.second - 1, 1 );
+ }
+ return buf; // NULL pointer or 0 size.
+ }
+
+
+ //
+ // <std::string> << ...
+ //
+ // Useful (but inefficient) standard output formatting directly to a std::string. Use only for
+ // testing code, for efficiency reasons...
+ //
+ template < typename T >
+ inline
+ std::string operator<<(
+ const std::string &lhs,
+ const T &rhs )
+ {
+ std::ostringstream oss;
+ oss << rhs;
+ return std::string( lhs ).append( oss.str() );
+ }
+
+} // namespace std
+
+#endif // _EZPWD_OUTPUT
diff --git a/op25/gr-op25_repeater/lib/ezpwd/rs b/op25/gr-op25_repeater/lib/ezpwd/rs
new file mode 100644
index 0000000..3479a49
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/rs
@@ -0,0 +1,168 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2014, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. c++/ezpwd/rs_base
+ * is redistributed under the terms of the LGPL, regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_RS
+#define _EZPWD_RS
+
+#include "rs_base"
+
+//
+// ezpwd::RS<SYMBOLS,PAYLOAD> -- Implements an RS(SYMBOLS,PAYLOAD) codec
+// ezpwd::RS_CCSDS<...> -- CCSDS standard 8-bit R-S codec
+//
+// Support for Reed-Solomon codecs for symbols of 2 to 16 bits is supported. The R-S "codeword"
+// for an N-bit symbol is defined to be 2^N-1 symbols in size. For example, for 5-bit symbols,
+// 2^5-1 == 31, so the notation for defining an Reed-Solomon codec for 5-bit symbols is always:
+// RS(31,PAYLOAD), where PAYLOAD is always some value less than 31. The difference is the number of
+// "parity" symbols.
+//
+// For example, to define an RS codeword of 31 symbols w/ 4 symbols of parity and up to 27
+// symbols of data, you would say: RS(31,27). Of course, you can supply smaller amounts of data;
+// the balance is assumed to be NUL (zero) symbols.
+//
+namespace ezpwd {
+
+ //
+ // __RS( ... ) -- Define a reed-solomon codec
+ //
+ // @SYMBOLS: Total number of symbols; must be a power of 2 minus 1, eg 2^8-1 == 255
+ // @PAYLOAD: The maximum number of non-parity symbols, eg 253 ==> 2 parity symbols
+ // @POLY: A primitive polynomial appropriate to the SYMBOLS size
+ // @FCR: The first consecutive root of the Reed-Solomon generator polynomial
+ // @PRIM: The primitive root of the generator polynomial
+ //
+# define __RS_TYP( TYPE, SYMBOLS, PAYLOAD, POLY, FCR, PRIM ) \
+ ezpwd::reed_solomon< \
+ TYPE, \
+ ezpwd::log_< (SYMBOLS) + 1 >::value, \
+ (SYMBOLS) - (PAYLOAD), FCR, PRIM, \
+ ezpwd::gfpoly< \
+ ezpwd::log_< (SYMBOLS) + 1 >::value, \
+ POLY >>
+
+# define __RS( NAME, TYPE, SYMBOLS, PAYLOAD, POLY, FCR, PRIM ) \
+ __RS_TYP( TYPE, SYMBOLS, PAYLOAD, POLY, FCR, PRIM ) { \
+ NAME() \
+ : __RS_TYP( TYPE, SYMBOLS, PAYLOAD, POLY, FCR, PRIM )() \
+ {;} \
+ }
+
+ //
+ // RS<SYMBOLS, PAYLOAD> -- Standard partial specializations for Reed-Solomon codec type access
+ //
+ // Normally, Reed-Solomon codecs are described with terms like RS(255,252). Obtain various
+ // standard Reed-Solomon codecs using macros of a similar form, eg. RS<255, 252>. Standard PLY,
+ // FCR and PRM values are provided for various SYMBOL sizes, along with appropriate basic types
+ // capable of holding all internal Reed-Solomon tabular data.
+ //
+ // In order to provide "default initialization" of const RS<...> types, a user-provided
+ // default constructor must be provided.
+ //
+ template < size_t SYMBOLS, size_t PAYLOAD > struct RS;
+ template < size_t PAYLOAD > struct RS< 3, PAYLOAD> : public __RS( RS, uint8_t, 3, PAYLOAD, 0x7, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 7, PAYLOAD> : public __RS( RS, uint8_t, 7, PAYLOAD, 0xb, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 15, PAYLOAD> : public __RS( RS, uint8_t, 15, PAYLOAD, 0x13, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 31, PAYLOAD> : public __RS( RS, uint8_t, 31, PAYLOAD, 0x25, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 63, PAYLOAD> : public __RS( RS, uint8_t, 63, PAYLOAD, 0x43, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 127, PAYLOAD> : public __RS( RS, uint8_t, 127, PAYLOAD, 0x89, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 255, PAYLOAD> : public __RS( RS, uint8_t, 255, PAYLOAD, 0x11d, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 511, PAYLOAD> : public __RS( RS, uint16_t, 511, PAYLOAD, 0x211, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 1023, PAYLOAD> : public __RS( RS, uint16_t, 1023, PAYLOAD, 0x409, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 2047, PAYLOAD> : public __RS( RS, uint16_t, 2047, PAYLOAD, 0x805, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 4095, PAYLOAD> : public __RS( RS, uint16_t, 4095, PAYLOAD, 0x1053, 1, 1 );
+ template < size_t PAYLOAD > struct RS< 8191, PAYLOAD> : public __RS( RS, uint16_t, 8191, PAYLOAD, 0x201b, 1, 1 );
+ template < size_t PAYLOAD > struct RS<16383, PAYLOAD> : public __RS( RS, uint16_t, 16383, PAYLOAD, 0x4443, 1, 1 );
+ template < size_t PAYLOAD > struct RS<32767, PAYLOAD> : public __RS( RS, uint16_t, 32767, PAYLOAD, 0x8003, 1, 1 );
+ template < size_t PAYLOAD > struct RS<65535, PAYLOAD> : public __RS( RS, uint16_t, 65535, PAYLOAD, 0x1100b, 1, 1 );
+
+ template < size_t SYMBOLS, size_t PAYLOAD > struct RS_CCSDS;
+ template < size_t PAYLOAD > struct RS_CCSDS<255, PAYLOAD> : public __RS( RS_CCSDS, uint8_t, 255, PAYLOAD, 0x187, 112, 11 );
+
+
+ //
+ // strength<PARITY> -- compute strength (given N parity symbols) of R-S correction
+ //
+ // Returns a confidence strength rating, which is the ratio:
+ //
+ // 100 - ( errors * 2 + erasures ) * 100 / parity
+ //
+ // which is proportional to the number of parity symbols unused by the reported number of
+ // corrected symbols. If 0, then all parity resources were consumed to recover the R-S
+ // codeword, and we can have no confidence in the result. If -'ve, indicates more parity
+ // resources were consumed than available, indicating that the result is likely incorrect.
+ //
+ // Accounts for the fact that a signalled erasure may not be reported in the corrected
+ // position vector, if the symbol happens to match the computed value. Note that even if the
+ // error or erasure occurs within the "parity" portion of the codeword, this doesn't reduce the
+ // effective strength -- all symbols in the R-S complete codeword are equally effective in
+ // recovering any other symbol in error/erasure.
+ //
+ template < size_t PARITY >
+ int strength(
+ int corrected,
+ const std::vector<int>&erasures, // original erasures positions
+ const std::vector<int>&positions ) // all reported correction positions
+ {
+ // -'ve indicates R-S failure; all parity consumed, but insufficient to correct the R-S
+ // codeword. Missing an unknown number of additional required parity symbols, so just
+ // return -1 as the strength.
+ if ( corrected < 0 ) {
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout
+ << corrected << " corrections (R-S decode failure) == -1 confidence"
+ << std::endl;
+#endif
+ return -1;
+ }
+ if ( corrected != int( positions.size() ))
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "inconsistent R-S decode results", -1 );
+
+ // Any erasures that don't turn out to contain errors are not returned as fixed positions.
+ // However, they have consumed parity resources. Search for each erasure location in
+ // positions, and if not reflected, add to the corrected/missed counters.
+ int missed = 0;
+ for ( auto e : erasures ) {
+ if ( std::find( positions.begin(), positions.end(), e ) == positions.end() ) {
+ ++corrected;
+ ++missed;
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout
+ << corrected << " corrections (R-S erasure missed): " << e
+ << std::endl;
+#endif
+ }
+ }
+ int errors = corrected - erasures.size();
+ int consumed= errors * 2 + erasures.size();
+ int confidence= 100 - consumed * 100 / PARITY;
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout
+ << corrected << " corrections (R-S decode success)"
+ << " at: " << positions
+ << ", " << erasures.size() + missed
+ << " erasures (" << missed
+ << " unreported) at: " << erasures
+ << ") ==> " << errors
+ << " errors, and " << consumed << " / " << PARITY
+ << " parity used == " << confidence
+ << "% confidence"
+ << std::endl;
+#endif
+ return confidence;
+ }
+
+} // namespace ezpwd
+
+#endif // _EZPWD_RS
diff --git a/op25/gr-op25_repeater/lib/ezpwd/rs_base b/op25/gr-op25_repeater/lib/ezpwd/rs_base
new file mode 100644
index 0000000..5dad4e3
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/rs_base
@@ -0,0 +1,1344 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2014, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. The
+ * c++/ezpwd/rs_base file is redistributed under the terms of the LGPL, regardless of the overall
+ * licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ *
+ * The core Reed-Solomon codec implementation in c++/ezpwd/rs_base is by Phil Karn, converted to C++
+ * by Perry Kundert (perry@hardconsulting.com), and may be used under the terms of the LGPL. Here
+ * is the terms from Phil's README file (see phil-karn/fec-3.0.1/README):
+ *
+ * COPYRIGHT
+ *
+ * This package is copyright 2006 by Phil Karn, KA9Q. It may be used
+ * under the terms of the GNU Lesser General Public License (LGPL). See
+ * the file "lesser.txt" in this package for license details.
+ *
+ * The c++/ezpwd/rs_base file is, therefore, redistributed under the terms of the LGPL, while the
+ * rest of Ezpwd Reed-Solomon is distributed under either the GPL or Commercial licenses.
+ * Therefore, even if you have obtained Ezpwd Reed-Solomon under a Commercial license, you must make
+ * available the source code of the c++/ezpwd/rs_base file with your product. One simple way to
+ * accomplish this is to include the following URL in your code or documentation:
+ *
+ * https://github.com/pjkundert/ezpwd-reed-solomon/blob/master/c++/ezpwd/rs_base
+ *
+ *
+ * The Linux 3.15.1 version of lib/reed_solomon was also consulted as a cross-reference, which (in
+ * turn) is basically verbatim copied from Phil Karn's LGPL implementation, to ensure that no new
+ * defects had been found and fixed; there were no meaningful changes made to Phil's implementation.
+ * I've personally been using Phil's implementation for years in a heavy industrial use, and it is
+ * rock-solid.
+ *
+ * However, both Phil's and the Linux kernel's (copy of Phil's) implementation will return a
+ * "corrected" decoding with impossible error positions, in some cases where the error load
+ * completely overwhelms the R-S encoding. These cases, when detected, are rejected in this
+ * implementation. This could be considered a defect in Phil's (and hence the Linux kernel's)
+ * implementations, which results in them accepting clearly incorrect R-S decoded values as valid
+ * (corrected) R-S codewords. We chose the report failure on these attempts.
+ *
+ */
+#ifndef _EZPWD_RS_BASE
+#define _EZPWD_RS_BASE
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstring>
+#include <iostream>
+#include <type_traits>
+#include <vector>
+
+//
+// Preprocessor defines available:
+//
+// EZPWD_NO_EXCEPTS -- define to use no exceptions; return -1, or abort on catastrophic failures
+// EZPWD_NO_MOD_TAB -- define to force no "modnn" Galois modulo table acceleration
+// EZPWD_ARRAY_SAFE -- define to force usage of bounds-checked arrays for most tabular data
+// EZPWD_ARRAY_TEST -- define to force erroneous sizing of some arrays for non-production testing
+//
+
+#if defined( DEBUG ) && DEBUG >= 2
+# include "output" // ezpwd::hex... std::ostream shims for outputting containers of uint8_t data
+#endif
+
+#if defined( EZPWD_NO_EXCEPTS )
+# include <cstdio> // No exceptions; don't use C++ ostream
+# define EZPWD_RAISE_OR_ABORT( typ, str ) do { \
+ std::fputs(( str ), stderr ); std::fputc( '\n', stderr ); \
+ abort(); \
+ } while ( false )
+# define EZPWD_RAISE_OR_RETURN( typ, str, ret ) return ( ret )
+#else
+# define EZPWD_RAISE_OR_ABORT( typ, str ) throw ( typ )( str )
+# define EZPWD_RAISE_OR_RETURN( typ, str, ret ) throw ( typ )( str )
+#endif
+
+namespace ezpwd {
+
+ // ezpwd::log_<N,B> -- compute the log base B of N at compile-time
+ template <size_t N, size_t B=2> struct log_{ enum { value = 1 + log_<N/B, B>::value }; };
+ template <size_t B> struct log_<1, B>{ enum { value = 0 }; };
+ template <size_t B> struct log_<0, B>{ enum { value = 0 }; };
+
+ //
+ // reed_solomon_base - Reed-Solomon codec generic base class
+ //
+ class reed_solomon_base {
+ public:
+ virtual size_t datum() const = 0; // a data element's bits
+ virtual size_t symbol() const = 0; // a symbol's bits
+ virtual int size() const = 0; // R-S block size (maximum total symbols)
+ virtual int nroots() const = 0; // R-S roots (parity symbols)
+ virtual int load() const = 0; // R-S net payload (data symbols)
+
+ virtual ~reed_solomon_base()
+ {
+ ;
+ }
+ reed_solomon_base()
+ {
+ ;
+ }
+
+ virtual std::ostream &output(
+ std::ostream &lhs )
+ const
+ {
+ return lhs << "RS(" << this->size() << "," << this->load() << ")";
+ }
+
+ //
+ // {en,de}code -- Compute/Correct errors/erasures in a Reed-Solomon encoded container
+ //
+ /// The encoded parity symbols may be included in 'data' (len includes nroots() parity
+ /// symbols), or may (optionally) supplied separately in (at least nroots()-sized)
+ /// 'parity'.
+ ///
+ /// For decode, optionally specify some known erasure positions (up to nroots()). If
+ /// non-empty 'erasures' is provided, it contains the positions of each erasure. If a
+ /// non-zero pointer to a 'position' vector is provided, its capacity will be increased to
+ /// be capable of storing up to 'nroots()' ints; the actual deduced error locations will be
+ /// returned.
+ ///
+ /// RETURN VALUE
+ ///
+ /// Return -1 on error. The encode returns the number of parity symbols produced;
+ /// decode returns the number of symbols corrected. Both errors and erasures are included,
+ /// so long as they are actually different than the deduced value. In other words, if a
+ /// symbol is marked as an erasure but it actually turns out to be correct, it's index will
+ /// NOT be included in the returned count, nor the modified erasure vector!
+ ///
+
+ //
+ // encode(<string>) -- extend string to contain parity, or place in supplied parity string
+ // encode(<vector>) -- extend vector to contain parity, or place in supplied parity vector
+ // encode(<array>) -- ignore 'pad' elements of array, puts nroots() parity symbols at end
+ // encode(pair<iter,iter>) -- encode all except the last nroots() of the data, put parity at end
+ // encode(pair<iter,iter>, pair<iter,iter>) -- encode data between first <iter> pair, put parity in second pair
+ //
+ int encode(
+ std::string &data )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ data.resize( data.size() + nroots() );
+ return encode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ));
+ }
+
+ int encode(
+ const std::string &data,
+ std::string &parity )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<const uT *, const uT *>
+ cuTpair;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ parity.resize( nroots() );
+ return encode( cuTpair( (const uT *)&data.front(), (const uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ));
+ }
+
+ template < typename T >
+ int encode(
+ std::vector<T> &data )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ data.resize( data.size() + nroots() );
+ return encode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ));
+ }
+ template < typename T >
+ int encode(
+ const std::vector<T>&data,
+ std::vector<T> &parity )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<const uT *, const uT *>
+ cuTpair;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ parity.resize( nroots() );
+ return encode( cuTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ));
+ }
+
+ template < typename T, size_t N >
+ int encode(
+ std::array<T,N> &data,
+ int pad = 0 ) // ignore 'pad' symbols at start of array
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return encode( uTpair( (uT *)&data.front() + pad, (uT *)&data.front() + data.size() ));
+ }
+
+ virtual int encode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data )
+ const
+ = 0;
+ virtual int encode(
+ const std::pair<const uint8_t *, const uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity )
+ const
+ = 0;
+ virtual int encode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data )
+ const
+ = 0;
+ virtual int encode(
+ const std::pair<const uint16_t *, const uint16_t *>
+ &data,
+ const std::pair<uint16_t *, uint16_t *>
+ &parity )
+ const
+ = 0;
+ virtual int encode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data )
+ const
+ = 0;
+ virtual int encode(
+ const std::pair<const uint32_t *, const uint32_t *>
+ &data,
+ const std::pair<uint32_t *, uint32_t *>
+ &parity )
+ const
+ = 0;
+
+ int decode(
+ std::string &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ erasure, position );
+ }
+
+ int decode(
+ std::string &data,
+ std::string &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef uint8_t uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ),
+ erasure, position );
+ }
+
+ template < typename T >
+ int decode(
+ std::vector<T> &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ erasure, position );
+ }
+
+ template < typename T >
+ int decode(
+ std::vector<T> &data,
+ std::vector<T> &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front(), (uT *)&data.front() + data.size() ),
+ uTpair( (uT *)&parity.front(), (uT *)&parity.front() + parity.size() ),
+ erasure, position );
+ }
+
+ template < typename T, size_t N >
+ int decode(
+ std::array<T,N> &data,
+ int pad = 0, // ignore 'pad' symbols at start of array
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ typedef typename std::make_unsigned<T>::type
+ uT;
+ typedef std::pair<uT *, uT *>
+ uTpair;
+ return decode( uTpair( (uT *)&data.front() + pad, (uT *)&data.front() + data.size() ),
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ virtual int decode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ virtual int decode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data,
+ const std::pair<uint16_t *, uint16_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ virtual int decode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ virtual int decode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data,
+ const std::pair<uint32_t *, uint32_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ = 0;
+ }; // class reed_solomon_base
+
+ //
+ // std::ostream << ezpwd::reed_solomon<...>
+ //
+ // Output a R-S codec description in standard form eg. RS(255,253)
+ //
+ inline
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::reed_solomon_base
+ &rhs )
+ {
+ return rhs.output( lhs );
+ }
+
+ //
+ // gfpoly - default field polynomial generator functor.
+ //
+ template < int SYM, int PLY >
+ struct gfpoly {
+ int operator() ( int sr )
+ const
+ {
+ if ( sr == 0 )
+ sr = 1;
+ else {
+ sr <<= 1;
+ if ( sr & ( 1 << SYM ))
+ sr ^= PLY;
+ sr &= (( 1 << SYM ) - 1);
+ }
+ return sr;
+ }
+ };
+
+ //
+ // class reed_solomon_tabs -- R-S tables common to all RS(NN,*) with same SYM, PRM and PLY
+ //
+ template < typename TYP, int SYM, int PRM, class PLY >
+ class reed_solomon_tabs
+ : public reed_solomon_base {
+
+ public:
+ typedef TYP symbol_t;
+ static const size_t DATUM = 8 * sizeof TYP(); // bits / TYP
+ static const size_t SYMBOL = SYM; // bits / symbol
+ static const int MM = SYM;
+ static const int SIZE = ( 1 << SYM ) - 1; // maximum symbols in field
+ static const int NN = SIZE;
+ static const int A0 = SIZE;
+ static const int MODS // modulo table: 1/2 the symbol size squared, up to 4k
+#if defined( EZPWD_NO_MOD_TAB )
+ = 0;
+#else
+ = SYM > 8 ? ( 1 << 12 ) : ( 1 << SYM << SYM/2 );
+#endif
+
+ static int iprim; // initialized to -1, below
+
+ protected:
+ static std::array<TYP,
+#if not defined( EZPWD_ARRAY_TEST )
+ NN + 1>
+#else
+# warning "EZPWD_ARRAY_TEST: Erroneously declaring alpha_to size!"
+ NN >
+#endif
+ alpha_to;
+ static std::array<TYP,NN + 1>
+ index_of;
+ static std::array<TYP,MODS>
+ mod_of;
+ virtual ~reed_solomon_tabs()
+ {
+ ;
+ }
+ reed_solomon_tabs()
+ : reed_solomon_base()
+ {
+ // Do init if not already done. We check one value which is initialized to -1; this is
+ // safe, 'cause the value will not be set 'til the initializing thread has completely
+ // initialized the structure. Worst case scenario: multiple threads will initialize
+ // identically. No mutex necessary.
+ if ( iprim >= 0 )
+ return;
+
+#if defined( DEBUG ) && DEBUG >= 1
+ std::cout << "RS(" << SIZE << ",*): Initialize for " << NN << " symbols size, " << MODS << " modulo table." << std::endl;
+#endif
+ // Generate Galois field lookup tables
+ index_of[0] = A0; // log(zero) = -inf
+ alpha_to[A0] = 0; // alpha**-inf = 0
+ PLY poly;
+ int sr = poly( 0 );
+ for ( int i = 0; i < NN; i++ ) {
+ index_of[sr] = i;
+ alpha_to[i] = sr;
+ sr = poly( sr );
+ }
+ // If it's not primitive, raise exception or abort
+ if ( sr != alpha_to[0] ) {
+ EZPWD_RAISE_OR_ABORT( std::runtime_error, "reed-solomon: Galois field polynomial not primitive" );
+ }
+
+ // Generate modulo table for some commonly used (non-trivial) values
+ for ( int x = NN; x < NN + MODS; ++x )
+ mod_of[x-NN] = _modnn( x );
+ // Find prim-th root of 1, index form, used in decoding.
+ int iptmp = 1;
+ while ( iptmp % PRM != 0 )
+ iptmp += NN;
+ iprim = iptmp / PRM;
+ }
+
+ //
+ // modnn -- modulo replacement for galois field arithmetics, optionally w/ table acceleration
+ //
+ // @x: the value to reduce (will never be -'ve)
+ //
+ // where
+ // MM = number of bits per symbol
+ // NN = (2^MM) - 1
+ //
+ // Simple arithmetic modulo would return a wrong result for values >= 3 * NN
+ //
+ TYP _modnn(
+ int x )
+ const
+ {
+ while ( x >= NN ) {
+ x -= NN;
+ x = ( x >> MM ) + ( x & NN );
+ }
+ return x;
+ }
+ TYP modnn(
+ int x )
+ const
+ {
+ while ( x >= NN + MODS ) {
+ x -= NN;
+ x = ( x >> MM ) + ( x & NN );
+ }
+ if ( MODS && x >= NN )
+ x = mod_of[x-NN];
+ return x;
+ }
+ };
+
+ //
+ // class reed_solomon - Reed-Solomon codec
+ //
+ // @TYP: A symbol datum; {en,de}code operates on arrays of these
+ // @DATUM: Bits per datum (a TYP())
+ // @SYM{BOL}, MM: Bits per symbol
+ // @NN: Symbols per block (== (1<<MM)-1)
+ // @alpha_to: log lookup table
+ // @index_of: Antilog lookup table
+ // @genpoly: Generator polynomial
+ // @NROOTS: Number of generator roots = number of parity symbols
+ // @FCR: First consecutive root, index form
+ // @PRM: Primitive element, index form
+ // @iprim: prim-th root of 1, index form
+ // @PLY: The primitive generator polynominal functor
+ //
+ // All reed_solomon<T, ...> instances with the same template type parameters share a common
+ // (static) set of alpha_to, index_of and genpoly tables. The first instance to be constructed
+ // initializes the tables.
+ //
+ // Each specialized type of reed_solomon implements a specific encode/decode method
+ // appropriate to its datum 'TYP'. When accessed via a generic reed_solomon_base pointer, only
+ // access via "safe" (size specifying) containers or iterators is available.
+ //
+ template < typename TYP, int SYM, int RTS, int FCR, int PRM, class PLY >
+ class reed_solomon
+ : public reed_solomon_tabs<TYP, SYM, PRM, PLY> {
+
+ public:
+ typedef reed_solomon_tabs<TYP, SYM, PRM, PLY>
+ tabs_t;
+ using tabs_t::DATUM;
+ using tabs_t::SYMBOL;
+ using tabs_t::MM;
+ using tabs_t::SIZE;
+ using tabs_t::NN;
+ using tabs_t::A0;
+
+ using tabs_t::iprim;
+
+ using tabs_t::alpha_to;
+ using tabs_t::index_of;
+
+ using tabs_t::modnn;
+
+ static const int NROOTS = RTS;
+ static const int LOAD = SIZE - NROOTS; // maximum non-parity symbol payload
+
+ protected:
+ static std::array<TYP, NROOTS + 1>
+ genpoly;
+
+ public:
+ virtual size_t datum() const
+ {
+ return DATUM;
+ }
+
+ virtual size_t symbol() const
+ {
+ return SYMBOL;
+ }
+
+ virtual int size() const
+ {
+ return SIZE;
+ }
+
+ virtual int nroots() const
+ {
+ return NROOTS;
+ }
+
+ virtual int load() const
+ {
+ return LOAD;
+ }
+
+ using reed_solomon_base::encode;
+ virtual int encode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data )
+ const
+ {
+ return encode_mask( data.first, data.second - data.first - NROOTS, data.second - NROOTS );
+ }
+
+ virtual int encode(
+ const std::pair<const uint8_t *, const uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return encode_mask( data.first, data.second - data.first, parity.first );
+ }
+
+ virtual int encode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data )
+ const
+ {
+ return encode_mask( data.first, data.second - data.first - NROOTS, data.second - NROOTS );
+ }
+
+ virtual int encode(
+ const std::pair<const uint16_t *, const uint16_t *>
+ &data,
+ const std::pair<uint16_t *, uint16_t *>
+ &parity )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return encode_mask( data.first, data.second - data.first, parity.first );
+ }
+
+ virtual int encode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data )
+ const
+ {
+ return encode_mask( data.first, data.second - data.first - NROOTS, data.second - NROOTS );
+ }
+
+ virtual int encode(
+ const std::pair<const uint32_t *, const uint32_t *>
+ &data,
+ const std::pair<uint32_t *, uint32_t *>
+ &parity )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return encode_mask( data.first, data.second - data.first, parity.first );
+ }
+
+ template < typename INP >
+ int encode_mask(
+ const INP *data,
+ int len,
+ INP *parity ) // pointer to all NROOTS parity symbols
+
+ const
+ {
+ if ( len < 1 ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: must provide space for all parity and at least one non-parity symbol", -1 );
+ }
+
+ const TYP *dataptr;
+ TYP *pariptr;
+ const size_t INPUT = 8 * sizeof ( INP );
+
+ if ( DATUM != SYMBOL || DATUM != INPUT ) {
+ // Our DATUM (TYP) size (eg. uint8_t ==> 8, uint16_t ==> 16, uint32_t ==> 32)
+ // doesn't exactly match our R-S SYMBOL size (eg. 6), or our INP size; Must mask and
+ // copy. The INP data must fit at least the SYMBOL size!
+ if ( SYMBOL > INPUT ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: output data type too small to contain symbols", -1 );
+ }
+ std::array<TYP,SIZE> tmp;
+ TYP msk = static_cast<TYP>( ~0UL << SYMBOL );
+ for ( int i = 0; i < len; ++i )
+ tmp[LOAD - len + i] = data[i] & ~msk;
+ dataptr = &tmp[LOAD - len];
+ pariptr = &tmp[LOAD];
+
+ encode( dataptr, len, pariptr );
+
+ // we copied/masked data; copy the parity symbols back (may be different sizes)
+ for ( int i = 0; i < NROOTS; ++i )
+ parity[i] = pariptr[i];
+ } else {
+ // Our R-S SYMBOL size, DATUM size and INP type size exactly matches; use in-place.
+ dataptr = reinterpret_cast<const TYP *>( data );
+ pariptr = reinterpret_cast<TYP *>( parity );
+
+ encode( dataptr, len, pariptr );
+ }
+ return NROOTS;
+ }
+
+ using reed_solomon_base::decode;
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ return decode_mask( data.first, data.second - data.first, (uint8_t *)0,
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint8_t *, uint8_t *>
+ &data,
+ const std::pair<uint8_t *, uint8_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return decode_mask( data.first, data.second - data.first, parity.first,
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ return decode_mask( data.first, data.second - data.first, (uint16_t *)0,
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint16_t *, uint16_t *>
+ &data,
+ const std::pair<uint16_t *, uint16_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return decode_mask( data.first, data.second - data.first, parity.first,
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ return decode_mask( data.first, data.second - data.first, (uint32_t *)0,
+ erasure, position );
+ }
+
+ virtual int decode(
+ const std::pair<uint32_t *, uint32_t *>
+ &data,
+ const std::pair<uint32_t *, uint32_t *>
+ &parity,
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( parity.second - parity.first != NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity length incompatible with number of roots", -1 );
+ }
+ return decode_mask( data.first, data.second - data.first, parity.first,
+ erasure, position );
+ }
+
+ //
+ // decode_mask -- mask INP data into valid SYMBOL data
+ //
+ /// Incoming data may be in a variety of sizes, and may contain information beyond the
+ /// R-S symbol capacity. For example, we might use a 6-bit R-S symbol to correct the lower
+ /// 6 bits of an 8-bit data character. This would allow us to correct common substitution
+ /// errors (such as '2' for '3', 'R' for 'T', 'n' for 'm').
+ ///
+ template < typename INP >
+ int decode_mask(
+ INP *data,
+ int len,
+ INP *parity = 0, // either 0, or pointer to all parity symbols
+ const std::vector<int>
+ &erasure = std::vector<int>(),
+ std::vector<int> *position= 0 )
+ const
+ {
+ if ( len < ( parity ? 0 : NROOTS ) + 1 ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: must provide all parity and at least one non-parity symbol", -1 );
+ }
+ if ( ! parity ) {
+ len -= NROOTS;
+ parity = data + len;
+ }
+
+ TYP *dataptr;
+ TYP *pariptr;
+ const size_t INPUT = 8 * sizeof ( INP );
+
+ std::array<TYP,SIZE> tmp;
+ TYP msk = static_cast<TYP>( ~0UL << SYMBOL );
+ const bool cpy = DATUM != SYMBOL || DATUM != INPUT;
+ if ( cpy ) {
+ // Our DATUM (TYP) size (eg. uint8_t ==> 8, uint16_t ==> 16, uint32_t ==> 32)
+ // doesn't exactly match our R-S SYMBOL size (eg. 6), or our INP size; Must copy.
+ // The INP data must fit at least the SYMBOL size!
+ if ( SYMBOL > INPUT ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: input data type too small to contain symbols", -1 );
+ }
+ for ( int i = 0; i < len; ++i ) {
+ tmp[LOAD - len + i] = data[i] & ~msk;
+ }
+ dataptr = &tmp[LOAD - len];
+ for ( int i = 0; i < NROOTS; ++i ) {
+ if ( TYP( parity[i] ) & msk ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: parity data contains information beyond R-S symbol size", -1 );
+ }
+ tmp[LOAD + i] = parity[i];
+ }
+ pariptr = &tmp[LOAD];
+ } else {
+ // Our R-S SYMBOL size, DATUM size and INPUT type sizes exactly matches
+ dataptr = reinterpret_cast<TYP *>( data );
+ pariptr = reinterpret_cast<TYP *>( parity );
+ }
+
+ int corrects;
+ if ( ! erasure.size() && ! position ) {
+ // No erasures, and error position info not wanted.
+ corrects = decode( dataptr, len, pariptr );
+ } else {
+ // Either erasure location info specified, or resultant error position info wanted;
+ // Prepare pos (a temporary, if no position vector provided), and copy any provided
+ // erasure positions. After number of corrections is known, resize the position
+ // vector. Thus, we use any supplied erasure info, and optionally return any
+ // correction position info separately.
+ std::vector<int> _pos;
+ std::vector<int> &pos = position ? *position : _pos;
+ pos.resize( std::max( size_t( NROOTS ), erasure.size() ));
+ std::copy( erasure.begin(), erasure.end(), pos.begin() );
+ corrects = decode( dataptr, len, pariptr,
+ &pos.front(), erasure.size() );
+ if ( corrects > int( pos.size() )) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: FATAL: produced too many corrections; possible corruption!", -1 );
+ }
+ pos.resize( std::max( 0, corrects ));
+ }
+
+ if ( cpy && corrects > 0 ) {
+ for ( int i = 0; i < len; ++i ) {
+ data[i] &= msk;
+ data[i] |= tmp[LOAD - len + i];
+ }
+ for ( int i = 0; i < NROOTS; ++i ) {
+ parity[i] = tmp[LOAD + i];
+ }
+ }
+ return corrects;
+ }
+
+ virtual ~reed_solomon()
+ {
+ ;
+ }
+ reed_solomon()
+ : reed_solomon_tabs<TYP, SYM, PRM, PLY>()
+ {
+ // We check one element of the array; this is safe, 'cause the value will not be
+ // initialized 'til the initializing thread has completely initialized the array. Worst
+ // case scenario: multiple threads will initialize identically. No mutex necessary.
+ if ( genpoly[0] )
+ return;
+
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout << "RS(" << SIZE << "," << LOAD << "): Initialize for " << NROOTS << " roots." << std::endl;
+#endif
+ std::array<TYP, NROOTS + 1>
+ tmppoly; // uninitialized
+ // Form RS code generator polynomial from its roots. Only lower-index entries are
+ // consulted, when computing subsequent entries; only index 0 needs initialization.
+ tmppoly[0] = 1;
+ for ( int i = 0, root = FCR * PRM; i < NROOTS; i++, root += PRM ) {
+ tmppoly[i + 1] = 1;
+ // Multiply tmppoly[] by @**(root + x)
+ for ( int j = i; j > 0; j-- ) {
+ if ( tmppoly[j] != 0 )
+ tmppoly[j] = tmppoly[j - 1]
+ ^ alpha_to[modnn(index_of[tmppoly[j]] + root)];
+ else
+ tmppoly[j] = tmppoly[j - 1];
+ }
+ // tmppoly[0] can never be zero
+ tmppoly[0] = alpha_to[modnn(index_of[tmppoly[0]] + root)];
+ }
+ // convert NROOTS entries of tmppoly[] to genpoly[] in index form for quicker encoding,
+ // in reverse order so genpoly[0] is last element initialized.
+ for ( int i = NROOTS; i >= 0; --i )
+ genpoly[i] = index_of[tmppoly[i]];
+ }
+
+ int encode(
+ const TYP *data,
+ int len,
+ TYP *parity ) // at least nroots
+ const
+ {
+ // Check length parameter for validity
+ int pad = NN - NROOTS - len;
+ if ( pad < 0 || pad >= NN ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: data length incompatible with block size and error correction symbols", -1 );
+ }
+ for ( int i = 0; i < NROOTS; i++ )
+ parity[i] = 0;
+ for ( int i = 0; i < len; i++ ) {
+ TYP feedback= index_of[data[i] ^ parity[0]];
+ if ( feedback != A0 )
+ for ( int j = 1; j < NROOTS; j++ )
+ parity[j] ^= alpha_to[modnn(feedback + genpoly[NROOTS - j])];
+
+ std::rotate( parity, parity + 1, parity + NROOTS );
+ if ( feedback != A0 )
+ parity[NROOTS - 1] = alpha_to[modnn(feedback + genpoly[0])];
+ else
+ parity[NROOTS - 1] = 0;
+ }
+#if defined( DEBUG ) && DEBUG >= 2
+ std::cout << *this << " encode " << std::vector<TYP>( data, data + len )
+ << " --> " << std::vector<TYP>( parity, parity + NROOTS ) << std::endl;
+#endif
+ return NROOTS;
+ }
+
+ int decode(
+ TYP *data,
+ int len,
+ TYP *parity, // Requires: at least NROOTS
+ int *eras_pos= 0, // Capacity: at least NROOTS
+ int no_eras = 0, // Maximum: at most NROOTS
+ TYP *corr = 0 ) // Capacity: at least NROOTS
+ const
+ {
+ typedef std::array< TYP, NROOTS >
+ typ_nroots;
+ typedef std::array< TYP, NROOTS+1 >
+ typ_nroots_1;
+ typedef std::array< int, NROOTS >
+ int_nroots;
+
+ typ_nroots_1 lambda { { 0 } };
+ typ_nroots syn;
+ typ_nroots_1 b;
+ typ_nroots_1 t;
+ typ_nroots_1 omega;
+ int_nroots root;
+ typ_nroots_1 reg;
+ int_nroots loc;
+ int count = 0;
+
+ // Check length parameter and erasures for validity
+ int pad = NN - NROOTS - len;
+ if ( pad < 0 || pad >= NN ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: data length incompatible with block size and error correction symbols", -1 );
+ }
+ if ( no_eras ) {
+ if ( no_eras > NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: number of erasures exceeds capacity (number of roots)", -1 );
+ }
+ for ( int i = 0; i < no_eras; ++i ) {
+ if ( eras_pos[i] < 0 || eras_pos[i] >= len + NROOTS ) {
+ EZPWD_RAISE_OR_RETURN( std::runtime_error, "reed-solomon: erasure positions outside data+parity", -1 );
+ }
+ }
+ }
+
+ // form the syndromes; i.e., evaluate data(x) at roots of g(x)
+ for ( int i = 0; i < NROOTS; i++ )
+ syn[i] = data[0];
+
+ for ( int j = 1; j < len; j++ ) {
+ for ( int i = 0; i < NROOTS; i++ ) {
+ if ( syn[i] == 0 ) {
+ syn[i] = data[j];
+ } else {
+ syn[i] = data[j]
+ ^ alpha_to[modnn(index_of[syn[i]] + ( FCR + i ) * PRM)];
+ }
+ }
+ }
+
+ for ( int j = 0; j < NROOTS; j++ ) {
+ for ( int i = 0; i < NROOTS; i++ ) {
+ if ( syn[i] == 0 ) {
+ syn[i] = parity[j];
+ } else {
+ syn[i] = parity[j]
+ ^ alpha_to[modnn(index_of[syn[i]] + ( FCR + i ) * PRM)];
+ }
+ }
+ }
+
+ // Convert syndromes to index form, checking for nonzero condition
+ TYP syn_error = 0;
+ for ( int i = 0; i < NROOTS; i++ ) {
+ syn_error |= syn[i];
+ syn[i] = index_of[syn[i]];
+ }
+
+ int deg_lambda = 0;
+ int deg_omega = 0;
+ int r = no_eras;
+ int el = no_eras;
+ if ( ! syn_error ) {
+ // if syndrome is zero, data[] is a codeword and there are no errors to correct.
+ count = 0;
+ goto finish;
+ }
+
+ lambda[0] = 1;
+ if ( no_eras > 0 ) {
+ // Init lambda to be the erasure locator polynomial. Convert erasure positions
+ // from index into data, to index into Reed-Solomon block.
+ lambda[1] = alpha_to[modnn(PRM * (NN - 1 - ( eras_pos[0] + pad )))];
+ for ( int i = 1; i < no_eras; i++ ) {
+ TYP u = modnn(PRM * (NN - 1 - ( eras_pos[i] + pad )));
+ for ( int j = i + 1; j > 0; j-- ) {
+ TYP tmp = index_of[lambda[j - 1]];
+ if ( tmp != A0 ) {
+ lambda[j] ^= alpha_to[modnn(u + tmp)];
+ }
+ }
+ }
+ }
+
+#if DEBUG >= 1
+ // Test code that verifies the erasure locator polynomial just constructed
+ // Needed only for decoder debugging.
+
+ // find roots of the erasure location polynomial
+ for( int i = 1; i<= no_eras; i++ )
+ reg[i] = index_of[lambda[i]];
+
+ count = 0;
+ for ( int i = 1, k = iprim - 1; i <= NN; i++, k = modnn( k + iprim )) {
+ TYP q = 1;
+ for ( int j = 1; j <= no_eras; j++ ) {
+ if ( reg[j] != A0 ) {
+ reg[j] = modnn( reg[j] + j );
+ q ^= alpha_to[reg[j]];
+ }
+ }
+ if ( q != 0 )
+ continue;
+ // store root and error location number indices
+ root[count] = i;
+ loc[count] = k;
+ count++;
+ }
+ if ( count != no_eras ) {
+ std::cout << "ERROR: count = " << count << ", no_eras = " << no_eras
+ << "lambda(x) is WRONG"
+ << std::endl;
+ count = -1;
+ goto finish;
+ }
+#if DEBUG >= 2
+ if ( count ) {
+ std::cout
+ << "Erasure positions as determined by roots of Eras Loc Poly: ";
+ for ( int i = 0; i < count; i++ )
+ std::cout << loc[i] << ' ';
+ std::cout << std::endl;
+ std::cout
+ << "Erasure positions as determined by roots of eras_pos array: ";
+ for ( int i = 0; i < no_eras; i++ )
+ std::cout << eras_pos[i] << ' ';
+ std::cout << std::endl;
+ }
+#endif
+#endif
+
+ for ( int i = 0; i < NROOTS + 1; i++ )
+ b[i] = index_of[lambda[i]];
+
+ //
+ // Begin Berlekamp-Massey algorithm to determine error+erasure locator polynomial
+ //
+ while ( ++r <= NROOTS ) { // r is the step number
+ // Compute discrepancy at the r-th step in poly-form
+ TYP discr_r = 0;
+ for ( int i = 0; i < r; i++ ) {
+ if (( lambda[i] != 0 ) && ( syn[r - i - 1] != A0 )) {
+ discr_r ^= alpha_to[modnn(index_of[lambda[i]] + syn[r - i - 1])];
+ }
+ }
+ discr_r = index_of[discr_r]; // Index form
+ if ( discr_r == A0 ) {
+ // 2 lines below: B(x) <-- x*B(x)
+ // Rotate the last element of b[NROOTS+1] to b[0]
+ std::rotate( b.begin(), b.begin()+NROOTS, b.end() );
+ b[0] = A0;
+ } else {
+ // 7 lines below: T(x) <-- lambda(x)-discr_r*x*b(x)
+ t[0] = lambda[0];
+ for ( int i = 0; i < NROOTS; i++ ) {
+ if ( b[i] != A0 ) {
+ t[i + 1] = lambda[i + 1]
+ ^ alpha_to[modnn(discr_r + b[i])];
+ } else
+ t[i + 1] = lambda[i + 1];
+ }
+ if ( 2 * el <= r + no_eras - 1 ) {
+ el = r + no_eras - el;
+ // 2 lines below: B(x) <-- inv(discr_r) * lambda(x)
+ for ( int i = 0; i <= NROOTS; i++ ) {
+ b[i] = ((lambda[i] == 0)
+ ? A0
+ : modnn(index_of[lambda[i]] - discr_r + NN));
+ }
+ } else {
+ // 2 lines below: B(x) <-- x*B(x)
+ std::rotate( b.begin(), b.begin()+NROOTS, b.end() );
+ b[0] = A0;
+ }
+ lambda = t;
+ }
+ }
+
+ // Convert lambda to index form and compute deg(lambda(x))
+ for ( int i = 0; i < NROOTS + 1; i++ ) {
+ lambda[i] = index_of[lambda[i]];
+ if ( lambda[i] != NN )
+ deg_lambda = i;
+ }
+ // Find roots of error+erasure locator polynomial by Chien search
+ reg = lambda;
+ count = 0; // Number of roots of lambda(x)
+ for ( int i = 1, k = iprim - 1; i <= NN; i++, k = modnn( k + iprim )) {
+ TYP q = 1; // lambda[0] is always 0
+ for ( int j = deg_lambda; j > 0; j-- ) {
+ if ( reg[j] != A0 ) {
+ reg[j] = modnn( reg[j] + j );
+ q ^= alpha_to[reg[j]];
+ }
+ }
+ if ( q != 0 )
+ continue; // Not a root
+ // store root (index-form) and error location number
+#if DEBUG >= 2
+ std::cout << "count " << count << " root " << i << " loc " << k << std::endl;
+#endif
+ root[count] = i;
+ loc[count] = k;
+ // If we've already found max possible roots, abort the search to save time
+ if ( ++count == deg_lambda )
+ break;
+ }
+ if ( deg_lambda != count ) {
+ // deg(lambda) unequal to number of roots => uncorrectable error detected
+ count = -1;
+ goto finish;
+ }
+ //
+ // Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo x**NROOTS). in
+ // index form. Also find deg(omega).
+ //
+ deg_omega = deg_lambda - 1;
+ for ( int i = 0; i <= deg_omega; i++ ) {
+ TYP tmp = 0;
+ for ( int j = i; j >= 0; j-- ) {
+ if (( syn[i - j] != A0 ) && ( lambda[j] != A0 ))
+ tmp ^= alpha_to[modnn(syn[i - j] + lambda[j])];
+ }
+ omega[i] = index_of[tmp];
+ }
+
+ //
+ // Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = inv(X(l))**(fcr-1)
+ // and den = lambda_pr(inv(X(l))) all in poly-form
+ //
+ for ( int j = count - 1; j >= 0; j-- ) {
+ TYP num1 = 0;
+ for ( int i = deg_omega; i >= 0; i-- ) {
+ if ( omega[i] != A0 )
+ num1 ^= alpha_to[modnn(omega[i] + i * root[j])];
+ }
+ TYP num2 = alpha_to[modnn(root[j] * ( FCR - 1 ) + NN)];
+ TYP den = 0;
+
+ // lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i]
+ for ( int i = std::min(deg_lambda, NROOTS - 1) & ~1; i >= 0; i -= 2 ) {
+ if ( lambda[i + 1] != A0 ) {
+ den ^= alpha_to[modnn(lambda[i + 1] + i * root[j])];
+ }
+ }
+#if defined( DEBUG ) && DEBUG >= 1
+ if ( den == 0 ) {
+ std::cout << "ERROR: denominator = 0" << std::endl;
+ count = -1;
+ goto finish;
+ }
+#endif
+ // Apply error to data. Padding ('pad' unused symbols) begin at index 0.
+ if ( num1 != 0 ) {
+ if ( loc[j] < pad ) {
+ // If the computed error position is in the 'pad' (the unused portion of the
+ // R-S data capacity), then our solution has failed -- we've computed a
+ // correction location outside of the data and parity we've been provided!
+#if DEBUG >= 2
+ std::cout
+ << "ERROR: RS(" << SIZE <<"," << LOAD
+ << ") computed error location: " << loc[j]
+ << " within " << pad << " pad symbols, not within "
+ << LOAD - pad << " data or " << NROOTS << " parity"
+ << std::endl;
+#endif
+ count = -1;
+ goto finish;
+ }
+
+ TYP cor = alpha_to[modnn(index_of[num1]
+ + index_of[num2]
+ + NN - index_of[den])];
+ // Store the error correction pattern, if a correction buffer is available
+ if ( corr )
+ corr[j] = cor;
+ // If a data/parity buffer is given and the error is inside the message or
+ // parity data, correct it
+ if ( loc[j] < ( NN - NROOTS )) {
+ if ( data ) {
+ data[loc[j] - pad] ^= cor;
+ }
+ } else if ( loc[j] < NN ) {
+ if ( parity )
+ parity[loc[j] - ( NN - NROOTS )] ^= cor;
+ }
+ }
+ }
+
+ finish:
+#if defined( DEBUG ) && DEBUG > 0
+ if ( count > NROOTS )
+ std::cout << "ERROR: Number of corrections: " << count << " exceeds NROOTS: " << NROOTS << std::endl;
+#endif
+#if defined( DEBUG ) && DEBUG > 1
+ std::cout << "data x" << std::setw( 3 ) << len << ": " << std::vector<uint8_t>( data, data + len ) << std::endl;
+ std::cout << "parity x" << std::setw( 3 ) << NROOTS << ": " << std::string( len * 2, ' ' ) << std::vector<uint8_t>( parity, parity + NROOTS ) << std::endl;
+ if ( count > 0 ) {
+ std::string errors( 2 * ( len + NROOTS ), ' ' );
+ for ( int i = 0; i < count; ++i ) {
+ errors[2*(loc[i]-pad)+0] = 'E';
+ errors[2*(loc[i]-pad)+1] = 'E';
+ }
+ for ( int i = 0; i < no_eras; ++i ) {
+ errors[2*(eras_pos[i])+0] = 'e';
+ errors[2*(eras_pos[i])+1] = 'e';
+ }
+ std::cout << "e)ra,E)rr x" << std::setw( 3 ) << count << ": " << errors << std::endl;
+ }
+#endif
+ if ( eras_pos != NULL ) {
+ for ( int i = 0; i < count; i++)
+ eras_pos[i] = loc[i] - pad;
+ }
+ return count;
+ }
+ }; // class reed_solomon
+
+ //
+ // Define the static reed_solomon...<...> members; allowed in header for template types.
+ //
+ // The reed_solomon_tags<...>::iprim < 0 is used to indicate to the first instance that the
+ // static tables require initialization.
+ //
+ template < typename TYP, int SYM, int PRM, class PLY >
+ int reed_solomon_tabs< TYP, SYM, PRM, PLY >::iprim = -1;
+
+ template < typename TYP, int SYM, int PRM, class PLY >
+ std::array< TYP, reed_solomon_tabs< TYP, SYM, PRM, PLY >
+#if not defined( EZPWD_ARRAY_TEST )
+ ::NN + 1 >
+#else
+# warning "EZPWD_ARRAY_TEST: Erroneously defining alpha_to size!"
+ ::NN >
+#endif
+ reed_solomon_tabs< TYP, SYM, PRM, PLY >::alpha_to;
+
+ template < typename TYP, int SYM, int PRM, class PLY >
+ std::array< TYP, reed_solomon_tabs< TYP, SYM, PRM, PLY >::NN + 1 >
+ reed_solomon_tabs< TYP, SYM, PRM, PLY >::index_of;
+ template < typename TYP, int SYM, int PRM, class PLY >
+ std::array< TYP, reed_solomon_tabs< TYP, SYM, PRM, PLY >::MODS >
+ reed_solomon_tabs< TYP, SYM, PRM, PLY >::mod_of;
+
+ template < typename TYP, int SYM, int RTS, int FCR, int PRM, class PLY >
+ std::array< TYP, reed_solomon< TYP, SYM, RTS, FCR, PRM, PLY >::NROOTS + 1 >
+ reed_solomon< TYP, SYM, RTS, FCR, PRM, PLY >::genpoly;
+
+} // namespace ezpwd
+
+#endif // _EZPWD_RS_BASE
diff --git a/op25/gr-op25_repeater/lib/ezpwd/serialize b/op25/gr-op25_repeater/lib/ezpwd/serialize
new file mode 100644
index 0000000..ae4a62c
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/serialize
@@ -0,0 +1,1188 @@
+/*
+ * Ezpwd Reed-Solomon -- Reed-Solomon encoder / decoder library
+ *
+ * Copyright (c) 2014, Hard Consulting Corporation.
+ *
+ * Ezpwd Reed-Solomon is free software: you can redistribute it and/or modify it under the terms of
+ * the GNU General Public License as published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version. See the LICENSE file at the top of the
+ * source tree. Ezpwd Reed-Solomon is also available under Commercial license. c++/ezpwd/rs_base
+ * is redistributed under the terms of the LGPL, regardless of the overall licensing terms.
+ *
+ * Ezpwd Reed-Solomon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ */
+#ifndef _EZPWD_SERIALIZE
+#define _EZPWD_SERIALIZE
+
+#include <iterator>
+#include <array>
+
+#include "output"
+
+//
+// EZPWD (no padding) and RFC4648 (enforce padding) base-N codecs
+//
+// scatter -- 8-bit binary data into 5-bit (base32) and 6-bit (base64) chunks (optionally w/pad)
+// gather -- collect up 5/6-bit binary data back into 8-bit characters (optionally w/pad)
+// ..._standard -- enforce RFC4648-standard padding
+//
+// Scatters or gathers 8-bit binary character data to 5/6-bit symbols, suitable for base32/64
+// encoding.
+//
+// encode -- convert binary data to ASCII base32/64, in-place
+// decode -- convert ASCII base32/64 to binary data, in-place
+// ..._standard -- enforce RFC4648-standard padding
+//
+// Transforms iterable containers of char between ASCII symbols and binary data, always in-place.
+// The decode may alter the size of the result (by ignoring whitespace).
+//
+// In general the ezpwd::base32/64 en/decoders are designed to produce easily human-usable
+// encodings, and can ignore common whitespace characters and '-' to allow human-readable
+// formatting. The RFC4648 Standard base 32/64 and Crockford base32 encodings are also supported.
+//
+// Adding new symbol encodings (and even new bases, up to base-128) is trivial.
+//
+namespace ezpwd {
+
+ namespace serialize {
+
+ enum chr_t {
+ pd = -1, // padding
+ nv = -2, // invalid
+ ws = -3, // whitespace
+ };
+
+ enum ws_use_t {
+ ws_invalid = 0, // Whitespace is invalid
+ ws_ignored = 1, // Whitespace ignored (the default)
+ };
+
+ enum pd_use_t {
+ pd_invalid = 0, // Padding is not expected (invalid)
+ pd_ignored = 1, // Padding is ignored, and automatically supplied if required (the default)
+ pd_enforce = 2, // Padding is expected and enforced
+ };
+
+ //
+ // serialize::tables -- base class for TABLES in all base<N,TABLES>
+ //
+ // Every serialize::table<BASE> specialization must have an encoder table of size BASE,
+ // and a decoder table of size 127.
+ //
+
+ //
+ // hex<16/32> -- RFC4648 4-bit (standard 16 symbol) and 5-bit (32 symbol)
+ // standard<16/32/64> -- RFC4648 standard tables
+ // standard_url<64> -- RFC4648 standard tables (base-64 URL-safe)
+ // ezpwd<16/32/64> -- EZPWD tables
+ // crockford<32> -- Crockford (base32 only)
+ //
+ // These types are passed as the TABLE template parameter to base<32/64,TABLE> class
+ // template instantiations. They must specify an encoder table of size BASE, and a decoder
+ // table of size 127.
+ //
+ template < size_t N > struct hex { };
+ template < size_t N > struct uuencode { };
+ template < size_t N > struct standard { };
+ template < size_t N > struct standard_url { };
+ template < size_t N > struct ezpwd { };
+ template < size_t N > struct crockford { };
+
+ //
+ // base<16> tables -- basic hexadecimal supported (hex, standard, ezpwd identical)
+ //
+ template <> struct hex<16> {
+ static const constexpr std::array<char,16>
+ encoder { {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, // !"#$%&`()*+,-./
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, nv, nv, nv, nv, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 10, 11, 12, 13, 14, 15, nv, nv, nv, nv, nv, nv, nv, nv, nv, // @ABCDEFGHIJKLMNO
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 10, 11, 12, 13, 14, 15, nv, nv, nv, nv, nv, nv, nv, nv, nv, // `abcdefghijklmno
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::hex<16>
+
+ template <> struct standard<16> {
+ static const constexpr std::array<char,16>
+ encoder = hex<16>::encoder;
+ static const constexpr std::array<char,127>
+ decoder = hex<16>::decoder;
+ };
+
+ template <> struct ezpwd<16> {
+ static const constexpr std::array<char,16>
+ encoder = hex<16>::encoder;
+ static const constexpr std::array<char,127>
+ decoder = hex<16>::decoder;
+ };
+
+ //
+ // base<32> tables -- ezpwd, and RFC4648 hex32, crockford and standard
+ //
+ template <> struct hex<32> {
+ static const constexpr std::array<char,32>
+ encoder { {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
+ 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
+ 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, // !"#$%&`()*+,-./
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, nv, nv, nv, nv, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // @ABCDEFGHIJKLMNO
+ 25, 26, 27, 28, 29, 30, 31, nv, nv, nv, nv, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // `abcdefghijklmno
+ 25, 26, 27, 28, 29, 30, 31, nv, nv, nv, nv, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::hex<32>
+
+ template <> struct standard<32> { // RFC4648 Standard
+ static const constexpr std::array<char,32>
+ encoder { {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', '2', '3', '4', '5', '6', '7',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, // !"#$%&`()*+,-./
+ nv, nv, 26, 27, 28, 29, 30, 31, nv, nv, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>?
+ nv, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // @ABCDEFGHIJKLMNO '=' is pad
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // `abcdefghijklmno
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::standard<32>
+
+ template <> struct ezpwd<32> {
+ static const constexpr std::array<char,32>
+ encoder { {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
+ 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
+ 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y',
+ } };
+
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, nv, nv, // !"#$%&`()*+,-./ '-' is whitespace
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 1, 18, 19, 20, 21, 22, 0, // @ABCDEFGHIJKLMNO
+ 23, 24, 25, 5, 26, 27, 28, 29, 30, 31, 2, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 1, 18, 19, 20, 21, 22, 0, // `abcdefghijklmno
+ 23, 24, 25, 5, 26, 27, 28, 29, 30, 31, 2, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::ezpwd<32>
+
+ template <> struct crockford<32> {
+ static const constexpr std::array<char,32>
+ encoder { {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
+ 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q',
+ 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z',
+ } };
+
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, nv, nv, // !"#$%&`()*+,-./ '-' is whitespace
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 1, 18, 19, 1, 20, 21, 0, // @ABCDEFGHIJKLMNO
+ 22, 23, 24, 25, 26, nv, 27, 28, 29, 30, 31, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 10, 11, 12, 13, 14, 15, 16, 17, 1, 18, 19, 1, 20, 21, 0, // `abcdefghijklmno
+ 22, 23, 24, 25, 26, nv, 27, 28, 29, 30, 31, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::crockford<32>
+
+ //
+ // base<64> tables
+ //
+ template <> struct uuencode<64> {
+ static const constexpr std::array<char,64>
+ encoder { {
+ ' ', '!', '"', '#', '$', '%', '&','\'',
+ '(', ')', '*', '+', ',', '-', '.', '/',
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', ':', ';', '<', '=', '>', '?',
+ '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
+ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
+ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
+ 'X', 'Y', 'Z', '[','\\', ']', '^', '_',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // !"#$%&`()*+,-./
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 0123456789:;<=>? '=' is pad
+ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // @ABCDEFGHIJKLMNO
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // PQRSTUVWXYZ[\]^_
+ nv, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // `abcdefghijklmno
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, nv, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::standard<64>
+
+ template <> struct standard<64> {
+ static const constexpr std::array<char,64> // RFC4648 Standard
+ encoder { {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
+ 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
+ 'w', 'x', 'y', 'z', '0', '1', '2', '3',
+ '4', '5', '6', '7', '8', '9', '+', '/',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 62, nv, nv, nv, 63, // !"#$%&`()*+,-./
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // @ABCDEFGHIJKLMNO
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, nv, nv, nv, nv, nv, // PQRSTUVWXYZ[\]^_
+ nv, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // `abcdefghijklmno
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::standard<64>
+
+ template <> struct standard_url<64> {
+ static const constexpr std::array<char,64>
+ encoder { {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
+ 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
+ 'w', 'x', 'y', 'z', '0', '1', '2', '3',
+ '4', '5', '6', '7', '8', '9', '-', '_',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 62, nv, nv, // !"#$%&`()*+,-./
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // @ABCDEFGHIJKLMNO
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, nv, nv, nv, nv, 63, // PQRSTUVWXYZ[\]^_
+ nv, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // `abcdefghijklmno
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::standar_url<64>
+
+ template <> struct ezpwd<64> {
+ static const constexpr std::array<char,64> // '+' and '.' are URL safe, and we treat '-' as whitespace
+ encoder { {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
+ 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
+ 'w', 'x', 'y', 'z', '0', '1', '2', '3',
+ '4', '5', '6', '7', '8', '9', '+', '.',
+ } };
+ static const constexpr std::array<char,127>
+ decoder { {
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, ws, ws, ws, ws, ws, nv, nv, // 9-13: <TAB>,<NL>,<VT>,<FF>,<CR>
+ nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, //
+ ws, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 62, nv, ws, 63, nv, // !"#$%&`()*+,-./ '-' is whitespace
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, nv, nv, nv, pd, nv, nv, // 0123456789:;<=>? '=' is pad
+ nv, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // @ABCDEFGHIJKLMNO
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, nv, nv, nv, nv, 63, // PQRSTUVWXYZ[\]^_
+ nv, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // `abcdefghijklmno
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, nv, nv, nv, nv, // pqrstuvwxyz{|}~
+ } };
+ }; // struct serialize::ezpwd<64>
+
+ //
+ // base_generic<N, TABLES> -- generic base-N conversion using TABLES<N>. Doesn't have scatter/gather.
+ //
+ // Every base-N converter requires a TABLE class of matching N, and can encode/decode.
+ // in-place using the table::encoder/decoder arrays. Only specific values of N have class
+ // template specialization which includes scatter/gather methods -- the generic base-N
+ // template does not..
+ //
+ template < size_t N, typename TABLES = ezpwd< N >>
+ class base_generic
+ : public TABLES {
+ public:
+ static
+ std::ostream &output(
+ std::ostream &lhs )
+ {
+ lhs << "base<" << N;
+#if defined( DEBUG ) && DEBUG >= 3
+ lhs << "," << TABLES::encoder;
+#endif
+ lhs << ">";
+ return lhs;
+ }
+
+ //
+ // base<N>::encode(<string>) -- encode the supplied sequence of data in the domain (0,N] to base-N
+ // base<N>::encode(<iter>,<iter>) -- encode the supplied std::string of (0,N] symbols in-place to base-N
+ //
+ // Items from iterator must be convertible to a table index (ie. not -'ve, and within
+ // the table size N). If the table contains 'ws' entries, they may optionally be ignored.
+ // If the input symbol indexes outside the provided encoder table (or an 'nv' entry), then an
+ // exception will be thrown.
+ //
+ // If a non-zero 'pad' character is supplied, then the -1 (pd) character value will be
+ // allowed (normally occurring only at the end of the input range), and a 'pad' will be
+ // emitted for each one.
+ //
+ template < typename I >
+ static
+ I encode(
+ I begin,
+ I end,
+ char pad = '=' ) // '=' for standards-compliance
+ {
+ for ( I i = begin; i != end; ++i ) {
+ if ( *i >= 0 and size_t( *i ) < TABLES::encoder.size() )
+ *i = TABLES::encoder[*i];
+ else if ( pd == *i and pad )
+ *i = pad;
+ else
+ throw std::runtime_error(
+ std::string( "ezpwd::serialize::encode: invalid base-" ) << N
+ << " binary symbol presented: " << *i );
+ }
+ return end;
+ }
+
+ static
+ std::string &encode(
+ std::string &symbols,
+ char pad = '=' ) // '=' for standards-compliance
+ {
+ encode( symbols.begin(), symbols.end(), pad );
+ return symbols;
+ }
+
+ //
+ // base<N>::decode(<iter>,<iter>) -- decode base-N symbols in-place, collapsing spaces.
+ // base<N>::decode(<string>) -- decode base-N symbols in supplied std::string, collapsing spaces, in-place.
+ //
+ // Items from iterator must be convertible to a table index (ie. not -'ve, and within
+ // the table size, which is always 127).
+ //
+ // ws_ignored -- skip whitepace/- symbols (the default)
+ // ws_invalid -- consider whitespace/- symbols as invalid symbols
+ //
+ // pd_invalid -- consider padding symbols as invalid
+ // pd_ignored -- skip padding symbols
+ // pd_enforce -- leave any padding symbols in place (the default)
+ //
+ // If erasure vector supplied, marks invalid symbols as erasures; otherwise, throws
+ // exception. Ignores whitespace. Will return an iterator to just after the last output
+ // symbol used in the provided range (eg. to shorten the container, if desired), leaving any
+ // remaining symbols unchanged. The <string> version returns the same string reference
+ // passed in (shortened, if spaces/padding ignored).
+ //
+ // If an invalid vector is supplied, we'll also return the offending input symbol(s); if
+ // an exception is raised (no erasure vector supplied), only one symbol will be in invalid.
+ //
+ // NOTE: will quite likely return an iterator before the supplied 'end', indicating that the
+ // output has been truncated (shortened), due to collapsing spaces!
+ //
+ template < typename I >
+ static
+ I decode(
+ I begin,
+ I end,
+ std::vector<int> *erasure, // Deem invalid symbols as erasures
+ std::vector<char> *invalid = 0, // and return the symbols
+ ws_use_t ws_use = ws_ignored, // skip any whitespace
+ pd_use_t pd_use = pd_invalid ) // no padding expected; invalid
+ {
+ if ( erasure )
+ erasure->clear();
+ if ( invalid )
+ invalid->clear();
+ I i, o;
+ for ( i = o = begin; i != end; ++i ) {
+ size_t ti( *i );
+ char c = ti < TABLES::decoder.size() ? TABLES::decoder[ti] : char( nv );
+ if ( ws == c )
+ switch ( ws_use ) {
+ case ws_invalid:
+ c = nv;
+ break;
+ case ws_ignored: default:
+ continue;
+ }
+ if ( pd == c )
+ switch ( pd_use ) {
+ case pd_invalid:
+ c = nv;
+ break;
+ case pd_enforce:
+ break;
+ case pd_ignored: default:
+ continue;
+ }
+ if ( nv == c ) {
+ // Invalid symbol; optionally remember them. Mark as erasure? Or throw.
+ if ( invalid )
+ invalid->push_back( *i );
+ if ( erasure ) {
+ erasure->push_back( o - begin ); // index of offending symbol in output
+ c = 0; // will be output w/ 0 value
+ } else {
+ throw std::runtime_error(
+ std::string( "ezpwd::serialize::decode: invalid base-" ) << N
+ << " ASCII symbol presented: " << int( *i ) << " '" << *i << "'" );
+ }
+ }
+ *o++ = c;
+ }
+ return o;
+ }
+
+ template < typename I >
+ static
+ I decode(
+ I begin,
+ I end,
+ ws_use_t ws_use = ws_ignored,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return decode( begin, end, 0, 0, ws_use, pd_use );
+ }
+
+ template < typename I >
+ static
+ I decode_standard(
+ I begin,
+ I end )
+ {
+ return decode( begin, end, 0, 0, ws_ignored, pd_enforce ); // RFC4648 padding
+ }
+
+ static
+ std::string &decode(
+ std::string &symbols,
+ std::vector<int> *erasure = 0,
+ std::vector<char> *invalid = 0,
+ ws_use_t ws_use = ws_ignored,
+ pd_use_t pd_use = pd_invalid )
+ {
+ auto last = decode( symbols.begin(), symbols.end(), erasure, invalid,
+ ws_use, pd_use );
+ if ( last != symbols.end() )
+ symbols.resize( last - symbols.begin() ); // eliminated some whitespace
+ return symbols;
+ }
+ static
+ std::string &decode_standard(
+ std::string &symbols,
+ std::vector<int> *erasure = 0,
+ std::vector<char> *invalid = 0 )
+ {
+ return decode( symbols, erasure, invalid, ws_ignored, pd_enforce ); // RFC4648 padding
+ }
+
+ //
+ // gather_next -- return next symbol to gather into 8-bit output
+ //
+ // Fails if padding mixed in with data, or a data symbol exceeds encoding bit depth
+ // (eg. 5 bits for base-32).
+ //
+ // If auto-padding, allow the caller to differentiate
+ //
+ template < typename I >
+ static
+ int gather_next( I &beg, I end, pd_use_t pd_use, int previous )
+ {
+ if ( beg == end ) {
+ if ( pd_enforce == pd_use )
+ throw std::logic_error( std::string( "base-" ) << N << " gather error; insufficient data");
+ // automatically pad; return nv on underflow while un-emitted data remains, finally pd
+ return previous >= 0 ? nv : pd;
+ }
+ int c = *beg++;
+ if ( previous < 0 and c >= 0 )
+ throw std::logic_error(
+ std::string( "base-" ) << N << " gather error; data following padding" );
+ if ( c >= char( N ) or c < pd )
+ throw std::logic_error(
+ std::string( "base-" ) << N << " gather error; symbol value " << int( c ) << " beyond capacity" );
+ return c;
+ }
+ }; // class serialize::base_generic
+ } // namespace serialize
+
+ template < size_t N, typename TABLES >
+ std::ostream &operator<<(
+ std::ostream &lhs,
+ const ezpwd::serialize::base_generic<N,TABLES>
+ &rhs )
+ {
+ return rhs.output( lhs );
+ }
+
+ namespace serialize {
+ //
+ // ezpwd::serialize::base<N> -- Arbitrary bases (other than those with specializations below)
+ //
+ // Can en/decode, but no scatter/gather implementation, nor encode_size.
+ //
+ template < size_t N, typename TABLES >
+ class base
+ : public base_generic< N, TABLES > {
+ public:
+ using base_generic< N, TABLES >::encode;
+ using base_generic< N, TABLES >::decode;
+ };
+
+
+ //
+ // ezpwd::serialize::base<16> -- transform individual characters between 4-bit binary and a base-16
+ //
+ template < typename TABLES >
+ class base< 16, TABLES >
+ : public base_generic< 16, TABLES > {
+ public:
+ using base_generic< 16, TABLES >::encode;
+ using base_generic< 16, TABLES >::decode;
+ using base_generic< 16, TABLES >::gather_next;
+
+ static constexpr size_t encode_size(
+ size_t len,
+ pd_use_t /* pd_use */ = pd_invalid )
+ {
+ return len * 2; // encoding base-16 always exactly doubles size
+ }
+
+ //
+ // base<16>::scatter -- distribute a range of input bytes to an output iterator in 4-bit chunks
+ //
+ // The same implementation is used for both random-access iterators, and for all
+ // other forward iterators.
+ //
+ template < typename I, typename O, typename iterator_tag >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t, // ignored; never needs to pad
+ iterator_tag ) // ignored
+ {
+ while ( beg != end ) {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 4);
+ *out++ = char((c0 & 0x0f));
+ }
+ return out;
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return scatter( beg, end, out, pd_use, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return scatter( beg, end, out, pd_enforce, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ //
+ // base<16>::gather -- collect 4-bit chunks into 8-bit characters
+ //
+ // If underflow occurs (not enough data collected to output complete last char), then an
+ // exception will be raised. However, if 'pad' is set, then output will automatically be
+ // padded, flushing out any un-emitted data remaining in previous 4-bit base-16 symbol.
+ //
+ // For correct base-16 data produced by 'scatter', this will allow 'gather' to always
+ // produce the identical output as was originally provided to 'scatter'. However, if simply
+ // truncated base-16 input is provided (eg. only 1 symbols of an 2-symbol 8-bit
+ // base-16 group), then the final 8-bit symbol from the original data will be missing.
+ //
+ template < typename I, typename O >
+ static
+ O gather(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ while ( beg != end ) {
+ int c0 = gather_next( beg, end, pd_use, 0 );
+ int c1 = gather_next( beg, end, pd_use, c0 );
+ if ( c0 >= 0 and c1 >= 0 )
+ *out++ = ( ((c0 < 0 ? 0 : c0 ) << 4)
+ | (c1 < 0 ? 0 : c1 ));
+ }
+ return out;
+ }
+ template < typename I, typename O >
+ static
+ O gather_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return gather( beg, end, out, pd_enforce );
+ }
+ }; // ezpwd::base<16>
+
+ //
+ // ezpwd::serialize::base16...
+ //
+ // Shortcut typedefs for the available base16 codec.
+ //
+ typedef base< 16, hex< 16 >>
+ base16;
+ typedef base< 16, hex< 16 >>
+ base16_standard;
+
+
+ //
+ // ezpwd::serialize::base<32> -- transform individual characters between 5-bit binary and a base-32
+ //
+ // The char values [0,32) are mapped by base<32>::encode onto something like
+ //
+ // 0123456789ABCDEFGHJKLMNPQRTUVWXY TABLES=ezpwd<32> (default)
+ // 0123456789ABCDEFGHJKMNPQRSTVWXYZ TABLES=crockford<32>
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 TABLES=standard<32>
+ //
+ // and base<32>::decode performs the inverse. In addition to folding lower-case to
+ // upper-case, the following mappings occur in the ezpwd<32>::decoder table:
+ //
+ // O -> 0
+ // Z -> 2
+ // S -> 5
+ // I -> 1
+ //
+ // B -> 8 could not be included due to the limited size of the capitalized alpha-numeric
+ // symbol pool, unfortunately, but the other substitutions were prioritized as they are
+ // more likely to occur in standard printed text.
+ //
+ // Any characters encountered outside [0,32) by encode and outside the above set by
+ // decode raise an exception, unless an erasure vector is provided, in which case we supply
+ // a 0 value and store the index of the invalid symbol in the vector.
+ //
+ template < typename TABLES >
+ class base< 32, TABLES >
+ : public base_generic< 32, TABLES > {
+ public:
+ using base_generic< 32, TABLES >::encode;
+ using base_generic< 32, TABLES >::decode;
+ using base_generic< 32, TABLES >::gather_next;
+
+ static constexpr size_t encode_size(
+ size_t len,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return ( pd_enforce == pd_use
+ ? ( len + 4 ) / 5 * 8
+ : ( len * 8 + 4 ) / 5 );
+ }
+
+ //
+ // base<32>::scatter -- distribute a range of input bytes to an output iterator in 5-bit chunks
+ //
+ // Separate implementation are provided for random-access iterators (with fewer
+ // comparisons necessary) and for all other forward iterators.
+ //
+ template < typename I, typename O, typename iterator_tag >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use,
+ iterator_tag )
+ {
+ while ( beg != end ) {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+
+ if ( beg == end ) {
+ *out++ = char((c0 & 0x07) << 2);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x07) << 2 | (c1 & 0xff) >> 6);
+ *out++ = char((c1 & 0x3f) >> 1);
+
+ if ( beg == end ) {
+ *out++ = char((c1 & 0x01) << 4);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x01) << 4 | (c2 & 0xff) >> 4);
+
+ if ( beg == end ) {
+ *out++ = char((c2 & 0x0f) << 1);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c3 = *beg++;
+ *out++ = char((c2 & 0x0f) << 1 | (c3 & 0xff) >> 7);
+ *out++ = char((c3 & 0x7f) >> 2);
+
+ if ( beg == end ) {
+ *out++ = char((c3 & 0x03) << 3);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c4 = *beg++;
+ *out++ = char((c3 & 0x03) << 3 | (c4 & 0xff) >> 5);
+ *out++ = char((c4 & 0x1f));
+ }
+
+ return out;
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use,
+ std::random_access_iterator_tag )
+ {
+ while ( end - beg >= 5 ) {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x07) << 2 | (c1 & 0xff) >> 6);
+ *out++ = char((c1 & 0x3f) >> 1);
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x01) << 4 | (c2 & 0xff) >> 4);
+ int c3 = *beg++;
+ *out++ = char((c2 & 0x0f) << 1 | (c3 & 0xff) >> 7);
+ *out++ = char((c3 & 0x7f) >> 2);
+ int c4 = *beg++;
+ *out++ = char((c3 & 0x03) << 3 | (c4 & 0xff) >> 5);
+ *out++ = char((c4 & 0x1f));
+ }
+
+ switch ( end - beg ) {
+ case 4: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x07) << 2 | (c1 & 0xff) >> 6);
+ *out++ = char((c1 & 0x3f) >> 1);
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x01) << 4 | (c2 & 0xff) >> 4);
+ int c3 = *beg++;
+ *out++ = char((c2 & 0x0f) << 1 | (c3 & 0xff) >> 7);
+ *out++ = char((c3 & 0x7f) >> 2);
+ *out++ = char((c3 & 0x03) << 3);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ }
+ return out;
+ }
+ case 3: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x07) << 2 | (c1 & 0xff) >> 6);
+ *out++ = char((c1 & 0x3f) >> 1);
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x01) << 4 | (c2 & 0xff) >> 4);
+ *out++ = char((c2 & 0x0f) << 1);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+ case 2: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x07) << 2 | (c1 & 0xff) >> 6);
+ *out++ = char((c1 & 0x3f) >> 1);
+ *out++ = char((c1 & 0x01) << 4);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+ case 1: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 3);
+ *out++ = char((c0 & 0x07) << 2);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+ default:
+ return out;
+ }
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return scatter( beg, end, out, pd_use, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return scatter( beg, end, out, pd_enforce, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ //
+ // base<32>::gather -- collect 5-bit chunks into 8-bit characters
+ //
+ // If underflow occurs (not enough data collected to output complete last char), then an
+ // exception will be raised. However, if 'pad' is set, then output will automatically be
+ // padded, discarding any un-emitted data remaining in previous 5-bit base-32 symbols.
+ //
+ // For correct base-32 data produced by 'scatter', this will allow 'gather' to always
+ // produce the identical output as was originally provided to 'scatter'. However, if simply
+ // truncated base-32 input is provided (eg. only 1, 3 or 5 symbols of an 8-symbol 40-bit
+ // base-32 group), then the final 8-bit symbol from the original data will be missing.
+ //
+ template < typename I, typename O >
+ static
+ O gather(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ while ( beg != end ) {
+ int c0 = gather_next( beg, end, pd_use, 0 );
+ int c1 = gather_next( beg, end, pd_use, c0 );
+ if ( c0 >= 0 and c1 >= 0 )
+ *out++ = ( ((c0 < 0 ? 0 : c0 ) << 3)
+ | (c1 < 0 ? 0 : c1 ) >> 2 );
+ int c2 = gather_next( beg, end, pd_use, c1 );
+ int c3 = gather_next( beg, end, pd_use, c2 );
+ if ( c1 >= 0 and c2 >= 0 and c3 >= 0 )
+ *out++ = ( ((c1 < 0 ? 0 : c1) & 0x03) << 6
+ | (c2 < 0 ? 0 : c2) << 1
+ | (c3 < 0 ? 0 : c3) >> 4 );
+ int c4 = gather_next( beg, end, pd_use, c3 );
+ if ( c3 >= 0 and c4 >= 0 )
+ *out++ = ( ((c3 < 0 ? 0 : c3) & 0x0f) << 4
+ | (c4 < 0 ? 0 : c4) >> 1 );
+ int c5 = gather_next( beg, end, pd_use, c4 );
+ int c6 = gather_next( beg, end, pd_use, c5 );
+ if ( c4 >=0 and c5 >= 0 and c6 >= 0 )
+ *out++ = ( ((c4 < 0 ? 0 : c4) & 0x01) << 7
+ | (c5 < 0 ? 0 : c5) << 2
+ | (c6 < 0 ? 0 : c6) >> 3 );
+ int c7 = gather_next( beg, end, pd_use, c6 );
+ if ( c6 >= 0 and c7 >= 0 )
+ *out++ = ( ((c6 < 0 ? 0 : c6 ) & 0x07) << 5
+ | (c7 < 0 ? 0 : c7 ));
+ }
+ return out;
+ }
+ template < typename I, typename O >
+ static
+ O gather_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return gather( beg, end, out, pd_enforce );
+ }
+ }; // ezpwd::base<32>
+
+ //
+ // ezpwd::serialize::base32...
+ //
+ // Shortcut typedefs for the available base32 codecs.
+ //
+ typedef base< 32, ezpwd< 32 >>
+ base32;
+ typedef base< 32, hex< 32 >>
+ base32_hex;
+ typedef base< 32, serialize::standard< 32 >>
+ base32_standard;
+ typedef base< 32, crockford< 32 >>
+ base32_crockford;
+
+
+ //
+ // ezpwd::serialize::base<64> -- transform individual characters between 6-bit binary and base-64
+ //
+ // The char values [0,64) are mapped by base64::encode onto either the
+ // standard or ezpwd (url-safe) tables:
+ //
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ -- RFC4648 standard
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ -- RFC4648 standard_url
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+. -- ezpwd
+ //
+ // and base<64>::decode performs the inverse (handles both standard and url-safe encodings).
+ //
+ // Any characters encountered outside [0,64) by encode and outside the above set
+ // by decode raise an exception.
+ //
+ template < typename TABLES >
+ class base< 64, TABLES >
+ : public base_generic< 64, TABLES > {
+ public:
+ using base_generic< 64, TABLES >::encode;
+ using base_generic< 64, TABLES >::decode;
+ using base_generic< 64, TABLES >::gather_next;
+
+ static constexpr size_t encode_size(
+ size_t len,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return ( pd_enforce == pd_use
+ ? ( len + 2 ) / 3 * 4
+ : ( len * 4 + 2 ) / 3 );
+ }
+
+ //
+ // base<64>::scatter -- distribute a range of input bytes to an output iterator in 6-bit chunks
+ //
+ template < typename I, typename O, typename iterator_tag >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use,
+ iterator_tag )
+ {
+ while ( beg != end ) {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 2);
+
+ if ( beg == end ) {
+ *out++ = char((c0 & 0x03) << 4);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x03) << 4 | (c1 & 0xff) >> 4);
+
+ if ( beg == end ) {
+ *out++ = char((c1 & 0x0f) << 2);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ }
+ return out;
+ }
+
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x0f) << 2 | (c2 & 0xff) >> 6);
+ *out++ = char((c2 & 0x3f));
+ }
+
+ return out;
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use,
+ std::random_access_iterator_tag )
+ {
+ while ( end - beg >= 3 ) {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 2);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x03) << 4 | (c1 & 0xff) >> 4);
+ int c2 = *beg++;
+ *out++ = char((c1 & 0x0f) << 2 | (c2 & 0xff) >> 6);
+ *out++ = char((c2 & 0x3f));
+ }
+
+ switch ( end - beg ) {
+ case 2: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 2);
+ int c1 = *beg++;
+ *out++ = char((c0 & 0x03) << 4 | (c1 & 0xff) >> 4);
+ *out++ = char((c1 & 0x0f) << 2);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ }
+ return out;
+ }
+ case 1: {
+ int c0 = *beg++;
+ *out++ = char((c0 & 0xff) >> 2);
+ *out++ = char((c0 & 0x03) << 4);
+ if ( pd_enforce == pd_use ) {
+ *out++ = EOF;
+ *out++ = EOF;
+ }
+ return out;
+ }
+ default:
+ return out;
+ }
+ }
+
+ template < typename I, typename O >
+ static
+ O scatter(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ return scatter( beg, end, out, pd_use, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+
+ template < typename I, typename O >
+ static
+ O scatter_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return scatter( beg, end, out, pd_enforce, typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ //
+ // base<64>::gather -- collect 6-bit chunks into 8-bit characters
+ //
+ template < typename I, typename O >
+ static
+ O gather(
+ I beg,
+ I end,
+ O out,
+ pd_use_t pd_use = pd_invalid )
+ {
+ while ( beg != end ) {
+ int c0 = gather_next( beg, end, pd_use, 0 );
+ int c1 = gather_next( beg, end, pd_use, c0 );
+ if ( c0 >= 0 and c1 >= 0 )
+ *out++ = ( ((c0 < 0 ? 0 : c0 ) << 2 )
+ | (c1 < 0 ? 0 : c1 ) >> 4 );
+ int c2 = gather_next( beg, end, pd_use, c1 );
+ if ( c1 >= 0 and c2 >= 0 )
+ *out++ = ( ((c1 < 0 ? 0 : c1) & 0x0f) << 4
+ | (c2 < 0 ? 0 : c2) >> 2 );
+ int c3 = gather_next( beg, end, pd_use, c2 );
+ if ( c2 >= 0 and c3 >= 0 )
+ *out++ = ( ((c2 < 0 ? 0 : c2) & 0x03) << 6
+ | (c3 < 0 ? 0 : c3));
+ }
+ return out;
+ }
+ template < typename I, typename O >
+ static
+ O gather_standard(
+ I beg,
+ I end,
+ O out )
+ {
+ return gather( beg, end, out, pd_enforce );
+ }
+ }; // ezpwd::serialize::base<64>
+
+ //
+ // ezpwd::serialize::base64...
+ //
+ // Shortcut typedefs for the standard base-64 codecs.
+ //
+ typedef base< 64, ezpwd< 64 >>
+ base64;
+ typedef base< 64, standard< 64 >>
+ base64_standard;
+ typedef base< 64, standard_url< 64 >>
+ base64_standard_url;
+ typedef base< 64, uuencode< 64 >>
+ base64_uuencode;
+ } // namespace ezpwd::serialize
+
+} // namespace ezpwd
+
+#endif // _EZPWD_SERIALIZE
diff --git a/op25/gr-op25_repeater/lib/ezpwd/serialize_definitions b/op25/gr-op25_repeater/lib/ezpwd/serialize_definitions
new file mode 100644
index 0000000..00b3fb7
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/serialize_definitions
@@ -0,0 +1,57 @@
+
+//
+// The encoder/decoder tables for all ezpwd::serialize::... base<N> codecs
+//
+// Must be included in exactly one C++ compilation unit.
+//
+
+#ifndef _EZPWD_SERIALIZE_DEFINITIONS
+#define _EZPWD_SERIALIZE_DEFINITIONS
+
+#include "serialize"
+
+//
+// base<16> tables for RFC4864 standard
+//
+const constexpr std::array<char,16>
+ ezpwd::serialize::hex<16>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::hex<16>::decoder;
+
+//
+// base<32> tables for RFC4864 standard, and the Hex32, EZPWD and Crockford codecs
+//
+const constexpr std::array<char,32>
+ ezpwd::serialize::hex<32>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::hex<32>::decoder;
+const constexpr std::array<char,32>
+ ezpwd::serialize::standard<32>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::standard<32>::decoder;
+const constexpr std::array<char,32>
+ ezpwd::serialize::ezpwd<32>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::ezpwd<32>::decoder;
+const constexpr std::array<char,32>
+ ezpwd::serialize::crockford<32>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::crockford<32>::decoder;
+
+//
+// base<64> tables for RFC4864 standard (regular and url), and the EZPWD codecs
+//
+const constexpr std::array<char,64>
+ ezpwd::serialize::standard<64>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::standard<64>::decoder;
+const constexpr std::array<char,64>
+ ezpwd::serialize::standard_url<64>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::standard_url<64>::decoder;
+const constexpr std::array<char,64>
+ ezpwd::serialize::ezpwd<64>::encoder;
+const constexpr std::array<char,127>
+ ezpwd::serialize::ezpwd<64>::decoder;
+
+#endif // _EZPWD_SERIALIZE_DEFINITIONS
diff --git a/op25/gr-op25_repeater/lib/ezpwd/timeofday b/op25/gr-op25_repeater/lib/ezpwd/timeofday
new file mode 100644
index 0000000..3016138
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/ezpwd/timeofday
@@ -0,0 +1,73 @@
+#ifndef _EZPWD_TIMEOFDAY
+#define _EZPWD_TIMEOFDAY
+
+#include <sys/time.h>
+
+//
+// ezpwd::timeofday -- Return current time.
+// ezpwd::epoch -- The UNIX epoch.
+// ezpwd::seconds -- convert timeval to a real-valued seconds
+// <timeval> < <timeval>-- less-than comparison on timevals
+// <timeval> - <timeval>-- difference on timevals
+//
+namespace ezpwd {
+ inline
+ timeval timeofday()
+ {
+ timeval tv;
+ ::gettimeofday( &tv, NULL );
+ return tv;
+ }
+
+ timeval epoch()
+ {
+ timeval tv;
+ tv.tv_sec = 0;
+ tv.tv_usec = 0;
+ return tv;
+ }
+
+ inline
+ double seconds( const timeval &rhs )
+ {
+ return rhs.tv_usec / 1000000.0 + rhs.tv_sec;
+ }
+} // namespace ezpwd
+
+inline
+bool operator<(
+ const timeval &lhs,
+ const timeval &rhs )
+{
+ return ( lhs.tv_sec < rhs.tv_sec
+ || (( lhs.tv_sec == rhs.tv_sec )
+ && ( lhs.tv_usec < rhs.tv_usec )));
+}
+
+inline
+timeval operator-(
+ const timeval &lhs,
+ timeval rhs ) // copy; adjusted...
+{
+ timeval result;
+ if ( lhs < rhs ) {
+ result = ezpwd::epoch();
+ } else {
+ // See http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
+ if ( lhs.tv_usec < rhs.tv_usec ) {
+ int sec = ( rhs.tv_usec - lhs.tv_usec ) / 1000000 + 1;
+ rhs.tv_usec -= sec * 1000000;
+ rhs.tv_sec += sec;
+ }
+ if ( lhs.tv_usec - rhs.tv_usec > 1000000 ) {
+ int sec = ( lhs.tv_usec - rhs.tv_usec ) / 1000000;
+ rhs.tv_usec += sec * 1000000;
+ rhs.tv_sec -= sec;
+ }
+ result.tv_sec = lhs.tv_sec - rhs.tv_sec;
+ result.tv_usec = lhs.tv_usec - rhs.tv_usec;
+ }
+ return result;
+}
+
+#endif // _EZPWD_TIMEOFDAY
diff --git a/op25/gr-op25_repeater/lib/frame_assembler_impl.cc b/op25/gr-op25_repeater/lib/frame_assembler_impl.cc
new file mode 100644
index 0000000..8f0f3ca
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/frame_assembler_impl.cc
@@ -0,0 +1,107 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gnuradio/io_signature.h>
+#include "frame_assembler_impl.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <errno.h>
+#include <vector>
+#include <sys/time.h>
+
+namespace gr {
+ namespace op25_repeater {
+
+ void frame_assembler_impl::set_xormask(const char*p) {
+ }
+
+ void frame_assembler_impl::set_nac(int nac) {
+ }
+
+ void frame_assembler_impl::set_slotid(int slotid) {
+ }
+
+ void frame_assembler_impl::insert_whitelist(int grpaddr) {
+ d_sync.insert_whitelist(grpaddr);
+ }
+ void frame_assembler_impl::insert_blacklist(int grpaddr) {
+ d_sync.insert_blacklist(grpaddr);
+ }
+
+ frame_assembler::sptr
+ frame_assembler::make(const char* options, int debug, gr::msg_queue::sptr queue, int msgq_id)
+ {
+ return gnuradio::get_initial_sptr
+ (new frame_assembler_impl(options, debug, queue, msgq_id));
+ }
+
+ /*
+ * The private constructor
+ */
+
+ /*
+ * Our virtual destructor.
+ */
+ frame_assembler_impl::~frame_assembler_impl()
+ {
+ }
+
+static const int MIN_IN = 1; // mininum number of input streams
+static const int MAX_IN = 1; // maximum number of input streams
+
+/*
+ * The private constructor
+ */
+ frame_assembler_impl::frame_assembler_impl(const char* options, int debug, gr::msg_queue::sptr queue, int msgq_id)
+ : gr::block("frame_assembler",
+ gr::io_signature::make (MIN_IN, MAX_IN, sizeof (char)),
+ gr::io_signature::make (0, 0, 0)),
+ d_msg_queue(queue),
+ d_sync(options, debug, queue, msgq_id),
+ d_msgq_id(msgq_id)
+{
+}
+
+int
+frame_assembler_impl::general_work (int noutput_items,
+ gr_vector_int &ninput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items)
+{
+
+ const uint8_t *in = (const uint8_t *) input_items[0];
+
+ for (int i=0; i<ninput_items[0]; i++)
+ d_sync.rx_sym(in[i]);
+ consume_each(ninput_items[0]);
+ // Tell runtime system how many output items we produced.
+ return 0;
+}
+
+ } /* namespace op25_repeater */
+} /* namespace gr */
diff --git a/op25/gr-op25_repeater/lib/frame_assembler_impl.h b/op25/gr-op25_repeater/lib/frame_assembler_impl.h
new file mode 100644
index 0000000..6080f60
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/frame_assembler_impl.h
@@ -0,0 +1,74 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_IMPL_H
+#define INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_IMPL_H
+
+#include <op25_repeater/frame_assembler.h>
+
+#include <gnuradio/msg_queue.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <deque>
+
+#include "rx_sync.h"
+
+typedef std::deque<uint8_t> dibit_queue;
+
+namespace gr {
+ namespace op25_repeater {
+
+ class frame_assembler_impl : public frame_assembler
+ {
+ private:
+ int d_debug;
+ gr::msg_queue::sptr d_msg_queue;
+ rx_sync d_sync;
+ int d_msgq_id;
+
+ // internal functions
+
+ void queue_msg(int duid);
+ void set_xormask(const char*p) ;
+ void set_nac(int nac) ;
+ void set_slotid(int slotid) ;
+ void insert_whitelist(int grpaddr);
+ void insert_blacklist(int grpaddr);
+
+ public:
+
+ public:
+ frame_assembler_impl(const char* options, int debug, gr::msg_queue::sptr queue, int msgq_id);
+ ~frame_assembler_impl();
+
+ // Where all the action really happens
+
+ int general_work(int noutput_items,
+ gr_vector_int &ninput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items);
+ };
+
+ } // namespace op25_repeater
+} // namespace gr
+
+#endif /* INCLUDED_OP25_REPEATER_FRAME_ASSEMBLER_IMPL_H */
diff --git a/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.cc b/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.cc
index 766652d..dc0fe4a 100644
--- a/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.cc
+++ b/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.cc
@@ -35,8 +35,10 @@
#include <stdexcept>
#include <cstdio>
#include <string.h>
+#include <sys/time.h>
#include "p25_frame.h"
+#include "p25p2_framer.h"
#include "check_frame_sync.h"
#define ENABLE_COSTAS_CQPSK_HACK 0
@@ -47,6 +49,10 @@ static const float M_TWOPI = 2 * M_PI;
static const gr_complex PT_45 = gr_expj( M_PI / 4.0 );
static const int NUM_COMPLEX=100;
+static const int FM_COUNT=500; // number of samples per measurement frame
+
+static const int N_FILES = 4; // number of filenames to cycle through
+
namespace gr {
namespace op25_repeater {
@@ -56,10 +62,103 @@ static inline std::complex<float> sgn(std::complex<float>c) {
return c/abs(c);
}
+#define UPDATE_COUNT(c) if (d_event_type == c) { \
+ d_event_count ++; \
+ } else { \
+ d_event_count = 1; \
+ d_event_type = c; \
+ }
+
+static int tuning_score(gr_complex buf[], int bufp, int bufl, int sync_l, int sps) {
+ int n_scan_samples = sps * 6;
+ float atan_prev = 0;
+ float score = 0;
+ int p = bufp - (n_scan_samples + 1);
+ if (p < 0)
+ p += bufl;
+ int n_tests = 0;
+ int n_plus = 0;
+ // a series of N consecutive samples treated as N-1 connected line segments
+ // is evaluated to find the angle, in radians, at the junction of each pair
+ // of lines.
+ // when a frequency tuning error is present the algebraic sum of the angles
+ // will contain a significant positive or negative bias.
+ for (int i = 0; i < n_scan_samples; i++) {
+ gr_complex sample1 = buf[ (p+i) % bufl ];
+ gr_complex sample2 = buf[ (p+i+1) % bufl ];
+ gr_complex diff = sample2 - sample1;
+ float atan = gr::fast_atan2f(diff.real(), diff.imag());
+ if (i == 0) {
+ atan_prev = atan;
+ continue;
+ }
+ float atan_diff = atan - atan_prev;
+ if (atan_diff > M_PI)
+ atan_diff -= M_TWOPI;
+ if (atan_diff < -M_PI)
+ atan_diff += M_TWOPI;
+ atan_prev = atan;
+ score += atan_diff;
+ n_tests += 1;
+ if (atan_diff > 0)
+ n_plus += 1;
+ }
+ float f1 = (score > 0) ? n_plus : n_tests - n_plus;
+ float f2 = n_tests;
+ int pct = (int) (100*f1/f2 + 0.5);
+ if (score < 0)
+ pct *= -1;
+ return pct;
+}
+
+static inline bool is_future(struct timeval*t) {
+ struct timeval current_t;
+ gettimeofday(&current_t,0);
+ if (t->tv_sec > current_t.tv_sec)
+ return true;
+ else if (t->tv_sec < current_t.tv_sec)
+ return false;
+ else if (t->tv_usec > current_t.tv_usec)
+ return true;
+ else
+ return false;
+}
+
+void gardner_costas_cc_impl::dump_samples(int error_amt) {
+ // TODO = disk I/O from inside a gr flow graph block work function (tsk tsk)
+ char tmp_filename[256];
+ char filename[256];
+ char line[64];
+ FILE *fp1;
+ if (!d_enable_sync_plot)
+ return;
+ if (d_prev_sample == NULL)
+ return;
+ if (is_future(&d_next_sample_time))
+ return;
+ gettimeofday(&d_next_sample_time,0);
+ d_next_sample_time.tv_sec += 1;
+ sprintf(filename, "sample-%ld-%d.dat", unique_id(), d_sample_file_id);
+ d_sample_file_id ++;
+ d_sample_file_id = d_sample_file_id % N_FILES;
+ sprintf(line, "%u %d %d %d\n", d_prev_sample_p, (d_is_tdma) ? 2 : 1, (int) (d_omega + 0.5), error_amt);
+ strcpy(tmp_filename, filename);
+ strcat(tmp_filename, ".tmp");
+ fp1 = fopen(tmp_filename, "wb");
+ if (!fp1)
+ return;
+ fwrite (line, 1, strlen(line), fp1);
+ fwrite (d_prev_sample, 1, d_n_prev_sample * sizeof(gr_complex), fp1);
+ fclose(fp1);
+
+ rename(tmp_filename, filename);
+}
+
uint8_t gardner_costas_cc_impl::slicer(float sym) {
uint8_t dibit = 0;
+ int sps = (int) (d_omega + 0.5);
static const float PI_4 = M_PI / 4.0;
- static const float d_slice_levels[4] = {-2.0*PI_4, 0.0*PI_4, 2.0*PI_4, 4.0*PI_4};
+ static const float d_slice_levels[4] = {(float)-2.0*PI_4, (float)0.0*PI_4, (float)2.0*PI_4, (float)4.0*PI_4};
if (d_slice_levels[3] < 0) {
dibit = 1;
if (d_slice_levels[3] <= sym && sym < d_slice_levels[0])
@@ -78,16 +177,90 @@ uint8_t gardner_costas_cc_impl::slicer(float sym) {
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ P25_FRAME_SYNC_MAGIC, 0, 48)) {
// fprintf(stderr, "P25P1 Framing detect\n");
+ UPDATE_COUNT(' ')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(0);
+ }
+ else if(check_frame_sync((nid_accum & P25P2_FRAME_SYNC_MASK) ^ P25P2_FRAME_SYNC_MAGIC, 0, 40)) {
+// fprintf(stderr, "P25P2 Framing detect\n");
+ UPDATE_COUNT(' ')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(0);
+ }
+ if (d_is_tdma) {
+ if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0x000104015155LL, 0, 40)) {
+ fprintf(stderr, "TDMA: channel %d tuning error -1200\n", -1);
+ UPDATE_COUNT('-')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(-1200);
}
+ else if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xfefbfeaeaaLL, 0, 40)) {
+ fprintf(stderr, "TDMA: channel %d tuning error +1200\n", -1);
+ UPDATE_COUNT('+')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(1200);
+ }
+ else if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xa8a2a80800LL, 0, 40)) {
+ int score = tuning_score(d_prev_sample, d_prev_sample_p, d_n_prev_sample, 20, sps);
+ int error = 24;
+ if (score == -100) {
+ error = 2400;
+ UPDATE_COUNT('>')
+ fprintf(stderr, "TDMA: channel %d tuning error %d\n", -1, error);
+ } else if (score == 100) {
+ error = -2400;
+ UPDATE_COUNT('<')
+ fprintf(stderr, "TDMA: channel %d tuning error %d\n", -1, error);
+ } else {
+ fprintf(stderr, "TDMA: channel %d tuning error +/-2400, confidence %d\n", -1, score);
+ }
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(error);
+ }
+ } else {
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0x001050551155LL, 0, 48)) {
- fprintf(stderr, "tuning error -1200\n");
+// fprintf(stderr, "tuning error -1200\n");
+ UPDATE_COUNT('-')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(-1200);
}
- if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xFFEFAFAAEEAALL, 0, 48)) {
- fprintf(stderr, "tuning error +1200\n");
+ else if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xFFEFAFAAEEAALL, 0, 48)) {
+// fprintf(stderr, "tuning error +1200\n");
+ UPDATE_COUNT('+')
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(1200);
}
- if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xAA8A0A008800LL, 0, 48)) {
- fprintf(stderr, "tuning error +/- 2400\n");
+ else if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xAA8A0A008800LL, 0, 48)) {
+ int score = tuning_score(d_prev_sample, d_prev_sample_p, d_n_prev_sample, 24, sps);
+ int error = 24;
+ if (score == -100) {
+ error = 2400;
+ UPDATE_COUNT('>')
+ fprintf(stderr, "channel %d block id %ld tuning error %d\n", -1, (long)unique_id(), error);
+ } else if (score == 100) {
+ error = -2400;
+ UPDATE_COUNT('<')
+ fprintf(stderr, "channel %d block id %ld tuning error %d\n", -1, (long)unique_id(), error);
+ } else {
+ fprintf(stderr, "channel %d block id %ld tuning error +/-2400, confidence %d\n", -1, (long)unique_id(), score);
+ }
+ d_sync_valid_until = d_sample_count + 2400 * sps;
+ dump_samples(error);
}
+ }
+ if (d_event_type == ' ' || d_event_count < 5) {
+ d_update_request = 0;
+ } else {
+ if (d_event_type == '+' && d_fm > 0)
+ d_update_request = -1;
+ else if (d_event_type == '-' && d_fm < 0)
+ d_update_request = 1;
+ else if (d_event_type == '<')
+ d_update_request = -2;
+ else if (d_event_type == '>')
+ d_update_request = 2;
+ else d_update_request = 0;
+ }
return dibit;
}
@@ -117,11 +290,20 @@ uint8_t gardner_costas_cc_impl::slicer(float sym) {
d_alpha(alpha), d_beta(beta),
d_interp_counter(0),
d_theta(M_PI / 4.0), d_phase(0), d_freq(0), d_max_freq(max_freq),
- nid_accum(0)
+ nid_accum(0), d_prev(0),
+ d_event_count(0), d_event_type(' '),
+ d_symbol_seq(samples_per_symbol * 4800),
+ d_update_request(0),
+ d_fm(0), d_fm_accum(0), d_fm_count(0), d_muted(false), d_is_tdma(false),
+ d_enable_sync_plot(false),
+ d_prev_sample(NULL), d_n_prev_sample(0), d_prev_sample_p(0),
+ d_sample_file_id(0),
+ d_sample_count(0), d_sync_valid_until(0)
{
set_omega(samples_per_symbol);
set_relative_rate (1.0 / d_omega);
set_history(d_twice_sps); // ensure extra input is available
+ gettimeofday(&d_next_sample_time, 0);
}
/*
@@ -129,6 +311,10 @@ uint8_t gardner_costas_cc_impl::slicer(float sym) {
*/
gardner_costas_cc_impl::~gardner_costas_cc_impl()
{
+ if (d_prev_sample != NULL) {
+ free(d_prev_sample);
+ d_prev_sample = NULL;
+ }
delete [] d_dl;
delete d_interp;
}
@@ -146,6 +332,17 @@ void gardner_costas_cc_impl::set_omega (float omega) {
memset(d_dl, 0, NUM_COMPLEX * sizeof(gr_complex));
}
+float gardner_costas_cc_impl::get_freq_error (void) {
+ if (!recent_sync())
+ return 0.0;
+ return (d_freq);
+}
+
+int gardner_costas_cc_impl::get_error_band (void) {
+ if (!recent_sync())
+ return 0;
+ return (d_update_request);
+}
void
gardner_costas_cc_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required)
@@ -190,21 +387,20 @@ gardner_costas_cc_impl::phase_error_tracking(gr_complex sample)
phase_error = phase_error_detector_qpsk(sample);
d_freq += d_beta*phase_error*abs(sample); // adjust frequency based on error
- d_phase += d_freq + d_alpha*phase_error*abs(sample); // adjust phase based on error
+ d_phase += d_alpha*phase_error*abs(sample); // adjust phase based on error
- // Make sure we stay within +-2pi
- while(d_phase > M_TWOPI)
+ // Make sure we stay within +-pi
+ while(d_phase > M_PI)
d_phase -= M_TWOPI;
- while(d_phase < -M_TWOPI)
+ while(d_phase < -M_PI)
d_phase += M_TWOPI;
// Limit the frequency range
d_freq = gr::branchless_clip(d_freq, d_max_freq);
#if VERBOSE_COSTAS
- printf("cl: phase_error: %f phase: %f freq: %f sample: %f+j%f constellation: %f+j%f\n",
- phase_error, d_phase, d_freq, sample.real(), sample.imag(),
- d_constellation[d_current_const_point].real(), d_constellation[d_current_const_point].imag());
+ fprintf(stderr, "COSTAS\t%f\t%f\t%f\t%f+j%f\n",
+ phase_error, d_phase, d_freq, sample.real(), sample.imag());
#endif
}
@@ -219,6 +415,14 @@ gardner_costas_cc_impl::general_work (int noutput_items,
int i=0, o=0;
gr_complex symbol, sample, nco;
+ gr_complex interp_samp, interp_samp_mid, diffdec;
+ float error_real, error_imag, symbol_error;
+
+ if (d_prev_sample == NULL) {
+ d_n_prev_sample = (int) (d_omega + 0.5); // sps
+ d_n_prev_sample *= (d_is_tdma) ? 32 : 25; // enough for p25p1 or p25p2 sync
+ d_prev_sample = (gr_complex *) calloc(d_n_prev_sample, sizeof(gr_complex));
+ }
while((o < noutput_items) && (i < ninput_items[0])) {
while((d_mu > 1.0) && (i < ninput_items[0])) {
@@ -226,24 +430,43 @@ gardner_costas_cc_impl::general_work (int noutput_items,
d_phase += d_freq;
// Keep phase clamped and not walk to infinity
- while(d_phase > M_TWOPI)
+ while(d_phase > M_PI)
d_phase -= M_TWOPI;
- while(d_phase < -M_TWOPI)
+ while(d_phase < -M_PI)
d_phase += M_TWOPI;
nco = gr_expj(d_phase+d_theta); // get the NCO value for derotating the curr
symbol = in[i];
sample = nco*symbol; // get the downconverted symbol
+ if (d_enable_sync_plot && d_prev_sample != NULL) {
+ d_prev_sample[d_prev_sample_p] = sample;
+ d_prev_sample_p ++;
+ d_prev_sample_p %= d_n_prev_sample;
+ }
+
d_dl[d_dl_index] = sample;
d_dl[d_dl_index + d_twice_sps] = sample;
d_dl_index ++;
d_dl_index = d_dl_index % d_twice_sps;
i++;
+ d_sample_count++;
+ gr_complex df = symbol * conj(d_prev);
+ float fmd = atan2f(df.imag(), df.real());
+ d_fm_accum += fmd;
+ d_fm_count ++;
+ if (d_fm_count % FM_COUNT == 0) {
+ d_fm = d_fm_accum / FM_COUNT;
+ d_fm_accum = 0;
+ }
+ d_prev = symbol;
}
if(i < ninput_items[0]) {
+ // to mitigate tracking drift in the event of no input signal
+ // skip tracking on muted channel
+ if (!d_muted) {
float half_omega = d_omega / 2.0;
int half_sps = (int) floorf(half_omega);
float half_mu = d_mu + half_omega - (float) half_sps;
@@ -255,18 +478,19 @@ gardner_costas_cc_impl::general_work (int noutput_items,
// half_mu the fractional part, of the halfway mark.
// locate two points, separated by half of one symbol time
// interp_samp is (we hope) at the optimum sampling point
- gr_complex interp_samp_mid = d_interp->interpolate(&d_dl[ d_dl_index ], d_mu);
- gr_complex interp_samp = d_interp->interpolate(&d_dl[ d_dl_index + half_sps], half_mu);
-
- float error_real = (d_last_sample.real() - interp_samp.real()) * interp_samp_mid.real();
- float error_imag = (d_last_sample.imag() - interp_samp.imag()) * interp_samp_mid.imag();
- gr_complex diffdec = interp_samp * conj(d_last_sample);
- (void)slicer(std::arg(diffdec));
+ interp_samp_mid = d_interp->interpolate(&d_dl[ d_dl_index ], d_mu);
+ interp_samp = d_interp->interpolate(&d_dl[ d_dl_index + half_sps], half_mu);
+
+ error_real = (d_last_sample.real() - interp_samp.real()) * interp_samp_mid.real();
+ error_imag = (d_last_sample.imag() - interp_samp.imag()) * interp_samp_mid.imag();
+ diffdec = interp_samp * conj(d_last_sample);
+ if (!d_muted) // if muted, assume channel idle (suspend tuning error checks)
+ (void)slicer(std::arg(diffdec));
d_last_sample = interp_samp; // save for next time
#if 1
- float symbol_error = error_real + error_imag; // Gardner loop error
+ symbol_error = error_real + error_imag; // Gardner loop error
#else
- float symbol_error = ((sgn(interp_samp) - sgn(d_last_sample)) * conj(interp_samp_mid)).real();
+ symbol_error = ((sgn(interp_samp) - sgn(d_last_sample)) * conj(interp_samp_mid)).real();
#endif
if (std::isnan(symbol_error)) symbol_error = 0.0;
if (symbol_error < -1.0) symbol_error = -1.0;
@@ -275,13 +499,21 @@ gardner_costas_cc_impl::general_work (int noutput_items,
d_omega = d_omega + d_gain_omega * symbol_error * abs(interp_samp); // update omega based on loop error
d_omega = d_omega_mid + gr::branchless_clip(d_omega-d_omega_mid, d_omega_rel); // make sure we don't walk away
#if VERBOSE_GARDNER
- printf("%f\t%f\t%f\t%f\t%f\n", symbol_error, d_mu, d_omega, error_real, error_imag);
+ fprintf(stderr, "%f\t%f\t%f\t%f\t%f\n", symbol_error, d_mu, d_omega, error_real, error_imag);
#endif
+ } else {
+ symbol_error = 0;
+ } /* end of if (!d_muted) */
d_mu += d_omega + d_gain_mu * symbol_error; // update mu based on loop error
+ if (!d_muted) {
phase_error_tracking(diffdec * PT_45);
-
- out[o++] = interp_samp;
+ } /* end of if (!d_muted) */
+
+ if (d_muted)
+ out[o++] = 0.0;
+ else
+ out[o++] = interp_samp;
}
}
diff --git a/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.h b/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.h
index 7fc8eb7..aa9e8b7 100644
--- a/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.h
+++ b/op25/gr-op25_repeater/lib/gardner_costas_cc_impl.h
@@ -66,7 +66,19 @@ namespace gr {
void set_verbose (bool verbose) { d_verbose = verbose; }
//! Sets value of omega and its min and max values
- void set_omega (float omega);
+ inline void set_omega (float omega);
+ inline float get_freq_error(void);
+ inline int get_error_band(void);
+ inline void set_muted(bool v) {
+ if (v == false && d_muted == true) {
+ d_event_count = 0; // mute state change from muted to unmuted
+ }
+ d_muted = v;
+ }
+ inline bool is_muted(void) { return d_muted; }
+ inline void set_tdma(bool v) { d_is_tdma = v; }
+ inline bool is_tdma(void) { return d_is_tdma; }
+ inline void enable_sync_plot(bool v) { d_enable_sync_plot = v; }
protected:
bool input_sample0(gr_complex, gr_complex& outp);
@@ -100,8 +112,32 @@ protected:
uint64_t nid_accum;
+ gr_complex d_prev;
+ int d_event_count;
+ char d_event_type;
+ int d_symbol_seq;
+ int d_update_request;
+ float d_fm;
+ float d_fm_accum;
+ int d_fm_count;
+ bool d_muted;
+ bool d_is_tdma;
+ bool d_enable_sync_plot;
+
+ gr_complex *d_prev_sample;
+ unsigned int d_n_prev_sample;
+ unsigned int d_prev_sample_p;
+
+ struct timeval d_next_sample_time;
+ int d_sample_file_id;
+
+ unsigned int d_sample_count;
+ unsigned int d_sync_valid_until;
+
float phase_error_detector_qpsk(gr_complex sample);
void phase_error_tracking(gr_complex sample);
+ void dump_samples(int);
+ bool recent_sync(void) { return d_sample_count <= d_sync_valid_until; }
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/lib/log_ts.h b/op25/gr-op25_repeater/lib/log_ts.h
new file mode 100644
index 0000000..fbd6bb3
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/log_ts.h
@@ -0,0 +1,44 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2018 Graham J. Norbury
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef INCLUDED_LOG_TS_H
+#define INCLUDED_LOG_TS_H
+
+#include <sys/time.h>
+
+class log_ts
+{
+private:
+ struct timeval curr_time;
+ char log_ts[20];
+
+public:
+ inline const char* get()
+ {
+ if (gettimeofday(&curr_time, 0) == 0)
+ sprintf(log_ts, "%010lu.%06lu", curr_time.tv_sec, curr_time.tv_usec);
+ else
+ log_ts[0] = 0;
+
+ return log_ts;
+ }
+};
+
+#endif // INCLUDED_LOG_TS_H
diff --git a/op25/gr-op25_repeater/lib/mbelib.c b/op25/gr-op25_repeater/lib/mbelib.c
index a9ed3bf..9581d5b 100644
--- a/op25/gr-op25_repeater/lib/mbelib.c
+++ b/op25/gr-op25_repeater/lib/mbelib.c
@@ -19,6 +19,18 @@
#include "mbelib.h"
#include "mbelib_const.h"
+#ifndef M_PI
+# define M_PI 3.14159265358979323846 /* pi */
+#endif
+
+#ifndef M_E
+# define M_E 2.7182818284590452354 /* e */
+#endif
+
+#ifndef M_SQRT2
+# define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
+#endif
+
void
mbe_printVersion (char *str)
{
diff --git a/op25/gr-op25_repeater/lib/nxdn.cc b/op25/gr-op25_repeater/lib/nxdn.cc
new file mode 100644
index 0000000..2e4a85d
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/nxdn.cc
@@ -0,0 +1,354 @@
+/* -*- c++ -*- */
+/*
+ * NXDN Encoder/Decoder (C) Copyright 2019 Max H. Parke KA1RBI
+ *
+ * This file is part of OP25
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <assert.h>
+#include "bit_utils.h"
+
+#include "nxdn.h"
+#include "nxdn_const.h"
+
+static const uint8_t scramble_t[] = {
+ 2, 5, 6, 7, 10, 12, 14, 16, 17, 22, 23, 25, 26, 27, 28, 30, 33, 34, 36, 37, 38, 41, 45, 47,
+ 52, 54, 56, 57, 59, 62, 63, 64, 65, 66, 67, 69, 70, 73, 76, 79, 81, 82, 84, 85, 86, 87, 88,
+ 89, 92, 95, 96, 98, 100, 103, 104, 107, 108, 116, 117, 121, 122, 125, 127, 131, 132, 134,
+ 137, 139, 140, 141, 142, 143, 144, 145, 147, 151, 153, 154, 158, 159, 160, 162, 164, 165,
+ 168, 170, 171, 174, 175, 176, 177, 181};
+
+static const int PARITY[] = {0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
+
+static inline uint16_t crc16(const uint8_t buf[], int len, uint32_t crc) {
+ uint32_t poly = (1<<12) + (1<<5) + (1<<0);
+ for(int i=0; i<len; i++) {
+ uint8_t bit = buf[i] & 1;
+ crc = ((crc << 1) | bit) & 0x1ffff;
+ if (crc & 0x10000)
+ crc = (crc & 0xffff) ^ poly;
+ }
+ crc = crc ^ 0xffff;
+ return crc & 0xffff;
+}
+
+static uint16_t crc15(const uint8_t buf[], int len) {
+ uint8_t s[15];
+ uint8_t a;
+ for (int i=0;i<15;i++)
+ s[i] = 1;
+ for (int i=0;i<len;i++) {
+ a = buf[i] ^ s[0];
+ s[0] = a ^ s[1];
+ s[1] = s[2];
+ s[2] = s[3];
+ s[3] = a ^ s[4];
+ s[4] = a ^ s[5];
+ s[5] = s[6];
+ s[6] = s[7];
+ s[7] = a ^ s[8];
+ s[8] = a ^ s[9];
+ s[9] = s[10];
+ s[10] = s[11];
+ s[11] = s[12];
+ s[12] = a ^ s[13];
+ s[13] = s[14];
+ s[14] = a;
+ }
+ return load_i(s, 15);
+}
+
+static uint16_t crc16(const uint8_t buf[], int len) {
+ int crc = 0xc3ee;
+ int poly = (1<<12) + (1<<5) + 1;
+ for (int i=0;i<len;i++) {
+ crc = ((crc << 1) | buf[i]) & 0x1ffff;
+ if(crc & 0x10000)
+ crc = (crc & 0xffff) ^ poly;
+ }
+ crc = crc ^ 0xffff;
+ return crc & 0xffff;
+}
+
+static uint8_t crc6(const uint8_t buf[], int len) {
+ uint8_t s[6];
+ uint8_t a;
+ for (int i=0;i<6;i++)
+ s[i] = 1;
+ for (int i=0;i<len;i++) {
+ a = buf[i] ^ s[0];
+ s[0] = a ^ s[1];
+ s[1] = s[2];
+ s[2] = s[3];
+ s[3] = a ^ s[4];
+ s[4] = a ^ s[5];
+ s[5] = a;
+ }
+ return load_i(s, 6);
+}
+
+static uint16_t crc12(const uint8_t buf[], int len) {
+ uint8_t s[12];
+ uint8_t a;
+ for (int i=0;i<12;i++)
+ s[i] = 1;
+ for (int i=0;i<len;i++) {
+ a = buf[i] ^ s[0];
+ s[0] = a ^ s[1];
+ s[1] = s[2];
+ s[2] = s[3];
+ s[3] = s[4];
+ s[4] = s[5];
+ s[5] = s[6];
+ s[6] = s[7];
+ s[7] = s[8];
+ s[8] = a ^ s[9];
+ s[9] = a ^ s[10];
+ s[10] = a ^ s[11];
+ s[11] = a;
+ }
+ return load_i(s, 12);
+}
+
+// trellis_1_2 encode: source is in bits, result in bits
+static inline void trellis_encode(uint8_t result[], const uint8_t source[], int result_len, int reg)
+{
+ for (int i=0; i<result_len; i+=2) {
+ reg = (reg << 1) | source[i>>1];
+ result[i] = PARITY[reg & 0x19];
+ result[i+1] = PARITY[reg & 0x17];
+ }
+}
+
+// simplified trellis 2:1 decode; source and result in bits
+// assumes that encoding was done with NTEST trailing zero bits
+// result_len should be set to the actual number of data bits
+// in the original unencoded message (excl. these trailing bits)
+static inline void trellis_decode(uint8_t result[], const uint8_t source[], int result_len)
+{
+ int reg = 0;
+ int min_d;
+ int min_bt;
+ static const int NTEST = 4;
+ static const int NTESTC = 1 << NTEST;
+ uint8_t bt[NTEST];
+ uint8_t tt[NTEST*2];
+ int dstats[4];
+ int sum;
+ for (int p=0; p < 4; p++)
+ dstats[p] = 0;
+ for (int p=0; p < result_len; p++) {
+ for (int i=0; i<NTESTC; i++) {
+ bt[0] = (i&8)>>3;
+ bt[1] = (i&4)>>2;
+ bt[2] = (i&2)>>1;
+ bt[3] = (i&1);
+ trellis_encode(tt, bt, NTEST*2, reg);
+ sum=0;
+ for (int j=0; j<NTEST*2; j++) {
+ sum += tt[j] ^ source[p*2+j];
+ }
+ if (i == 0 || sum < min_d) {
+ min_d = sum;
+ min_bt = bt[0];
+ }
+ }
+ result[p] = min_bt;
+ reg = (reg << 1) | min_bt;
+ dstats[(min_d > 3) ? 3 : min_d] += 1;
+ }
+ // fprintf (stderr, "stats\t%d %d %d %d\n", dstats[0], dstats[1], dstats[2], dstats[3]);
+}
+
+void nxdn_descramble(uint8_t dibits[], int len) {
+ for (int i=0; i<sizeof(scramble_t); i++) {
+ if (scramble_t[i] >= len)
+ break;
+ dibits[scramble_t[i]] ^= 0x2; // invert sign of scrambled dibits
+ }
+}
+
+static inline void cfill(uint8_t result[], const uint8_t src[], int len) {
+ for (int i=0; i<len; i++)
+ result[i] = load_i(src+i*8, 8);
+}
+
+void nxdn_decode_cac(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len) {
+ uint8_t cacbits[300];
+ uint8_t deperm[300];
+ uint8_t depunc[350];
+ uint8_t decode[171];
+ int id=0;
+ uint16_t crc;
+
+ assert (len == 150);
+ if (answer_len < 19) {
+ answer_len = -1;
+ return;
+ }
+ dibits_to_bits(cacbits, dibits, 150);
+ for (int i=0; i<300; i++) {
+ deperm[PERM_12_25[i]] = cacbits[i];
+ }
+ for (int i=0; i<25; i++) {
+ depunc[id++] = deperm[i*12];
+ depunc[id++] = deperm[i*12+1];
+ depunc[id++] = deperm[i*12+2];
+ depunc[id++] = 0;
+ depunc[id++] = deperm[i*12+3];
+ depunc[id++] = deperm[i*12+4];
+ depunc[id++] = deperm[i*12+5];
+ depunc[id++] = deperm[i*12+6];
+ depunc[id++] = deperm[i*12+7];
+ depunc[id++] = deperm[i*12+8];
+ depunc[id++] = deperm[i*12+9];
+ depunc[id++] = 0;
+ depunc[id++] = deperm[i*12+10];
+ depunc[id++] = deperm[i*12+11];
+ }
+ trellis_decode(decode, depunc, 171);
+ crc = crc16(decode, 171, 0xc3ee);
+ if (crc != 0) {
+ answer_len = -1;
+ return; // ignore msg if crc failed
+ }
+ // result length after crc and 3 zero bits removed = 152 = 19 bytes
+ cfill(answer, decode, 19);
+ answer_len = 19; /* return 19 bytes */
+}
+
+void nxdn_decode_facch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len) {
+ uint8_t bits[144];
+ uint8_t deperm[144];
+ uint8_t depunc[192];
+ uint8_t trellis_buf[92];
+ uint16_t crc;
+ uint16_t crc2;
+ int out;
+ char buf[128];
+ assert (len == 72);
+ if (answer_len < 10) {
+ answer_len = -1;
+ return;
+ }
+ dibits_to_bits(bits, dibits, 72);
+ for (int i=0; i<144; i++)
+ deperm[PERM_16_9[i]] = bits[i];
+ out = 0;
+ for (int i=0; i<144; i+=3) {
+ depunc[out++] = deperm[i+0];
+ depunc[out++] = 0;
+ depunc[out++] = deperm[i+1];
+ depunc[out++] = deperm[i+2];
+ }
+ trellis_decode(trellis_buf, depunc, 92);
+ crc = crc12(trellis_buf, 92);
+ if (crc) {
+ answer_len = -1;
+ return;
+ }
+ cfill(answer, trellis_buf, 10);
+ answer_len = 10;
+}
+
+void nxdn_decode_facch2_udch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len) {
+ uint8_t bits[348];
+ uint8_t deperm[348];
+ uint8_t depunc[406];
+ uint8_t trellis_buf[199];
+ int id=0;
+ uint16_t crc;
+ assert (len == 174);
+ if (answer_len < 23) {
+ answer_len = -1;
+ return;
+ }
+ dibits_to_bits(bits, dibits, 174);
+ for (int i=0; i<348; i++) {
+ deperm[PERM_12_29[i]] = bits[i];
+ }
+ for (int i=0; i<29; i++) {
+ depunc[id++] = deperm[i*12];
+ depunc[id++] = deperm[i*12+1];
+ depunc[id++] = deperm[i*12+2];
+ depunc[id++] = 0;
+ depunc[id++] = deperm[i*12+3];
+ depunc[id++] = deperm[i*12+4];
+ depunc[id++] = deperm[i*12+5];
+ depunc[id++] = deperm[i*12+6];
+ depunc[id++] = deperm[i*12+7];
+ depunc[id++] = deperm[i*12+8];
+ depunc[id++] = deperm[i*12+9];
+ depunc[id++] = 0;
+ depunc[id++] = deperm[i*12+10];
+ depunc[id++] = deperm[i*12+11];
+ }
+ trellis_decode(trellis_buf, depunc, 199);
+ crc = crc15(trellis_buf, 199);
+ if (crc != 0) {
+ answer_len = -1;
+ return; // ignore msg if crc failed
+ }
+ // pack 184 bits in 23 bytes
+ cfill(answer, trellis_buf, 23);
+ answer_len = 23;
+}
+
+void nxdn_decode_sacch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len) {
+ // global NEXT_S, SACCH
+ uint8_t bits[60];
+ uint8_t deperm[60];
+ uint8_t depunc[72];
+ uint8_t trellis_buf[32];
+ int o=0;
+ uint8_t crc;
+
+ assert (len == 30);
+ if (answer_len < 26) {
+ answer_len = -1;
+ return;
+ }
+ dibits_to_bits(bits, dibits, 30);
+ for (int i=0; i<60; i++)
+ deperm[PERM_12_5[i]] = bits[i];
+ for (int p=0; p<60; p+= 10) {
+ depunc[o++] = deperm[p+0];
+ depunc[o++] = deperm[p+1];
+ depunc[o++] = deperm[p+2];
+ depunc[o++] = deperm[p+3];
+ depunc[o++] = deperm[p+4];
+ depunc[o++] = 0;
+ depunc[o++] = deperm[p+5];
+ depunc[o++] = deperm[p+6];
+ depunc[o++] = deperm[p+7];
+ depunc[o++] = deperm[p+8];
+ depunc[o++] = deperm[p+9];
+ depunc[o++] = 0;
+ }
+ trellis_decode(trellis_buf, depunc, 32);
+ crc = crc6(trellis_buf, 32);
+ if (crc) {
+ answer_len = -1;
+ return;
+ }
+ memcpy(answer, trellis_buf, 26);
+ answer_len = 26; // answer is 26 bits, not packed
+}
diff --git a/op25/gr-op25_repeater/lib/nxdn.h b/op25/gr-op25_repeater/lib/nxdn.h
new file mode 100644
index 0000000..47bdecd
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/nxdn.h
@@ -0,0 +1,31 @@
+//
+// NXDN Encoder (C) Copyright 2019 Max H. Parke KA1RBI
+// thx gr-ysf fr_vch_decoder_bb_impl.cc * Copyright 2015 Mathias Weyland *
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+#ifndef INCLUDED_NXDN_H
+#define INCLUDED_NXDN_H
+
+void nxdn_descramble(uint8_t dibits[], int len);
+void nxdn_decode_cac(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len);
+void nxdn_decode_facch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len);
+void nxdn_decode_facch2_udch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len);
+void nxdn_decode_sacch(const uint8_t dibits[], int len, uint8_t answer[], int& answer_len);
+
+#endif /* INCLUDED_NXDN_H */
diff --git a/op25/gr-op25_repeater/lib/nxdn_const.h b/op25/gr-op25_repeater/lib/nxdn_const.h
new file mode 100644
index 0000000..3452410
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/nxdn_const.h
@@ -0,0 +1,98 @@
+//
+// NXDN Encoder (C) Copyright 2019 Max H. Parke KA1RBI
+// thx gr-ysf fr_vch_decoder_bb_impl.cc * Copyright 2015 Mathias Weyland *
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+#ifndef INCLUDED_NXDN_CONST_H
+#define INCLUDED_NXDN_CONST_H
+
+#include <stdint.h>
+
+/* postamble + frame sync (FS) */
+static const uint64_t NXDN_POSTFS_SYNC_MAGIC = 0x5775fdcdf59LL;
+/* frame sync + scrambled rendition of LICH=0x6e (a halfrate voice 4V) */
+static const uint64_t NXDN_CONV_SYNC_MAGIC = 0xcdf59d5dfLL;
+static const uint64_t NXDN_FS6E_SYNC_MAGIC = 0xcdf5975d7LL;
+static const uint64_t NXDN_SYNC_MAGIC = 0xcdf59LL;
+
+static const uint8_t PERM_12_5[] = {
+ 0,12,24,36,48,
+ 1,13,25,37,49,
+ 2,14,26,38,50,
+ 3,15,27,39,51,
+ 4,16,28,40,52,
+ 5,17,29,41,53,
+ 6,18,30,42,54,
+ 7,19,31,43,55,
+ 8,20,32,44,56,
+ 9,21,33,45,57,
+ 10,22,34,46,58,
+ 11,23,35,47,59
+};
+
+static const uint8_t PERM_16_9[] = {
+ 0, 16, 32, 48, 64, 80, 96, 112, 128,
+ 1, 17, 33, 49, 65, 81, 97, 113, 129,
+ 2, 18, 34, 50, 66, 82, 98, 114, 130,
+ 3, 19, 35, 51, 67, 83, 99, 115, 131,
+ 4, 20, 36, 52, 68, 84, 100, 116, 132,
+ 5, 21, 37, 53, 69, 85, 101, 117, 133,
+ 6, 22, 38, 54, 70, 86, 102, 118, 134,
+ 7, 23, 39, 55, 71, 87, 103, 119, 135,
+ 8, 24, 40, 56, 72, 88, 104, 120, 136,
+ 9, 25, 41, 57, 73, 89, 105, 121, 137,
+ 10, 26, 42, 58, 74, 90, 106, 122, 138,
+ 11, 27, 43, 59, 75, 91, 107, 123, 139,
+ 12, 28, 44, 60, 76, 92, 108, 124, 140,
+ 13, 29, 45, 61, 77, 93, 109, 125, 141,
+ 14, 30, 46, 62, 78, 94, 110, 126, 142,
+ 15, 31, 47, 63, 79, 95, 111, 127, 143
+};
+
+static const uint16_t PERM_12_25[] = {
+ 0,12,24,36,48,60,72,84,96,108,120,132,144,156,168,180,192,204,216,228,240,252,264,276,288,
+ 1,13,25,37,49,61,73,85,97,109,121,133,145,157,169,181,193,205,217,229,241,253,265,277,289,
+ 2,14,26,38,50,62,74,86,98,110,122,134,146,158,170,182,194,206,218,230,242,254,266,278,290,
+ 3,15,27,39,51,63,75,87,99,111,123,135,147,159,171,183,195,207,219,231,243,255,267,279,291,
+ 4,16,28,40,52,64,76,88,100,112,124,136,148,160,172,184,196,208,220,232,244,256,268,280,292,
+ 5,17,29,41,53,65,77,89,101,113,125,137,149,161,173,185,197,209,221,233,245,257,269,281,293,
+ 6,18,30,42,54,66,78,90,102,114,126,138,150,162,174,186,198,210,222,234,246,258,270,282,294,
+ 7,19,31,43,55,67,79,91,103,115,127,139,151,163,175,187,199,211,223,235,247,259,271,283,295,
+ 8,20,32,44,56,68,80,92,104,116,128,140,152,164,176,188,200,212,224,236,248,260,272,284,296,
+ 9,21,33,45,57,69,81,93,105,117,129,141,153,165,177,189,201,213,225,237,249,261,273,285,297,
+ 10,22,34,46,58,70,82,94,106,118,130,142,154,166,178,190,202,214,226,238,250,262,274,286,298,
+ 11,23,35,47,59,71,83,95,107,119,131,143,155,167,179,191,203,215,227,239,251,263,275,287,299
+};
+
+static const uint16_t PERM_12_29[] = {
+ 0,12,24,36,48,60,72,84,96,108,120,132,144,156,168,180,192,204,216,228,240,252,264,276,288,300,312,324,336,
+ 1,13,25,37,49,61,73,85,97,109,121,133,145,157,169,181,193,205,217,229,241,253,265,277,289,301,313,325,337,
+ 2,14,26,38,50,62,74,86,98,110,122,134,146,158,170,182,194,206,218,230,242,254,266,278,290,302,314,326,338,
+ 3,15,27,39,51,63,75,87,99,111,123,135,147,159,171,183,195,207,219,231,243,255,267,279,291,303,315,327,339,
+ 4,16,28,40,52,64,76,88,100,112,124,136,148,160,172,184,196,208,220,232,244,256,268,280,292,304,316,328,340,
+ 5,17,29,41,53,65,77,89,101,113,125,137,149,161,173,185,197,209,221,233,245,257,269,281,293,305,317,329,341,
+ 6,18,30,42,54,66,78,90,102,114,126,138,150,162,174,186,198,210,222,234,246,258,270,282,294,306,318,330,342,
+ 7,19,31,43,55,67,79,91,103,115,127,139,151,163,175,187,199,211,223,235,247,259,271,283,295,307,319,331,343,
+ 8,20,32,44,56,68,80,92,104,116,128,140,152,164,176,188,200,212,224,236,248,260,272,284,296,308,320,332,344,
+ 9,21,33,45,57,69,81,93,105,117,129,141,153,165,177,189,201,213,225,237,249,261,273,285,297,309,321,333,345,
+ 10,22,34,46,58,70,82,94,106,118,130,142,154,166,178,190,202,214,226,238,250,262,274,286,298,310,322,334,346,
+ 11,23,35,47,59,71,83,95,107,119,131,143,155,167,179,191,203,215,227,239,251,263,275,287,299,311,323,335,347
+};
+
+#endif /* INCLUDED_NXDN_CONST_H */
diff --git a/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.cc b/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.cc
new file mode 100644
index 0000000..b9b11ca
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.cc
@@ -0,0 +1,373 @@
+/* -*- c++ -*- */
+/*
+ * NXDN Encoder (C) Copyright 2017 Max H. Parke KA1RBI
+ *
+ * This file is part of OP25
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gnuradio/io_signature.h>
+#include "nxdn.h"
+#include "mbelib.h"
+#include "p25p2_vf.h"
+#include "nxdn_tx_sb_impl.h"
+#include "nxdn_const.h"
+#include "op25_imbe_frame.h"
+
+#include <vector>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <assert.h>
+
+static const uint8_t nxdn_fs[] = {3, 0, 3, 1, 3, 3, 1, 1, 2, 1};
+
+#if 0
+static inline void print_result(char title[], const uint8_t r[], int len) {
+ uint8_t buf[256];
+ for (int i=0; i<len; i++){
+ buf[i] = r[i] + '0';
+ }
+ buf[len] = 0;
+ printf("%s: %s\n", title, buf);
+}
+#endif
+
+static inline void store_i(int reg, uint8_t val[], int len) {
+ for (int i=0; i<len; i++){
+ val[i] = (reg >> (len-1-i)) & 1;
+ }
+}
+
+static inline void bits_to_dibits(uint8_t* dest, const uint8_t* src, int n_dibits) {
+ for (int i=0; i<n_dibits; i++) {
+ dest[i] = src[i*2] * 2 + src[i*2+1];
+ }
+}
+
+static inline void bool_to_dibits(uint8_t* dest, const std::vector<bool> src, int n_dibits) {
+ for (int i=0; i<n_dibits; i++) {
+ int l = src[i*2] ? 1 : 0;
+ int r = src[i*2+1] ? 1 : 0;
+ dest[i] = l * 2 + r;
+ }
+}
+
+static inline int load_i(const uint8_t val[], int len) {
+ int acc = 0;
+ for (int i=0; i<len; i++){
+ acc = (acc << 1) + (val[i] & 1);
+ }
+ return acc;
+}
+
+// unpacks bytes into bits, len is length of result
+static inline void unpack_bytes(uint8_t result[], const char src[], int len) {
+ static const int nbytes = len / 8;
+ int outp = 0;
+ for (int i=0; i < len; i++) {
+ result[i] = (src[i>>3] >> (7-(i%8))) & 1;
+ }
+}
+
+static inline int crc6(const uint8_t * bits, int len) {
+ uint8_t s[6] = {1,1,1,1,1,1};
+ for (int i=0; i<len; i++) {
+ int bit = bits[i];
+ int a = bit ^ s[0];
+ s[0] = a ^ s[1];
+ s[1] = s[2];
+ s[2] = s[3];
+ s[3] = a ^ s[4];
+ s[4] = a ^ s[5];
+ s[5] = a;
+ }
+ return (load_i(s, 6));
+}
+
+static inline int crc12(uint8_t bits[], int len) {
+ uint8_t s[] = {1,1,1,1,1,1,1,1,1,1,1,1};
+ for (int i=0; i<len; i++) {
+ int bit = bits[i];
+ int a = bit ^ s[0];
+ s[0] = a ^ s[1];
+ s[1] = s[2];
+ s[2] = s[3];
+ s[3] = s[4];
+ s[4] = s[5];
+ s[5] = s[6];
+ s[6] = s[7];
+ s[7] = s[8];
+ s[8] = a ^ s[9];
+ s[9] = a ^ s[10];
+ s[10] = a ^ s[11];
+ s[11] = a;
+ }
+ return (load_i(s, 12));
+}
+
+static const uint8_t trellis_PC[] = {0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
+static inline void trellis_encode(const uint8_t src_bits[], uint8_t dest_bits[], const int dest_len) {
+ int reg = 0;
+ for (int i=0; i<dest_len/2; i++) {
+ int bit = src_bits[i];
+ reg = (reg << 1) | bit;
+ dest_bits[i*2] = trellis_PC[reg & 0x19];
+ dest_bits[i*2+1] = trellis_PC[reg & 0x17];
+ }
+}
+
+static inline uint16_t crc16(const uint8_t buf[], int len) {
+ uint32_t poly = (1<<12) + (1<<5) + (1<<0);
+ uint32_t crc = 0;
+ for(int i=0; i<len; i++) {
+ uint8_t bit = buf[i] & 1;
+ crc = ((crc << 1) | bit) & 0x1ffff;
+ if (crc & 0x10000)
+ crc = (crc & 0xffff) ^ poly;
+ }
+ crc = crc ^ 0xffff;
+ return crc & 0xffff;
+}
+
+static inline void encode_sacch_chunk(const uint8_t src_bits[18], uint8_t dest_dibits[30], int structure, int ran) {
+ uint8_t buf1[60];
+ uint8_t buf2[72];
+ uint8_t str_field[8];
+ int str;
+
+ str = (structure & 3) << 6;
+ str |= ran & 0x3f;
+ store_i(str, str_field, 8);
+
+ memcpy(buf1, str_field, 8);
+ memcpy(buf1+8, src_bits, 18);
+
+ int crc = crc6(buf1, 26);
+ store_i(crc, buf1+26, 6);
+ store_i(0, buf1+32, 4);
+ trellis_encode(buf1, buf2, sizeof(buf2));
+ for (int i=0, op=0; i<sizeof(buf2); i += 12) {
+ buf1[op++] = buf2[i+0];
+ buf1[op++] = buf2[i+1];
+ buf1[op++] = buf2[i+2];
+ buf1[op++] = buf2[i+3];
+ buf1[op++] = buf2[i+4];
+ buf1[op++] = buf2[i+6];
+ buf1[op++] = buf2[i+7];
+ buf1[op++] = buf2[i+8];
+ buf1[op++] = buf2[i+9];
+ buf1[op++] = buf2[i+10];
+ }
+ for (int i=0; i<60; i++) {
+ buf2[i] = buf1[PERM_12_5[i]];
+ }
+ bits_to_dibits(dest_dibits, buf2, 30);
+}
+
+static inline void encode_facch(const uint8_t src_bits[80], uint8_t dest_dibits[72]) {
+ uint8_t buf1[144];
+ uint8_t buf2[192];
+ memcpy(buf1, src_bits, 80);
+ int crc = crc12(buf1, 80);
+ store_i(crc, buf1+80, 12);
+ store_i(0, buf1+92, 4);
+ trellis_encode(buf1, buf2, sizeof(buf2));
+ for (int i=0, op=0; i<sizeof(buf2); i += 4) {
+ buf1[op++] = buf2[i+0];
+ buf1[op++] = buf2[i+2];
+ buf1[op++] = buf2[i+3];
+ }
+ for (int i=0; i<144; i++) {
+ buf2[i] = buf1[PERM_16_9[i]];
+ }
+ bits_to_dibits(dest_dibits, buf2, 72);
+}
+
+static inline void encode_lich(const int lich, uint8_t lich_dibits[8]) {
+ uint8_t b[8];
+ store_i(lich & 0x7f, b, 7);
+ b[8] = (b[0] + b[1] + b[2] + b[3]) & 1;
+ for (int i=0; i<8; i++)
+ lich_dibits[i] = (b[i]) ? 3 : 1;
+}
+
+namespace gr {
+ namespace op25_repeater {
+
+ nxdn_tx_sb::sptr
+ nxdn_tx_sb::make(int verbose_flag, const char * config_file, bool nxdn96_mode)
+ {
+ return gnuradio::get_initial_sptr
+ (new nxdn_tx_sb_impl(verbose_flag, config_file, nxdn96_mode));
+ }
+
+//////////////////////////////////////////////////////////////////////////
+
+static const int MIN_IN = 1;
+static const int MAX_IN = 1;
+
+static const int MIN_OUT = 1;
+static const int MAX_OUT = 1;
+
+ /*
+ * The private constructor
+ */
+ nxdn_tx_sb_impl::nxdn_tx_sb_impl(int verbose_flag, const char * config_file, bool nxdn96_mode)
+ : gr::block("nxdn_tx_sb",
+ gr::io_signature::make (MIN_IN, MAX_IN, sizeof(short)),
+ gr::io_signature::make (MIN_OUT, MAX_OUT, sizeof(char))),
+ d_verbose_flag(verbose_flag),
+ d_config_file(config_file),
+ d_nxdn96_mode(nxdn96_mode),
+ d_output_amount((nxdn96_mode) ? 384 : 192),
+ d_sacch_seq(0),
+ d_lich(0),
+ d_ran(0)
+ {
+ set_output_multiple(d_output_amount);
+ memset(d_acch, 0, sizeof(d_acch));
+ config();
+ }
+
+ /*
+ * Our virtual destructor.
+ */
+ nxdn_tx_sb_impl::~nxdn_tx_sb_impl()
+ {
+ }
+
+void
+nxdn_tx_sb_impl::config()
+{
+ FILE * fp1 = fopen(d_config_file, "r");
+ char line[256];
+ char * cp;
+ unsigned int li[10];
+ long int ran;
+ long int lich, lich2;
+ if (!fp1) {
+ fprintf(stderr, "nxdn_tx_sb_impl:config: failed to open %s\n", d_config_file);
+ return;
+ }
+ for (;;) {
+ cp = fgets(line, sizeof(line) - 2, fp1);
+ if (!cp) break;
+ if (line[0] == '#') continue;
+ if (memcmp(line, "ran=", 4) == 0) {
+ ran = strtol(line+4, 0, 0);
+ d_ran = ran;
+ } else if (memcmp(line, "lich=", 5) == 0) {
+ lich = strtol(line+5, 0, 0);
+ d_lich = lich;
+ } else if (memcmp(line, "lich2=", 6) == 0) {
+ lich2 = strtol(line+6, 0, 0);
+ d_lich2 = lich2;
+ } else if (memcmp(line, "acch=", 5) == 0) {
+ sscanf(&line[5], "%x %x %x %x %x %x %x %x %x %x", &li[0], &li[1], &li[2], &li[3], &li[4], &li[5], &li[6], &li[7], &li[8], &li[9]);
+ for (int i=0; i<10; i++) {
+ store_i(li[i], d_acch+i*8, 8);
+ }
+ }
+ }
+ encode_lich(d_lich, d_lich_x1);
+ encode_lich(d_lich2, d_lich_x2);
+ encode_facch(d_acch, d_facch1);
+ for (int i=0; i<4; i++)
+ encode_sacch_chunk(d_acch+18*i, d_sacch[i], 3-i, d_ran);
+ fclose(fp1);
+}
+
+void
+nxdn_tx_sb_impl::forecast(int nof_output_items, gr_vector_int &nof_input_items_reqd)
+{
+ // each 192-dibit output frame contains four voice code words=640 samples
+ // for nxdn96 we output 384 dibits per four voice code words
+ const size_t nof_inputs = nof_input_items_reqd.size();
+ const int nof_vcw = nof_output_items / d_output_amount;
+ const int nof_samples_reqd = nof_vcw * 4 * 160;
+ std::fill(&nof_input_items_reqd[0], &nof_input_items_reqd[nof_inputs], nof_samples_reqd);
+}
+
+int
+nxdn_tx_sb_impl::general_work (int noutput_items,
+ gr_vector_int &ninput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items)
+{
+
+ int nconsumed = 0;
+ int16_t *in;
+ in = (int16_t *) input_items[0];
+ uint8_t *out = reinterpret_cast<uint8_t*>(output_items[0]);
+ int nframes=0;
+ int16_t frame_vector[8];
+ voice_codeword cw(voice_codeword_sz);
+ uint8_t ambe_codeword[36]; // dibits
+ std::vector <bool> interleaved_buf(144);
+
+ for (int n=0;n < (noutput_items/d_output_amount);n++) {
+ // need (at least) four voice codewords worth of samples
+ if (ninput_items[0] - nconsumed < 4*160) break;
+ memcpy(out, nxdn_fs, sizeof(nxdn_fs));
+ memcpy(out+10, d_lich_x1, 8);
+ memcpy(out+18, d_sacch[d_sacch_seq++ % 4], 30);
+ // TODO: would be nice to multithread these
+ for (int vcw = 0; vcw < 4; vcw++) {
+ d_halfrate_encoder.encode(in, ambe_codeword);
+ memcpy(out+48+36*vcw, ambe_codeword, sizeof(ambe_codeword));
+ in += 160;
+ nconsumed += 160;
+ }
+ nxdn_descramble(out+10, 182);
+ if (d_nxdn96_mode) {
+ memcpy(out+192, nxdn_fs, sizeof(nxdn_fs));
+ memcpy(out+192+10, d_lich_x2, 8);
+ memcpy(out+192+18, d_sacch[d_sacch_seq++ % 4], 30);
+ memcpy(out+192+48, d_facch1, 72);
+ memcpy(out+192+120, d_facch1, 72);
+ nxdn_descramble(out+192+10, 182);
+ }
+ nframes += 1;
+ out += d_output_amount;
+ }
+
+ // Tell runtime system how many input items we consumed on
+ // each input stream.
+
+ if (nconsumed)
+ consume_each(nconsumed);
+
+ // Tell runtime system how many output items we produced.
+ return (nframes * d_output_amount);
+}
+
+void
+nxdn_tx_sb_impl::set_gain_adjust(float gain_adjust) {
+ d_halfrate_encoder.set_gain_adjust(gain_adjust);
+}
+
+ } /* namespace op25_repeater */
+} /* namespace gr */
diff --git a/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.h b/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.h
new file mode 100644
index 0000000..4d2590a
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/nxdn_tx_sb_impl.h
@@ -0,0 +1,80 @@
+/* -*- c++ -*- */
+/*
+ * NXDN Encoder (C) Copyright 2020 Max H. Parke KA1RBI
+ *
+ * This file is part of OP25
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef INCLUDED_OP25_REPEATER_NXDN_TX_SB_IMPL_H
+#define INCLUDED_OP25_REPEATER_NXDN_TX_SB_IMPL_H
+
+#include <op25_repeater/nxdn_tx_sb.h>
+
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <stdint.h>
+#include <vector>
+#include <deque>
+#include <algorithm>
+
+#include "imbe_vocoder/imbe_vocoder.h"
+#include "ambe_encoder.h"
+
+namespace gr {
+ namespace op25_repeater {
+
+ class nxdn_tx_sb_impl : public nxdn_tx_sb
+ {
+ private:
+ void config(void);
+
+ public:
+ nxdn_tx_sb_impl(int verbose_flag, const char * config_file, bool nxdn96_mode);
+ ~nxdn_tx_sb_impl();
+
+ void forecast (int noutput_items, gr_vector_int &ninput_items_required);
+
+ int general_work(int noutput_items,
+ gr_vector_int &ninput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items);
+ void set_gain_adjust(float gain_adjust);
+
+ private:
+ int d_verbose_flag;
+ int d_nxdn96_mode;
+ const char * d_config_file;
+ // imbe_vocoder d_fullrate_encoder;
+ ambe_encoder d_halfrate_encoder;
+ int d_output_amount;
+ int d_sacch_seq;
+
+ uint8_t d_lich;
+ uint8_t d_lich2;
+ uint16_t d_ran;
+ uint8_t d_acch[80];
+ uint8_t d_lich_x1[8];
+ uint8_t d_lich_x2[8];
+ uint8_t d_sacch[4][30];
+ uint8_t d_facch1[72];
+ };
+
+ } // namespace op25_repeater
+} // namespace gr
+
+#endif /* INCLUDED_OP25_REPEATER_NXDN_TX_SB_IMPL_H */
diff --git a/op25/gr-op25_repeater/lib/op25_audio.cc b/op25/gr-op25_repeater/lib/op25_audio.cc
new file mode 100644
index 0000000..ed5963c
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/op25_audio.cc
@@ -0,0 +1,247 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2017 Graham J Norbury, gnorbury@bondcar.com
+ * from op25_audio; rewrite Nov 2017 Copyright 2017 Max H. Parke KA1RBI
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <netdb.h>
+
+#include "op25_audio.h"
+
+// convert hostname to ip address
+static int hostname_to_ip(const char *hostname , char *ip)
+{
+ int sockfd;
+ struct addrinfo hints, *servinfo, *p;
+ struct sockaddr_in *h;
+ int rv;
+
+ memset(&hints, 0, sizeof hints);
+ hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
+ hints.ai_socktype = SOCK_DGRAM;
+
+ if ( (rv = getaddrinfo( hostname , NULL , &hints , &servinfo)) != 0)
+ {
+ fprintf(stderr, "op25_audio::hostname_to_ip() getaddrinfo: %s\n", gai_strerror(rv));
+ return -1;
+ }
+
+ // loop through all the results and connect to the first we can
+ for(p = servinfo; p != NULL; p = p->ai_next)
+ {
+ h = (struct sockaddr_in *) p->ai_addr;
+ if (h->sin_addr.s_addr != 0)
+ {
+ strcpy(ip , inet_ntoa( h->sin_addr ) );
+ break;
+ }
+ }
+
+ freeaddrinfo(servinfo); // all done with this structure
+ return 0;
+
+}
+
+// constructor
+op25_audio::op25_audio(const char* udp_host, int port, int debug) :
+ d_udp_enabled(false),
+ d_debug(debug),
+ d_write_port(port),
+ d_audio_port(port),
+ d_write_sock(0),
+ d_file_enabled(false)
+{
+ char ip[20];
+ if (hostname_to_ip(udp_host, ip) == 0)
+ {
+ strncpy(d_udp_host, ip, sizeof(d_udp_host));
+ d_udp_host[sizeof(d_udp_host)-1] = 0;
+ if ( port )
+ open_socket();
+ }
+}
+
+// destructor
+op25_audio::~op25_audio()
+{
+ if (d_file_enabled)
+ close(d_write_sock);
+ close_socket();
+}
+
+// constructor
+op25_audio::op25_audio(const char* destination, int debug) :
+ d_udp_enabled(false),
+ d_debug(debug),
+ d_write_port(0),
+ d_audio_port(0),
+ d_write_sock(0),
+ d_file_enabled(false)
+{
+ static const int DEFAULT_UDP_PORT = 23456;
+ static const char P_UDP[] = "udp://";
+ static const char P_FILE[] = "file://";
+ int port = DEFAULT_UDP_PORT;
+
+ if (memcmp(destination, P_UDP, strlen(P_UDP)) == 0) {
+ char ip[20];
+ char host[64];
+ const char * p1 = destination+strlen(P_UDP);
+ strncpy(host, p1, sizeof(host));
+ char * pc = index(host, ':');
+ if (pc) {
+ sscanf(pc+1, "%d", &port);
+ *pc = 0;
+ }
+ if (hostname_to_ip(host, ip) == 0) {
+ strncpy(d_udp_host, ip, sizeof(d_udp_host));
+ d_udp_host[sizeof(d_udp_host)-1] = 0;
+ d_write_port = d_audio_port = port;
+ open_socket();
+ }
+ } else if (memcmp(destination, P_FILE, strlen(P_FILE)) == 0) {
+ const char * filename = destination+strlen(P_FILE);
+ size_t l = strlen(filename);
+ if (l > 4 && (strcmp(&filename[l-4], ".wav") == 0 || strcmp(&filename[l-4], ".WAV") == 0)) {
+ fprintf (stderr, "Warning! Output file %s will be written, but in raw form ***without*** a WAV file header!\n", filename);
+ }
+ d_write_sock = open(filename, O_WRONLY | O_CREAT, 0644);
+ if (d_write_sock < 0) {
+ fprintf(stderr, "op25_audio::open file %s: error: %d (%s)\n", filename, errno, strerror(errno));
+ d_write_sock = 0;
+ return;
+ }
+ d_file_enabled = true;
+ }
+}
+// open socket and set up data structures
+void op25_audio::open_socket()
+{
+ memset (&d_sock_addr, 0, sizeof(d_sock_addr));
+
+ // open handle to socket
+ d_write_sock = socket(PF_INET, SOCK_DGRAM, 17); // UDP socket
+ if ( d_write_sock < 0 )
+ {
+ fprintf(stderr, "op25_audio::open_socket(): error: %d\n", errno);
+ d_write_sock = 0;
+ return;
+ }
+
+ // set up data structure for generic udp host/port
+ if ( !inet_aton(d_udp_host, &d_sock_addr.sin_addr) )
+ {
+ fprintf(stderr, "op25_audio::open_socket(): inet_aton: bad IP address\n");
+ close(d_write_sock);
+ d_write_sock = 0;
+ return;
+ }
+ d_sock_addr.sin_family = AF_INET;
+
+ fprintf(stderr, "op25_audio::open_socket(): enabled udp host(%s), wireshark(%d), audio(%d)\n", d_udp_host, d_write_port, d_audio_port);
+ d_udp_enabled = true;
+}
+
+// close socket
+void op25_audio::close_socket()
+{
+ if (!d_udp_enabled)
+ return;
+ close(d_write_sock);
+ d_write_sock = 0;
+ d_udp_enabled = false;
+}
+
+ssize_t op25_audio::do_send(const void * buf, size_t len, int port, bool is_ctrl ) const {
+ ssize_t rc = 0;
+ struct sockaddr_in tmp_sockaddr;
+ if (len <= 0)
+ return 0;
+ if (d_udp_enabled) {
+ memcpy(&tmp_sockaddr, &d_sock_addr, sizeof(struct sockaddr));
+ tmp_sockaddr.sin_port = htons(port);
+ rc = sendto(d_write_sock, buf, len, 0, (struct sockaddr *)&tmp_sockaddr, sizeof(struct sockaddr_in));
+ if (rc == -1)
+ {
+ fprintf(stderr, "op25_audio::do_send(length %lu): error(%d): %s\n", len, errno, strerror(errno));
+ rc = 0;
+ }
+ } else if (d_file_enabled && !is_ctrl) {
+ size_t amt_written = 0;
+ for (;;) {
+ rc = write(d_write_sock, amt_written + (char*)buf, len - amt_written);
+ if (rc < 0) {
+ fprintf(stderr, "op25_audio::write(length %lu): error(%d): %s\n", len, errno, strerror(errno));
+ rc = 0;
+ } else if (rc == 0) {
+ fprintf(stderr, "op25_audio::write(length %lu): error, write rc zero\n", len);
+ } else {
+ amt_written += rc;
+ }
+ if (rc <= 0 || amt_written >= len)
+ break;
+ } /* end of for() */
+ rc = amt_written;
+ }
+ return rc;
+}
+
+// send generic data to destination
+ssize_t op25_audio::send_to(const void *buf, size_t len) const
+{
+ return do_send(buf, len, d_write_port, false);
+}
+
+// send audio data to destination
+ssize_t op25_audio::send_audio(const void *buf, size_t len) const
+{
+ return do_send(buf, len, d_audio_port, false);
+}
+
+// send audio data on specifed channel to destination
+ssize_t op25_audio::send_audio_channel(const void *buf, size_t len, ssize_t slot_id) const
+{
+ return do_send(buf, len, d_audio_port + slot_id*2, false);
+}
+
+// send flag to audio destination
+ssize_t op25_audio::send_audio_flag_channel(const udpFlagEnumType udp_flag, ssize_t slot_id) const
+{
+ char audio_flag[2];
+ // 16 bit little endian encoding
+ audio_flag[0] = (udp_flag & 0x00ff);
+ audio_flag[1] = ((udp_flag & 0xff00) >> 8);
+ return do_send(audio_flag, 2, d_audio_port+slot_id, true);
+}
+
+ssize_t op25_audio::send_audio_flag(const op25_audio::udpFlagEnumType udp_flag) const
+{
+ return send_audio_flag_channel(udp_flag, 0);
+}
diff --git a/op25/gr-op25_repeater/lib/op25_audio.h b/op25/gr-op25_repeater/lib/op25_audio.h
new file mode 100644
index 0000000..dc715a0
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/op25_audio.h
@@ -0,0 +1,70 @@
+/* -*- c++ -*- */
+/*
+ * Copyright 2017 Graham J Norbury, gnorbury@bondcar.com
+ * from op25_audio; rewrite Nov 2017 Copyright 2017 Max H. Parke KA1RBI
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef INCLUDED_OP25_AUDIO_H
+#define INCLUDED_OP25_AUDIO_H
+
+#include <stdint.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+class op25_audio
+{
+public:
+ enum udpFlagEnumType
+ {
+ DRAIN = 0x0000, // play queued pcm frames
+ DROP = 0x0001 // discard queued pcm frames
+ };
+
+private:
+ bool d_udp_enabled;
+ int d_debug;
+ int d_write_port;
+ int d_audio_port;
+ char d_udp_host[64];
+ int d_write_sock;
+ bool d_file_enabled;
+ struct sockaddr_in d_sock_addr;
+
+ void open_socket();
+ void close_socket();
+ ssize_t do_send(const void * bufp, size_t len, int port, bool is_ctrl) const;
+
+public:
+ op25_audio(const char* udp_host, int port, int debug);
+ op25_audio(const char* destination, int debug);
+ ~op25_audio();
+
+ inline bool enabled() const { return d_udp_enabled; }
+
+ ssize_t send_to(const void *buf, size_t len) const;
+
+ ssize_t send_audio(const void *buf, size_t len) const;
+ ssize_t send_audio_flag(const udpFlagEnumType udp_flag) const;
+
+ ssize_t send_audio_channel(const void *buf, size_t len, ssize_t slot_id) const;
+ ssize_t send_audio_flag_channel(const udpFlagEnumType udp_flag, ssize_t slot_id) const;
+
+}; // class op25_audio
+
+#endif /* INCLUDED_OP25_AUDIO_H */
diff --git a/op25/gr-op25_repeater/lib/p25_frame.h b/op25/gr-op25_repeater/lib/p25_frame.h
index 8afbaf0..6c47b01 100644
--- a/op25/gr-op25_repeater/lib/p25_frame.h
+++ b/op25/gr-op25_repeater/lib/p25_frame.h
@@ -18,8 +18,8 @@
* Boston, MA 02110-1301, USA.
*/
-#ifndef INCLUDED_OP25_P25_FRAME_H
-#define INCLUDED_OP25_P25_FRAME_H 1
+#ifndef INCLUDED_P25_FRAME_H
+#define INCLUDED_P25_FRAME_H 1
#include <vector>
typedef std::vector<bool> bit_vector;
@@ -62,4 +62,4 @@ p25_setup_frame_header(bit_vector& frame_body, uint64_t hw) {
} // namespace op25_repeater
} // namespace gr
-#endif /* INCLUDED_OP25_P25_FRAME_H */
+#endif /* INCLUDED_P25_FRAME_H */
diff --git a/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.cc b/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.cc
index 1c1acf7..43086c2 100644
--- a/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.cc
+++ b/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.cc
@@ -39,12 +39,23 @@ namespace gr {
void p25_frame_assembler_impl::p25p2_queue_msg(int duid)
{
- static const char wbuf[2] = {0xff, 0xff}; // dummy NAC
+ unsigned char wbuf[8];
+ int p=0;
+
if (!d_do_msgq)
return;
if (d_msg_queue->full_p())
return;
- gr::message::sptr msg = gr::message::make_from_string(std::string(wbuf, 2), duid, 0, 0);
+ if (!d_nac)
+ return;
+
+ wbuf[p++] = 0xaa;
+ wbuf[p++] = 0x55;
+ wbuf[p++] = (d_msgq_id >> 8) & 0xff;
+ wbuf[p++] = d_msgq_id & 0xff;
+ wbuf[p++] = (d_nac >> 8) & 0xff;
+ wbuf[p++] = d_nac & 0xff;
+ gr::message::sptr msg = gr::message::make_from_string(std::string((const char *)wbuf, p), duid, 0, 0);
d_msg_queue->insert_tail(msg);
}
@@ -52,15 +63,20 @@ namespace gr {
p2tdma.set_xormask(p);
}
+ void p25_frame_assembler_impl::set_nac(int nac) {
+ d_nac = nac;
+ p2tdma.set_nac(nac);
+ }
+
void p25_frame_assembler_impl::set_slotid(int slotid) {
p2tdma.set_slotid(slotid);
}
p25_frame_assembler::sptr
- p25_frame_assembler::make(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma)
+ p25_frame_assembler::make(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma, int msgq_id)
{
return gnuradio::get_initial_sptr
- (new p25_frame_assembler_impl(udp_host, port, debug, do_imbe, do_output, do_msgq, queue, do_audio_output, do_phase2_tdma));
+ (new p25_frame_assembler_impl(udp_host, port, debug, do_imbe, do_output, do_msgq, queue, do_audio_output, do_phase2_tdma, msgq_id));
}
/*
@@ -80,24 +96,24 @@ static const int MAX_IN = 1; // maximum number of input streams
/*
* The private constructor
*/
- p25_frame_assembler_impl::p25_frame_assembler_impl(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma)
+ p25_frame_assembler_impl::p25_frame_assembler_impl(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma, int msgq_id)
: gr::block("p25_frame_assembler",
gr::io_signature::make (MIN_IN, MAX_IN, sizeof (char)),
gr::io_signature::make ((do_output) ? 1 : 0, (do_output) ? 1 : 0, (do_audio_output && do_output) ? sizeof(int16_t) : ((do_output) ? sizeof(char) : 0 ))),
d_do_imbe(do_imbe),
d_do_output(do_output),
output_queue(),
- p1fdma(udp_host, port, debug, do_imbe, do_output, do_msgq, queue, output_queue, do_audio_output),
+ op25audio(udp_host, port, debug),
+ p1fdma(op25audio, debug, do_imbe, do_output, do_msgq, queue, output_queue, do_audio_output, msgq_id),
d_do_audio_output(do_audio_output),
d_do_phase2_tdma(do_phase2_tdma),
- p2tdma(udp_host, port, 0, debug, output_queue),
+ p2tdma(op25audio, 0, debug, do_msgq, queue, output_queue, do_audio_output, msgq_id),
d_do_msgq(do_msgq),
- d_msg_queue(queue)
+ d_msg_queue(queue),
+ d_nac(0),
+ d_msgq_id(msgq_id)
{
- if (d_do_audio_output && !d_do_imbe)
- fprintf(stderr, "p25_frame_assembler: error: do_imbe must be enabled if do_audio_output is enabled\n");
- if (d_do_phase2_tdma && !d_do_audio_output)
- fprintf(stderr, "p25_frame_assembler: error: do_audio_output must be enabled if do_phase2_tdma is enabled\n");
+ fprintf(stderr, "p25_frame_assembler_impl: do_imbe[%d], do_output[%d], do_audio_output[%d], do_phase2_tdma[%d]\n", do_imbe, do_output, do_audio_output, do_phase2_tdma);
}
void
@@ -113,6 +129,7 @@ p25_frame_assembler_impl::forecast(int nof_output_items, gr_vector_int &nof_inpu
nof_samples_reqd = nof_output_items;
if (d_do_audio_output)
nof_samples_reqd = 0.6 * nof_output_items;
+ nof_samples_reqd = std::max(nof_samples_reqd, 256);
std::fill(&nof_input_items_reqd[0], &nof_input_items_reqd[nof_inputs], nof_samples_reqd);
}
@@ -130,9 +147,10 @@ p25_frame_assembler_impl::general_work (int noutput_items,
for (int i = 0; i < ninput_items[0]; i++) {
if(p2tdma.rx_sym(in[i])) {
int rc = p2tdma.handle_frame();
- if (rc > -1)
+ if (rc > -1) {
p25p2_queue_msg(rc);
p1fdma.reset_timer(); // prevent P1 timeouts due to long TDMA transmissions
+ }
}
}
}
diff --git a/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.h b/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.h
index 9763e79..5c53a77 100644
--- a/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.h
+++ b/op25/gr-op25_repeater/lib/p25_frame_assembler_impl.h
@@ -32,6 +32,7 @@
#include "p25p1_fdma.h"
#include "p25p2_tdma.h"
+#include "op25_audio.h"
typedef std::deque<uint8_t> dibit_queue;
@@ -49,11 +50,14 @@ namespace gr {
p25p2_tdma p2tdma;
bool d_do_msgq;
gr::msg_queue::sptr d_msg_queue;
+ int d_nac;
+ int d_msgq_id;
// internal functions
void p25p2_queue_msg(int duid);
void set_xormask(const char*p) ;
+ void set_nac(int nac);
void set_slotid(int slotid) ;
typedef std::vector<bool> bit_vector;
std::deque<int16_t> output_queue;
@@ -63,9 +67,11 @@ namespace gr {
// Nothing to declare in this block.
public:
- p25_frame_assembler_impl(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma);
+ p25_frame_assembler_impl(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, bool do_audio_output, bool do_phase2_tdma, int msgq_id);
~p25_frame_assembler_impl();
+ op25_audio op25audio;
+
// Where all the action really happens
int general_work(int noutput_items,
diff --git a/op25/gr-op25_repeater/lib/p25_framer.cc b/op25/gr-op25_repeater/lib/p25_framer.cc
index 20338b4..32d92a5 100644
--- a/op25/gr-op25_repeater/lib/p25_framer.cc
+++ b/op25/gr-op25_repeater/lib/p25_framer.cc
@@ -7,16 +7,16 @@
#include <vector>
#include <stdio.h>
#include <stdint.h>
-#include <bch.h>
+#include "bch.h"
#include <sys/time.h>
-#include <op25_p25_frame.h>
-#include <p25_framer.h>
+#include "op25_p25_frame.h"
+#include "p25_framer.h"
#include "check_frame_sync.h"
static const int max_frame_lengths[16] = {
// lengths are in bits, not symbols
- 792, // 0 - pdu
+ 792, // 0 - hdu
0, 0, // 1, 2 - undef
144, // 3 - tdu
0, // 4 - undef
@@ -27,17 +27,22 @@ static const int max_frame_lengths[16] = {
0, // 9 - VSELP "voice PDU"
P25_VOICE_FRAME_SIZE, // a - ldu2
0, // b - undef
- 720, // c - VSELP "voice PDU"
+ 962, // c - pdu (triple data block MBT)
0, 0, // d, e - undef
432 // f - tdu
};
// constructor
-p25_framer::p25_framer() :
+p25_framer::p25_framer(int debug, int msgq_id) :
+ d_debug(debug),
+ d_msgq_id(msgq_id),
reverse_p(0),
nid_syms(0),
next_bit(0),
nid_accum(0),
+ nac(0),
+ duid(0),
+ parity(0),
frame_size_limit(0),
symbols_received(0),
frame_body(P25_VOICE_FRAME_SIZE)
@@ -57,35 +62,41 @@ p25_framer::~p25_framer ()
*/
bool p25_framer::nid_codeword(uint64_t acc) {
bit_vector cw(64);
- bool low = acc & 1;
- // for bch, split bits into codeword vector
- for (int i=0; i < 64; i++) {
+ uint64_t save_acc = acc;
+
+ // save the parity lsb, not used by BCH`
+ int acc_parity = acc & 1;
+
+ // for bch, split bits into codeword vector (lsb first)
+ for (int i = 0; i <= 63; i++) {
acc >>= 1;
cw[i] = acc & 1;
}
// do bch decode
- int rc = bchDec(cw);
-
- // check if bch decode unsuccessful
- if (rc < 0) {
- return false;
- }
-
- bch_errors = rc;
-
- // load corrected bch bits into acc
+ int ec = bchDec(cw);
+
+ // load corrected bch bits into acc (msb first)
acc = 0;
- for (int i=63; i>=0; i--) {
+ for (int i = 63; i >= 0; i--) {
acc |= cw[i];
acc <<= 1;
}
- acc |= low; // FIXME
+
+ // put the parity lsb back
+ acc |= acc_parity;
+
+ // check if bch decode unsuccessful
+ if (ec < 0)
+ return false;
+
+ bch_errors = ec;
nid_word = acc; // reconstructed NID
// extract nac and duid
nac = (acc >> 52) & 0xfff;
duid = (acc >> 48) & 0x00f;
+ parity = acc_parity;
return true;
}
@@ -100,6 +111,7 @@ bool p25_framer::nid_codeword(uint64_t acc) {
* Returns true when complete frame received, else false
*/
bool p25_framer::rx_sym(uint8_t dibit) {
+ struct timeval currtime;
symbols_received++;
bool rc = false;
dibit ^= reverse_p;
@@ -125,7 +137,7 @@ bool p25_framer::rx_sym(uint8_t dibit) {
if (nid_syms > 0) // if nid accumulation in progress
nid_syms++; // count symbols in nid
- if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ P25_FRAME_SYNC_MAGIC, 6, 48)) {
+ if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ P25_FRAME_SYNC_MAGIC, 3, 48)) {
nid_syms = 1;
}
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ P25_FRAME_SYNC_REV_P, 0, 48)) {
@@ -134,13 +146,16 @@ bool p25_framer::rx_sym(uint8_t dibit) {
fprintf(stderr, "Reversed FS polarity detected - autocorrecting\n");
}
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0x001050551155LL, 0, 48)) {
- fprintf(stderr, "tuning error -1200\n");
+ gettimeofday(&currtime, 0);
+ fprintf(stderr, "%010lu.%06lu channel %d tuning error -1200\n", currtime.tv_sec, currtime.tv_usec, d_msgq_id);
}
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xFFEFAFAAEEAALL, 0, 48)) {
- fprintf(stderr, "tuning error +1200\n");
+ gettimeofday(&currtime, 0);
+ fprintf(stderr, "%010lu.%06lu channel %d tuning error +1200\n", currtime.tv_sec, currtime.tv_usec, d_msgq_id);
}
if(check_frame_sync((nid_accum & P25_FRAME_SYNC_MASK) ^ 0xAA8A0A008800LL, 0, 48)) {
- fprintf(stderr, "tuning error +/- 2400\n");
+ gettimeofday(&currtime, 0);
+ fprintf(stderr, "%010lu.%06lu channel %d tuning error +/- 2400\n", currtime.tv_sec, currtime.tv_usec, d_msgq_id);
}
if (next_bit > 0) {
frame_body[next_bit++] = (dibit >> 1) & 1;
diff --git a/op25/gr-op25_repeater/lib/p25_framer.h b/op25/gr-op25_repeater/lib/p25_framer.h
index ddaf71c..1a7fe55 100644
--- a/op25/gr-op25_repeater/lib/p25_framer.h
+++ b/op25/gr-op25_repeater/lib/p25_framer.h
@@ -26,9 +26,11 @@ private:
uint64_t nid_accum;
uint32_t frame_size_limit;
+ int d_debug;
+ int d_msgq_id;
public:
- p25_framer(); // constructor
+ p25_framer(int debug = 0, int msgq_id=0);
~p25_framer (); // destructor
bool rx_sym(uint8_t dibit) ;
@@ -38,9 +40,10 @@ public:
uint64_t nid_word; // received NID word
uint32_t nac; // extracted NAC
uint32_t duid; // extracted DUID
+ uint8_t parity; // extracted DUID parity
bit_vector frame_body; // all bits in frame
- uint32_t frame_size; // number of bits in frame_body
- uint32_t bch_errors; // number of errors detected in bch
+ uint32_t frame_size; // number of bits in frame_body
+ uint32_t bch_errors; // number of errors detected in bch
};
#endif /* INCLUDED_P25_FRAMER_H */
diff --git a/op25/gr-op25_repeater/lib/p25p1_fdma.cc b/op25/gr-op25_repeater/lib/p25p1_fdma.cc
index 336e0e8..396fb55 100644
--- a/op25/gr-op25_repeater/lib/p25p1_fdma.cc
+++ b/op25/gr-op25_repeater/lib/p25p1_fdma.cc
@@ -1,6 +1,8 @@
/* -*- c++ -*- */
/*
- * Copyright 2010, 2011, 2012, 2013, 2014 Max H. Parke KA1RBI
+ * Copyright 2010, 2011, 2012, 2013, 2014, 2018 Max H. Parke KA1RBI
+ * Copyright 2017 Graham J. Norbury (modularization rewrite)
+ * Copyright 2008, Michael Ossmann <mike@ossmann.com>
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -37,6 +39,7 @@
#include "p25_frame.h"
#include "p25_framer.h"
#include "rs.h"
+#include "value_string.h"
namespace gr {
namespace op25_repeater {
@@ -45,12 +48,12 @@ static const int64_t TIMEOUT_THRESHOLD = 1000000;
p25p1_fdma::~p25p1_fdma()
{
- if (write_sock > 0)
- close(write_sock);
delete framer;
}
static uint16_t crc16(uint8_t buf[], int len) {
+ if (buf == 0)
+ return -1;
uint32_t poly = (1<<12) + (1<<5) + (1<<0);
uint32_t crc = 0;
for(int i=0; i<len; i++) {
@@ -146,8 +149,6 @@ block_deinterleave(bit_vector& bv, unsigned int start, uint8_t* buf)
int state = 0;
uint8_t codeword;
uint16_t crc;
- uint32_t crc1;
- uint32_t crc2;
static const uint8_t next_words[4][4] = {
{0x2, 0xC, 0x1, 0xF},
@@ -187,38 +188,31 @@ block_deinterleave(bit_vector& bv, unsigned int start, uint8_t* buf)
buf[d >> 2] |= state << (6 - ((d%4) * 2));
}
}
- crc = crc16(buf, 12);
- if (crc == 0)
- return 0; // return OK code
- crc1 = crc32(buf, 8*8); // try crc32
- crc2 = (buf[8] << 24) + (buf[9] << 16) + (buf[10] << 8) + buf[11];
- if (crc1 == crc2)
- return 0; // return OK code
- return -2; // trellis decode OK, but CRC error occurred
+ return 0;
}
-p25p1_fdma::p25p1_fdma(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &output_queue, bool do_audio_output) :
+p25p1_fdma::p25p1_fdma(const op25_audio& udp, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &output_queue, bool do_audio_output, int msgq_id) :
+ op25audio(udp),
write_bufp(0),
- write_sock(0),
- d_udp_host(udp_host),
- d_port(port),
d_debug(debug),
d_do_imbe(do_imbe),
d_do_output(do_output),
d_do_msgq(do_msgq),
d_msg_queue(queue),
output_queue(output_queue),
- framer(new p25_framer()),
+ framer(new p25_framer(debug, msgq_id)),
d_do_audio_output(do_audio_output),
- p1voice_decode((debug > 0), udp_host, port, output_queue)
+ ess_algid(0x80),
+ ess_keyid(0),
+ vf_tgid(0),
+ d_msgq_id(msgq_id),
+ p1voice_decode((debug > 0), udp, output_queue)
{
gettimeofday(&last_qtime, 0);
- if (port > 0)
- init_sock(d_udp_host, d_port);
}
void
-p25p1_fdma::process_duid(uint32_t const duid, uint32_t const nac, uint8_t const buf[], int const len)
+p25p1_fdma::process_duid(uint32_t const duid, uint32_t const nac, const uint8_t* buf, const int len)
{
char wbuf[256];
int p = 0;
@@ -226,7 +220,11 @@ p25p1_fdma::process_duid(uint32_t const duid, uint32_t const nac, uint8_t const
return;
if (d_msg_queue->full_p())
return;
- assert (len+2 <= sizeof(wbuf));
+ assert (len+6 <= sizeof(wbuf));
+ wbuf[p++] = 0xaa;
+ wbuf[p++] = 0x55;
+ wbuf[p++] = (d_msgq_id >> 8) & 0xff;
+ wbuf[p++] = d_msgq_id & 0xff;
wbuf[p++] = (nac >> 8) & 0xff;
wbuf[p++] = nac & 0xff;
if (buf) {
@@ -236,110 +234,507 @@ p25p1_fdma::process_duid(uint32_t const duid, uint32_t const nac, uint8_t const
gr::message::sptr msg = gr::message::make_from_string(std::string(wbuf, p), duid, 0, 0);
d_msg_queue->insert_tail(msg);
gettimeofday(&last_qtime, 0);
-// msg.reset();
}
void
-p25p1_fdma::reset_timer()
+p25p1_fdma::process_HDU(const bit_vector& A)
{
- //update last_qtime with current time
- gettimeofday(&last_qtime, 0);
+ uint32_t MFID;
+ int i, j, k, ec;
+ uint32_t gly;
+ std::vector<uint8_t> HB(63,0); // hexbit vector
+ std::string s = "";
+ int failures = 0;
+ k = 0;
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x HDU: ", logts.get(), framer->nac);
+ }
+
+ for (i = 0; i < 36; i ++) {
+ uint32_t CW = 0;
+ for (j = 0; j < 18; j++) { // 18 bits / cw
+ CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
+ }
+ gly = gly24128Dec(CW);
+ HB[27 + i] = gly & 63;
+ if (CW ^ gly24128Enc(gly))
+ /* "failures" in this context means any mismatch,
+ * disregarding how "recoverable" the error may be
+ * and disregarding how many bits may mismatch */
+ failures += 1;
+ }
+ ec = rs16.decode(HB); // Reed Solomon (36,20,17) error correction
+ if (failures > 6) {
+ if (d_debug >= 10) {
+ fprintf (stderr, "ESS computation suppressed: failed %d of 36, ec=%d\n", failures, ec);
+ }
+ return;
+ }
+ if (ec >= 0) {
+ j = 27; // 72 bit MI
+ for (i = 0; i < 9;) {
+ ess_mi[i++] = (uint8_t) (HB[j ] << 2) + (HB[j+1] >> 4);
+ ess_mi[i++] = (uint8_t) ((HB[j+1] & 0x0f) << 4) + (HB[j+2] >> 2);
+ ess_mi[i++] = (uint8_t) ((HB[j+2] & 0x03) << 6) + HB[j+3];
+ j += 4;
+ }
+ MFID = (HB[j ] << 2) + (HB[j+1] >> 4); // 8 bit MfrId
+ ess_algid = ((HB[j+1] & 0x0f) << 4) + (HB[j+2] >> 2); // 8 bit AlgId
+ ess_keyid = ((HB[j+2] & 0x03) << 14) + (HB[j+3] << 8) + (HB[j+4] << 2) + (HB[j+5] >> 4); // 16 bit KeyId
+ vf_tgid = ((HB[j+5] & 0x0f) << 12) + (HB[j+6] << 6) + HB[j+7]; // 16 bit TGID
+
+ if (ess_algid == 0) { // workaround spurious algid
+ ess_algid = 128; // unenc
+ if (d_debug)
+ fprintf(stderr, "***HDU detected zero algid, msgq_id %d***\n", d_msgq_id);
+ }
+
+ if (d_debug >= 10) {
+ fprintf (stderr, "ESS: tgid=%d, mfid=%x, algid=%x, keyid=%x, mi=", vf_tgid, MFID, ess_algid, ess_keyid);
+ for (i = 0; i < 9; i++) {
+ fprintf(stderr, "%02x ", ess_mi[i]);
+ }
+ fprintf(stderr, ", Golay failures=%d of 36, ec=%d", failures, ec);
+ }
+ s = "{\"nac\" : " + std::to_string(framer->nac) + ", \"algid\" : " + std::to_string(ess_algid) + ", \"alg\" : \"" + lookup(ess_algid, ALGIDS, ALGIDS_SZ) + "\", \"keyid\": " + std::to_string(ess_keyid) + "}";
+ send_msg(s, -3);
+ }
+
+ if (d_debug >= 10) {
+ fprintf (stderr, "\n");
+ }
}
-void
-p25p1_fdma::rx_sym (const uint8_t *syms, int nsyms)
+int
+p25p1_fdma::process_LLDU(const bit_vector& A, std::vector<uint8_t>& HB)
+{ // return count of hamming failures
+ process_duid(framer->duid, framer->nac, NULL, 0);
+
+ int i, j, k;
+ int failures = 0;
+ k = 0;
+ for (i = 0; i < 24; i ++) { // 24 10-bit codewords
+ uint32_t CW = 0;
+ for (j = 0; j < 10; j++) { // 10 bits / cw
+ CW = (CW << 1) + A[ imbe_ldu_ls_data_bits[k++] ];
+ }
+ HB[39 + i] = hmg1063Dec( CW >> 4, CW & 0x0f );
+ if (CW ^ ((HB[39+i] << 4) + hmg1063EncTbl[HB[39+i]]))
+ failures += 1;
+ }
+ return failures;
+}
+
+void
+p25p1_fdma::process_LDU1(const bit_vector& A)
{
- struct timeval currtime;
- for (int i1 = 0; i1 < nsyms; i1++){
- if(framer->rx_sym(syms[i1])) { // complete frame was detected
+ int hmg_failures;
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x LDU1: ", logts.get(), framer->nac);
+ }
+
+ std::vector<uint8_t> HB(63,0); // hexbit vector
+ hmg_failures = process_LLDU(A, HB);
+ if (hmg_failures < 6)
+ process_LCW(HB);
+ else {
if (d_debug >= 10) {
- fprintf (stderr, "NAC 0x%X DUID 0x%X len %u errs %u ", framer->nac, framer->duid, framer->frame_size >> 1, framer->bch_errors);
- }
- if ((framer->duid == 0x03) ||
- (framer->duid == 0x05) ||
- (framer->duid == 0x0A) ||
- (framer->duid == 0x0F)) {
- process_duid(framer->duid, framer->nac, NULL, 0);
+ fprintf (stderr, " (LCW computation suppressed");
}
- if ((framer->duid == 0x07 || framer->duid == 0x0c)) {
- unsigned int d, b;
- int rc[3];
- bit_vector bv1(720);
- int sizes[3] = {360, 576, 720};
- uint8_t deinterleave_buf[3][12];
-
- if (framer->frame_size > 720) {
- fprintf(stderr, "warning trunk frame size %u exceeds maximum\n", framer->frame_size);
- framer->frame_size = 720;
+ }
+
+ if (d_debug >= 10) {
+ fprintf(stderr, ", Hamming failures=%d of 24", hmg_failures);
+ fprintf (stderr, "\n");
+ }
+
+ // LDUx frames with exactly 20 failures seem to be not uncommon (and deliberate?)
+ // a TDU almost always immediately follows these code violations
+ if (hmg_failures < 16)
+ process_voice(A);
+}
+
+void
+p25p1_fdma::process_LDU2(const bit_vector& A)
+{
+ std::string s = "";
+ int hmg_failures;
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x LDU2: ", logts.get(), framer->nac);
+ }
+
+ std::vector<uint8_t> HB(63,0); // hexbit vector
+ hmg_failures = process_LLDU(A, HB);
+
+ int i, j, ec=0;
+ if (hmg_failures < 6) {
+ ec = rs8.decode(HB); // Reed Solomon (24,16,9) error correction
+ if (ec >= 0) { // save info if good decode
+ j = 39; // 72 bit MI
+ for (i = 0; i < 9;) {
+ ess_mi[i++] = (uint8_t) (HB[j ] << 2) + (HB[j+1] >> 4);
+ ess_mi[i++] = (uint8_t) ((HB[j+1] & 0x0f) << 4) + (HB[j+2] >> 2);
+ ess_mi[i++] = (uint8_t) ((HB[j+2] & 0x03) << 6) + HB[j+3];
+ j += 4;
}
- for (d=0, b=0; d < framer->frame_size >> 1; d++) {
- if ((d+1) % 36 == 0)
- continue; // skip SS
- bv1[b++] = framer->frame_body[d*2];
- bv1[b++] = framer->frame_body[d*2+1];
+ ess_algid = (HB[j ] << 2) + (HB[j+1] >> 4); // 8 bit AlgId
+ ess_keyid = ((HB[j+1] & 0x0f) << 12) + (HB[j+2] << 6) + HB[j+3]; // 16 bit KeyId
+
+ if (ess_algid == 0) { // workaround spurious algid
+ ess_algid = 128; // unenc
+ if (d_debug)
+ fprintf(stderr, "***LDU2 detected zero algid, msgq_id %d***\n", d_msgq_id);
}
- for(int sz=0; sz < 3; sz++) {
- if (framer->frame_size >= sizes[sz]) {
- rc[sz] = block_deinterleave(bv1,48+64+sz*196 , deinterleave_buf[sz]);
- if (framer->duid == 0x07 && rc[sz] == 0)
- process_duid(framer->duid, framer->nac, deinterleave_buf[sz], 10);
+
+ if (d_debug >= 10) {
+ fprintf(stderr, "ESS: algid=%x, keyid=%x, mi=", ess_algid, ess_keyid);
+ for (int i = 0; i < 9; i++) {
+ fprintf(stderr, "%02x ", ess_mi[i]);
+ }
+ }
+ s = "{\"nac\" : " + std::to_string(framer->nac) + ", \"algid\" : " + std::to_string(ess_algid) + ", \"alg\" : \"" + lookup(ess_algid, ALGIDS, ALGIDS_SZ) + "\", \"keyid\": " + std::to_string(ess_keyid) + "}";
+ send_msg(s, -3);
+ }
+ } else {
+ if (d_debug >= 10) {
+ fprintf (stderr, " (ESS computation suppressed)");
+ }
+ }
+
+ if (d_debug >= 10) {
+ fprintf(stderr, ", Hamming failures=%d of 24, ec=%d", hmg_failures, ec);
+ fprintf (stderr, "\n");
+ }
+
+ if (hmg_failures < 16)
+ process_voice(A);
+}
+
+void
+p25p1_fdma::process_TTDU()
+{
+ process_duid(framer->duid, framer->nac, NULL, 0);
+
+ if ((d_do_imbe || d_do_audio_output) && (framer->duid == 0x3 || framer->duid == 0xf)) { // voice termination
+ op25audio.send_audio_flag(op25_audio::DRAIN);
+ }
+}
+
+void
+p25p1_fdma::process_TDU3()
+{
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x TDU3: ", logts.get(), framer->nac);
+ }
+
+ process_TTDU();
+
+ if (d_debug >= 10) {
+ fprintf (stderr, "\n");
+ }
+}
+
+void
+p25p1_fdma::process_TDU15(const bit_vector& A)
+{
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x TDU15: ", logts.get(), framer->nac);
+ }
+
+ process_TTDU();
+
+ int i, j, k;
+ std::vector<uint8_t> HB(63,0); // hexbit vector
+ k = 0;
+ for (i = 0; i <= 22; i += 2) {
+ uint32_t CW = 0;
+ for (j = 0; j < 12; j++) { // 12 24-bit codewords
+ CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
+ CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
+ }
+ uint32_t D = gly24128Dec(CW);
+ HB[39 + i] = D >> 6;
+ HB[40 + i] = D & 63;
+ }
+ process_LCW(HB);
+
+ if (d_debug >= 10) {
+ fprintf (stderr, "\n");
+ }
+}
+
+void
+p25p1_fdma::process_LCW(std::vector<uint8_t>& HB)
+{
+ int ec = rs12.decode(HB); // Reed Solomon (24,12,13) error correction
+ if (ec < 0) {
+ if (d_debug >= 10)
+ fprintf(stderr, "p25p1_fdma::process_LCW: rs decode failure\n");
+ return; // failed CRC
+ }
+
+ int i, j;
+ std::vector<uint8_t> lcw(9,0); // Convert hexbits to bytes
+ j = 0;
+ for (i = 0; i < 9;) {
+ lcw[i++] = (uint8_t) (HB[j+39] << 2) + (HB[j+40] >> 4);
+ lcw[i++] = (uint8_t) ((HB[j+40] & 0x0f) << 4) + (HB[j+41] >> 2);
+ lcw[i++] = (uint8_t) ((HB[j+41] & 0x03) << 6) + HB[j+42];
+ j += 4;
+ }
+
+ int pb = (lcw[0] >> 7);
+ int sf = ((lcw[0] & 0x40) >> 6);
+ int lco = lcw[0] & 0x3f;
+ std::string s = "";
+
+ if (d_debug >= 10)
+ fprintf(stderr, "LCW: ec=%d, pb=%d, sf=%d, lco=%d", ec, pb, sf, lco);
+
+ char s_msg[9];
+ for (i=0; i<9; i++) {
+ s_msg[i] = lcw[i];
+ }
+ char nac[2];
+ nac[0] = (framer->nac >> 8) & 0xff;
+ nac[1] = (framer->nac ) & 0xff;
+ send_msg(std::string(nac, 2) + std::string(s_msg, 9), -7);
+
+ if (pb == 0) { // only decode if unencrypted
+ if ((sf == 0) && ((lcw[1] == 0x00) || (lcw[1] == 0x01) || (lcw[1] == 0x90))) { // sf=0, explicit MFID in standard or Motorola format
+ switch (lco) {
+ case 0x00: { // Group Voice Channel User
+ uint16_t grpaddr = (lcw[4] << 8) + lcw[5];
+ uint32_t srcaddr = (lcw[6] << 16) + (lcw[7] << 8) + lcw[8];
+ s = "{\"srcaddr\" : " + std::to_string(srcaddr) + ", \"grpaddr\": " + std::to_string(grpaddr) + ", \"nac\" : " + std::to_string(framer->nac) + "}";
+ send_msg(s, -3);
+ if (d_debug >= 10)
+ fprintf(stderr, ", srcaddr=%d, grpaddr=%d", srcaddr, grpaddr);
+ break;
}
}
- // two-block mbt is the only format currently supported
- if (framer->duid == 0x0c
- && framer->frame_size == 576
- && rc[0] == 0
- && rc[1] == 0) {
- // we copy first 10 bytes from first and
- // first 8 from second (removes CRC's)
- uint8_t mbt_block[18];
- memcpy(mbt_block, deinterleave_buf[0], 10);
- memcpy(&mbt_block[10], deinterleave_buf[1], 8);
- process_duid(framer->duid, framer->nac, mbt_block, sizeof(mbt_block));
+ } else if (sf == 1) { // sf=1, implicit MFID
+ switch (lco) {
+ case 0x02: { // Group Voice Channel Update
+ uint16_t ch_A = (lcw[1] << 8) + lcw[2];
+ uint16_t grp_A = (lcw[3] << 8) + lcw[4];
+ uint16_t ch_B = (lcw[5] << 8) + lcw[6];
+ uint16_t grp_B = (lcw[7] << 8) + lcw[8];
+ if (d_debug >= 10)
+ fprintf(stderr, ", ch_A=%d, grp_A=%d, ch_B=%d, grp_B=%d", ch_A, grp_A, ch_B, grp_B);
+ break;
+ }
+ case 0x04: { // Group Voice Channel Update Explicit
+ uint8_t svcopts = (lcw[2] ) ;
+ uint16_t grpaddr = (lcw[3] << 8) + lcw[4];
+ uint16_t ch_T = (lcw[5] << 8) + lcw[6];
+ uint16_t ch_R = (lcw[7] << 8) + lcw[8];
+ if (d_debug >= 10)
+ fprintf(stderr, ", svcopts=0x%02x, grpaddr=%d, ch_T=%d, ch_R=%d", svcopts, grpaddr, ch_T, ch_R);
+ break;
+ }
+
}
}
- if (d_debug >= 10 && framer->duid == 0x00) {
- ProcHDU(framer->frame_body);
- } else if (d_debug > 10 && framer->duid == 0x05) {
- ProcLDU1(framer->frame_body);
- } else if (d_debug >= 10 && framer->duid == 0x0a) {
- ProcLDU2(framer->frame_body);
- } else if (d_debug > 10 && framer->duid == 0x0f) {
- ProcTDU(framer->frame_body);
+ }
+ if (d_debug >= 10) {
+ fprintf(stderr, " : ");
+ for (i = 0; i < 9; i++)
+ fprintf(stderr, " %02x", lcw[i]);
+ }
+}
+
+void
+p25p1_fdma::process_TSBK(const bit_vector& fr, uint32_t fr_len)
+{
+ uint8_t op, lb = 0;
+ block_vector deinterleave_buf;
+ if (process_blocks(fr, fr_len, deinterleave_buf) == 0) {
+ for (int j = 0; (j < deinterleave_buf.size()) && (lb == 0); j++) {
+ if (crc16(deinterleave_buf[j].data(), 12) != 0) // validate CRC
+ return;
+
+ lb = deinterleave_buf[j][0] >> 7; // last block flag
+ op = deinterleave_buf[j][0] & 0x3f; // opcode
+ process_duid(framer->duid, framer->nac, deinterleave_buf[j].data(), 10);
+
+ if (d_debug >= 10) {
+ fprintf (stderr, "%s NAC 0x%03x TSBK: op=%02x : ", logts.get(), framer->nac, op);
+ for (int i = 0; i < 12; i++) {
+ fprintf(stderr, "%02x ", deinterleave_buf[j][i]);
+ }
+ fprintf(stderr, "\n");
+ }
}
- if (d_debug >= 10)
- fprintf(stderr, "\n");
- if ((d_do_imbe || d_do_audio_output) && (framer->duid == 0x5 || framer->duid == 0xa)) { // if voice - ldu1 or ldu2
- for(size_t i = 0; i < nof_voice_codewords; ++i) {
- voice_codeword cw(voice_codeword_sz);
- uint32_t E0, ET;
- uint32_t u[8];
- char s[128];
- imbe_deinterleave(framer->frame_body, cw, i);
- // recover 88-bit IMBE voice code word
- imbe_header_decode(cw, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7], E0, ET);
- // output one 32-byte msg per 0.020 sec.
- // also, 32*9 = 288 byte pkts (for use via UDP)
- sprintf(s, "%03x %03x %03x %03x %03x %03x %03x %03x\n", u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7]);
- if (d_do_audio_output)
- p1voice_decode.rxframe(u);
- if (d_do_output && !d_do_audio_output) {
- for (size_t j=0; j < strlen(s); j++) {
- output_queue.push_back(s[j]);
- }
+ }
+}
+
+void
+p25p1_fdma::process_PDU(const bit_vector& fr, uint32_t fr_len)
+{
+ uint8_t fmt, sap, blks, op = 0;
+ block_vector deinterleave_buf;
+ if ((process_blocks(fr, fr_len, deinterleave_buf) == 0) &&
+ (deinterleave_buf.size() > 0)) { // extract all blocks associated with this PDU
+ if (crc16(deinterleave_buf[0].data(), 12) != 0) // validate PDU header
+ return;
+
+ fmt = deinterleave_buf[0][0] & 0x1f;
+ sap = deinterleave_buf[0][1] & 0x3f;
+ blks = deinterleave_buf[0][6] & 0x7f;
+
+ if ((sap == 61) && ((fmt == 0x17) || (fmt == 0x15))) { // Multi Block Trunking messages
+ if (blks > deinterleave_buf.size())
+ return; // insufficient blocks available
+
+ uint32_t crc1 = crc32(deinterleave_buf[1].data(), ((blks * 12) - 4) * 8);
+ uint32_t crc2 = (deinterleave_buf[blks][8] << 24) + (deinterleave_buf[blks][9] << 16) +
+ (deinterleave_buf[blks][10] << 8) + deinterleave_buf[blks][11];
+
+ if (crc1 != crc2)
+ return; // payload crc check failed
+
+ process_duid(framer->duid, framer->nac, deinterleave_buf[0].data(), ((blks + 1) * 12) - 4);
+
+ if (d_debug >= 10) {
+ if (fmt == 0x15) {
+ op = deinterleave_buf[1][0] & 0x3f; // Unconfirmed MBT format
+ } else if (fmt == 0x17) {
+ op = deinterleave_buf[0][7] & 0x3f; // Alternate MBT format
}
- if (d_do_output && write_sock > 0) {
- memcpy(&write_buf[write_bufp], s, strlen(s));
- write_bufp += strlen(s);
- if (write_bufp >= 288) { // 9 * 32 = 288
- sendto(write_sock, write_buf, 288, 0, (struct sockaddr *)&write_sock_addr, sizeof(write_sock_addr));
- // FIXME check sendto() rc
- write_bufp = 0;
+
+ fprintf (stderr, "%s NAC 0x%03x PDU: fmt=%02x, op=0x%02x : ", logts.get(), framer->nac, fmt, op);
+ for (int j = 0; (j < blks+1) && (j < 3); j++) {
+ for (int i = 0; i < 12; i++) {
+ fprintf(stderr, "%02x ", deinterleave_buf[j][i]);
}
}
+ fprintf(stderr, "\n");
}
- } // end of imbe/voice
- if (!d_do_imbe) {
+ } else if (d_debug >= 10) {
+ fprintf(stderr, "%s NAC 0x%03x PDU: non-MBT message ignored\n", logts.get(), framer->nac);
+ }
+
+ }
+}
+
+int
+p25p1_fdma::process_blocks(const bit_vector& fr, uint32_t& fr_len, block_vector& dbuf)
+{
+ bit_vector bv;
+ bv.reserve(fr_len >> 1);
+ for (unsigned int d=0; d < fr_len >> 1; d++) { // eliminate status bits from frame
+ if ((d+1) % 36 == 0)
+ continue;
+ bv.push_back(fr[d*2]);
+ bv.push_back(fr[d*2+1]);
+ }
+
+ int bl_cnt = 0;
+ int bl_len = (bv.size() - (48+64)) / 196;
+ for (bl_cnt = 0; bl_cnt < bl_len; bl_cnt++) { // deinterleave, decode trellis1_2, save 12 byte block
+ dbuf.push_back({0,0,0,0,0,0,0,0,0,0,0,0});
+ if(block_deinterleave(bv, 48+64+bl_cnt*196, dbuf[bl_cnt].data()) != 0) {
+ dbuf.pop_back();
+ return -1;
+ }
+ }
+ return (bl_cnt > 0) ? 0 : -1;
+}
+
+void
+p25p1_fdma::process_voice(const bit_vector& A)
+{
+ if (d_do_imbe || d_do_audio_output) {
+ for(size_t i = 0; i < nof_voice_codewords; ++i) {
+ voice_codeword cw(voice_codeword_sz);
+ uint32_t E0, ET;
+ uint32_t u[8];
+ char s[128];
+ imbe_deinterleave(A, cw, i);
+ // recover 88-bit IMBE voice code word
+ imbe_header_decode(cw, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7], E0, ET);
+
+ if (d_debug >= 10) {
+ packed_codeword p_cw;
+ imbe_pack(p_cw, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7]);
+ sprintf(s,"%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
+ p_cw[0], p_cw[1], p_cw[2], p_cw[3], p_cw[4], p_cw[5],
+ p_cw[6], p_cw[7], p_cw[8], p_cw[9], p_cw[10]);
+ fprintf(stderr, "%s IMBE %s\n", logts.get(), s); // print to log in one operation
+ }
+ // output one 32-byte msg per 0.020 sec.
+ // also, 32*9 = 288 byte pkts (for use via UDP)
+ sprintf(s, "%03x %03x %03x %03x %03x %03x %03x %03x\n", u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7]);
+ if (d_do_audio_output) {
+ if (!encrypted())
+ p1voice_decode.rxframe(u);
+ }
+
+ if (d_do_output && !d_do_audio_output) {
+ for (size_t j=0; j < strlen(s); j++) {
+ output_queue.push_back(s[j]);
+ }
+ }
+ }
+ }
+}
+
+void
+p25p1_fdma::reset_timer()
+{
+ //update last_qtime with current time
+ gettimeofday(&last_qtime, 0);
+}
+
+void p25p1_fdma::send_msg(const std::string msg_str, long msg_type)
+{
+ unsigned char hdr[4] = {0xaa, 0x55, (unsigned char)((d_msgq_id >> 8) & 0xff), (unsigned char) (d_msgq_id & 0xff)};
+ if (!d_do_msgq || d_msg_queue->full_p())
+ return;
+
+ gr::message::sptr msg = gr::message::make_from_string(std::string((char*)hdr, 4) + msg_str, msg_type, 0, 0);
+ d_msg_queue->insert_tail(msg);
+}
+
+void
+p25p1_fdma::rx_sym (const uint8_t *syms, int nsyms)
+{
+ struct timeval currtime;
+ unsigned char hdr[4] = {0xaa, 0x55, (unsigned char)((d_msgq_id >> 8) & 0xff), (unsigned char) (d_msgq_id & 0xff)};
+ for (int i1 = 0; i1 < nsyms; i1++){
+ if(framer->rx_sym(syms[i1])) { // complete frame was detected
+
+ if (framer->nac == 0) { // discard frame if NAC is invalid
+ return;
+ }
+
+ // extract additional signalling information and voice codewords
+ switch(framer->duid) {
+ case 0x00:
+ process_HDU(framer->frame_body);
+ break;
+ case 0x03:
+ process_TDU3();
+ break;
+ case 0x05:
+ process_LDU1(framer->frame_body);
+ break;
+ case 0x07:
+ process_TSBK(framer->frame_body, framer->frame_size);
+ break;
+ case 0x0a:
+ process_LDU2(framer->frame_body);
+ break;
+ case 0x0c:
+ process_PDU(framer->frame_body, framer->frame_size);
+ break;
+ case 0x0f:
+ process_TDU15(framer->frame_body);
+ break;
+ }
+
+ if (!d_do_imbe) { // send raw frame to wireshark
// pack the bits into bytes, MSB first
size_t obuf_ct = 0;
uint8_t obuf[P25_VOICE_FRAME_SIZE/2];
@@ -355,16 +750,15 @@ p25p1_fdma::rx_sym (const uint8_t *syms, int nsyms)
(framer->frame_body[i+7] );
obuf[obuf_ct++] = b;
}
- if (write_sock > 0) {
- sendto(write_sock, obuf, obuf_ct, 0, (struct sockaddr*)&write_sock_addr, sizeof(write_sock_addr));
- }
+ op25audio.send_to(obuf, obuf_ct);
+
if (d_do_output) {
for (size_t j=0; j < obuf_ct; j++) {
output_queue.push_back(obuf[j]);
}
}
}
- } // end of complete frame
+ } // end of complete frame
}
if (d_do_msgq && !d_msg_queue->full_p()) {
// check for timeout
@@ -377,31 +771,19 @@ p25p1_fdma::rx_sym (const uint8_t *syms, int nsyms)
}
diff_usec += diff_sec * 1000000;
if (diff_usec >= TIMEOUT_THRESHOLD) {
+ if (d_debug > 0)
+ fprintf(stderr, "%010lu.%06lu p25p1_fdma::rx_sym() timeout, channel %d\n", currtime.tv_sec, currtime.tv_usec, d_msgq_id);
+
+ if (d_do_audio_output) {
+ op25audio.send_audio_flag(op25_audio::DRAIN);
+ }
+
gettimeofday(&last_qtime, 0);
- gr::message::sptr msg = gr::message::make(-1, 0, 0);
+ gr::message::sptr msg = gr::message::make_from_string(std::string((char*)hdr, 4), -1, 0, 0);
d_msg_queue->insert_tail(msg);
}
}
}
-void p25p1_fdma::init_sock(const char* udp_host, int udp_port)
-{
- memset (&write_sock_addr, 0, sizeof(write_sock_addr));
- write_sock = socket(PF_INET, SOCK_DGRAM, 17); // UDP socket
- if (write_sock < 0) {
- fprintf(stderr, "op25_imbe_vocoder: socket: %d\n", errno);
- write_sock = 0;
- return;
- }
- if (!inet_aton(udp_host, &write_sock_addr.sin_addr)) {
- fprintf(stderr, "op25_imbe_vocoder: inet_aton: bad IP address\n");
- close(write_sock);
- write_sock = 0;
- return;
- }
- write_sock_addr.sin_family = AF_INET;
- write_sock_addr.sin_port = htons(udp_port);
-}
-
} // namespace
} // namespace
diff --git a/op25/gr-op25_repeater/lib/p25p1_fdma.h b/op25/gr-op25_repeater/lib/p25p1_fdma.h
index 3595699..e5f3292 100644
--- a/op25/gr-op25_repeater/lib/p25p1_fdma.h
+++ b/op25/gr-op25_repeater/lib/p25p1_fdma.h
@@ -22,12 +22,13 @@
#define INCLUDED_OP25_REPEATER_P25P1_FDMA_H
#include <gnuradio/msg_queue.h>
-#include <sys/socket.h>
#include <sys/time.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
#include <deque>
+#include "ezpwd/rs"
+
+#include "log_ts.h"
+#include "op25_audio.h"
#include "p25_framer.h"
#include "p25p1_voice_encode.h"
#include "p25p1_voice_decode.h"
@@ -37,37 +38,59 @@ namespace gr {
class p25p1_fdma
{
private:
-
- void init_sock(const char* udp_host, int udp_port);
+ typedef std::vector<bool> bit_vector;
+ typedef std::array<uint8_t, 12> block_array;
+ typedef std::vector<block_array> block_vector;
// internal functions
- typedef std::vector<bool> bit_vector;
bool header_codeword(uint64_t acc, uint32_t& nac, uint32_t& duid);
- void proc_voice_unit(bit_vector& frame_body) ;
- void process_duid(uint32_t const duid, uint32_t const nac, uint8_t const buf[], int const len);
+ void process_duid(uint32_t const duid, uint32_t const nac, const uint8_t* buf, const int len);
+ void process_HDU(const bit_vector& A);
+ void process_LCW(std::vector<uint8_t>& HB);
+ int process_LLDU(const bit_vector& A, std::vector<uint8_t>& HB);
+ void process_LDU1(const bit_vector& A);
+ void process_LDU2(const bit_vector& A);
+ void process_TTDU();
+ void process_TDU15(const bit_vector& A);
+ void process_TDU3();
+ void process_TSBK(const bit_vector& fr, uint32_t fr_len);
+ void process_PDU(const bit_vector& fr, uint32_t fr_len);
+ void process_voice(const bit_vector& A);
+ int process_blocks(const bit_vector& fr, uint32_t& fr_len, block_vector& dbuf);
+ inline bool encrypted() { return (ess_algid != 0x80); }
+ void send_msg(const std::string msg_str, long msg_type);
+
// internal instance variables and state
int write_bufp;
- int write_sock;
- struct sockaddr_in write_sock_addr;
char write_buf[512];
- const char* d_udp_host;
- int d_port;
int d_debug;
bool d_do_imbe;
bool d_do_output;
bool d_do_msgq;
+ bool d_do_audio_output;
gr::msg_queue::sptr d_msg_queue;
std::deque<int16_t> &output_queue;
p25_framer* framer;
struct timeval last_qtime;
- bool d_do_audio_output;
p25p1_voice_decode p1voice_decode;
+ const op25_audio& op25audio;
+ log_ts logts;
+
+ ezpwd::RS<63,55> rs8; // Reed-Solomon decoders for 8, 12 and 16 bit parity
+ ezpwd::RS<63,51> rs12;
+ ezpwd::RS<63,47> rs16;
+
+ uint16_t ess_keyid;
+ uint16_t ess_algid;
+ uint8_t ess_mi[9] = {0};
+ uint16_t vf_tgid;
+ int d_msgq_id;
public:
void reset_timer();
void rx_sym (const uint8_t *syms, int nsyms);
- p25p1_fdma(const char* udp_host, int port, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &output_queue, bool do_audio_output);
- ~p25p1_fdma();
+ p25p1_fdma(const op25_audio& udp, int debug, bool do_imbe, bool do_output, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &output_queue, bool do_audio_output, int msgq_id);
+ ~p25p1_fdma();
// Where all the action really happens
diff --git a/op25/gr-op25_repeater/lib/p25p1_voice_decode.cc b/op25/gr-op25_repeater/lib/p25p1_voice_decode.cc
index 798b373..bf30b4f 100644
--- a/op25/gr-op25_repeater/lib/p25p1_voice_decode.cc
+++ b/op25/gr-op25_repeater/lib/p25p1_voice_decode.cc
@@ -50,18 +50,13 @@ static void clear_bits(bit_vector& v) {
}
}
-p25p1_voice_decode::p25p1_voice_decode(bool verbose_flag, const char* udp_host, int udp_port, std::deque<int16_t> &_output_queue) :
- write_sock(0),
+p25p1_voice_decode::p25p1_voice_decode(bool verbose_flag, const op25_audio& udp, std::deque<int16_t> &_output_queue) :
+ op25audio(udp),
write_bufp(0),
rxbufp(0),
output_queue(_output_queue),
- opt_verbose(verbose_flag),
- opt_udp_port(udp_port)
+ opt_verbose(verbose_flag)
{
- if (opt_udp_port != 0)
- // remote UDP output
- init_sock(udp_host, opt_udp_port);
-
const char *p = getenv("IMBE");
if (p && strcasecmp(p, "soft") == 0)
d_software_imbe_decoder = true;
@@ -101,8 +96,8 @@ void p25p1_voice_decode::rxframe(const uint32_t u[])
/* TEST*/ frame_vector[7] >>= 1;
vocoder.imbe_decode(frame_vector, snd);
}
- if (opt_udp_port > 0) {
- sendto(write_sock, snd, FRAME * sizeof(int16_t), 0, (struct sockaddr*)&write_sock_addr, sizeof(write_sock_addr));
+ if (op25audio.enabled()) {
+ op25audio.send_audio(snd, FRAME * sizeof(int16_t));
} else {
// add generated samples to output queue
for (int i = 0; i < FRAME; i++) {
@@ -132,24 +127,5 @@ void p25p1_voice_decode::rxchar(const char* c, int len)
} /* end of for() */
}
-void p25p1_voice_decode::init_sock(const char* udp_host, int udp_port)
-{
- memset (&write_sock_addr, 0, sizeof(write_sock_addr));
- write_sock = socket(PF_INET, SOCK_DGRAM, 17); // UDP socket
- if (write_sock < 0) {
- fprintf(stderr, "vocoder: socket: %d\n", errno);
- write_sock = 0;
- return;
- }
- if (!inet_aton(udp_host, &write_sock_addr.sin_addr)) {
- fprintf(stderr, "vocoder: bad IP address\n");
- close(write_sock);
- write_sock = 0;
- return;
- }
- write_sock_addr.sin_family = AF_INET;
- write_sock_addr.sin_port = htons(udp_port);
-}
-
} /* namespace op25_repeater */
} /* namespace gr */
diff --git a/op25/gr-op25_repeater/lib/p25p1_voice_decode.h b/op25/gr-op25_repeater/lib/p25p1_voice_decode.h
index 9c49b9d..159cba6 100644
--- a/op25/gr-op25_repeater/lib/p25p1_voice_decode.h
+++ b/op25/gr-op25_repeater/lib/p25p1_voice_decode.h
@@ -22,11 +22,11 @@
#define INCLUDED_OP25_REPEATER_P25P1_VOICE_DECODE_H
#include <sys/time.h>
-#include <netinet/in.h>
#include <stdint.h>
#include <vector>
#include <deque>
+#include "op25_audio.h"
#include "imbe_vocoder/imbe_vocoder.h"
#include "imbe_decoder.h"
@@ -42,7 +42,7 @@ namespace gr {
// Nothing to declare in this block.
public:
- p25p1_voice_decode(bool verbose_flag, const char* udp_host, int udp_port, std::deque<int16_t> &_output_queue);
+ p25p1_voice_decode(bool verbose_flag, const op25_audio& udp, std::deque<int16_t> &_output_queue);
~p25p1_voice_decode();
void rxframe(const uint32_t u[]);
void rxchar(const char* c, int len);
@@ -51,8 +51,6 @@ namespace gr {
static const int RXBUF_MAX = 80;
/* data items */
- int write_sock;
- struct sockaddr_in write_sock_addr;
int write_bufp;
char write_buf[512];
char rxbuf[RXBUF_MAX];
@@ -60,13 +58,12 @@ namespace gr {
imbe_vocoder vocoder;
software_imbe_decoder software_decoder;
bool d_software_imbe_decoder;
+ const op25_audio& op25audio;
std::deque<int16_t> &output_queue;
bool opt_verbose;
- int opt_udp_port;
/* local methods */
- void init_sock(const char* udp_host, int udp_port);
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/lib/p25p1_voice_encode.cc b/op25/gr-op25_repeater/lib/p25p1_voice_encode.cc
index f2ca445..d2fda13 100644
--- a/op25/gr-op25_repeater/lib/p25p1_voice_encode.cc
+++ b/op25/gr-op25_repeater/lib/p25p1_voice_encode.cc
@@ -33,9 +33,6 @@
#include <stdio.h>
#include <string.h>
#include <errno.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
#include "imbe_vocoder/imbe_vocoder.h"
#include "p25_frame.h"
@@ -153,9 +150,9 @@ static void clear_bits(bit_vector& v) {
}
}
-p25p1_voice_encode::p25p1_voice_encode(bool verbose_flag, int stretch_amt, char* udp_host, int udp_port, bool raw_vectors_flag, std::deque<uint8_t> &_output_queue) :
+p25p1_voice_encode::p25p1_voice_encode(bool verbose_flag, int stretch_amt, const op25_audio& udp, bool raw_vectors_flag, std::deque<uint8_t> &_output_queue) :
+ op25audio(udp),
frame_cnt(0),
- write_sock(0),
write_bufp(0),
peak_amplitude(0),
peak(0),
@@ -166,8 +163,7 @@ p25p1_voice_encode::p25p1_voice_encode(bool verbose_flag, int stretch_amt, char*
output_queue(_output_queue),
f_body(P25_VOICE_FRAME_SIZE),
opt_dump_raw_vectors(raw_vectors_flag),
- opt_verbose(verbose_flag),
- opt_udp_port(udp_port)
+ opt_verbose(verbose_flag)
{
opt_stretch_amt = 0;
if (stretch_amt < 0) {
@@ -178,10 +174,6 @@ p25p1_voice_encode::p25p1_voice_encode(bool verbose_flag, int stretch_amt, char*
opt_stretch_amt = stretch_amt;
}
- if (opt_udp_port != 0)
- // remote UDP output
- init_sock(udp_host, opt_udp_port);
-
clear_bits(f_body);
}
@@ -216,7 +208,7 @@ void p25p1_voice_encode::append_imbe_codeword(bit_vector& frame_body, int16_t fr
frame_body[i] = frame_body[i] | ldu_preset[i];
}
// finally, output the frame
- if (opt_udp_port > 0) {
+ if (op25audio.enabled()) {
// pack the bits into bytes, MSB first
size_t obuf_ct = 0;
for (uint32_t i = 0; i < P25_VOICE_FRAME_SIZE; i += 8) {
@@ -231,7 +223,7 @@ void p25p1_voice_encode::append_imbe_codeword(bit_vector& frame_body, int16_t fr
(frame_body[i+7] );
obuf[obuf_ct++] = b;
}
- sendto(write_sock, obuf, obuf_ct, 0, (struct sockaddr*)&write_sock_addr, sizeof(write_sock_addr));
+ op25audio.send_to(obuf, obuf_ct);
} else {
for (uint32_t i = 0; i < P25_VOICE_FRAME_SIZE; i += 2) {
uint8_t dibit =
@@ -274,7 +266,7 @@ void p25p1_voice_encode::compress_frame(int16_t snd[])
memcpy(&write_buf[write_bufp], s, strlen(s));
write_bufp += strlen(s);
if (write_bufp >= 288) {
- sendto(write_sock, write_buf, 288, 0, (struct sockaddr*)&write_sock_addr, sizeof(write_sock_addr));
+ op25audio.send_to(write_buf, 288);
write_bufp = 0;
}
return;
@@ -324,28 +316,10 @@ void p25p1_voice_encode::compress_samp(const int16_t * samp, int len)
}
}
-void p25p1_voice_encode::init_sock(char* udp_host, int udp_port)
-{
- memset (&write_sock_addr, 0, sizeof(write_sock_addr));
- write_sock = socket(PF_INET, SOCK_DGRAM, 17); // UDP socket
- if (write_sock < 0) {
- fprintf(stderr, "vocoder: socket: %d\n", errno);
- write_sock = 0;
- return;
- }
- if (!inet_aton(udp_host, &write_sock_addr.sin_addr)) {
- fprintf(stderr, "vocoder: bad IP address\n");
- close(write_sock);
- write_sock = 0;
- return;
- }
- write_sock_addr.sin_family = AF_INET;
- write_sock_addr.sin_port = htons(udp_port);
-}
-
void
p25p1_voice_encode::set_gain_adjust(float gain_adjust) {
vocoder.set_gain_adjust(gain_adjust);
}
+
} /* namespace op25_repeater */
} /* namespace gr */
diff --git a/op25/gr-op25_repeater/lib/p25p1_voice_encode.h b/op25/gr-op25_repeater/lib/p25p1_voice_encode.h
index e3663ec..379eda5 100644
--- a/op25/gr-op25_repeater/lib/p25p1_voice_encode.h
+++ b/op25/gr-op25_repeater/lib/p25p1_voice_encode.h
@@ -22,11 +22,11 @@
#define INCLUDED_OP25_REPEATER_P25P1_VOICE_ENCODE_H
#include <sys/time.h>
-#include <netinet/in.h>
#include <stdint.h>
#include <vector>
#include <deque>
+#include "op25_audio.h"
#include "imbe_vocoder/imbe_vocoder.h"
#include "imbe_decoder.h"
@@ -42,7 +42,7 @@ namespace gr {
// Nothing to declare in this block.
public:
- p25p1_voice_encode(bool verbose_flag, int stretch_amt, char* udp_host, int udp_port, bool raw_vectors_flag, std::deque<uint8_t> &_output_queue);
+ p25p1_voice_encode(bool verbose_flag, int stretch_amt, const op25_audio& udp, bool raw_vectors_flag, std::deque<uint8_t> &_output_queue);
~p25p1_voice_encode();
void compress_samp(const int16_t * samp, int len);
void set_gain_adjust(float gain_adjust);
@@ -51,8 +51,6 @@ namespace gr {
/* data items */
int frame_cnt ;
- int write_sock;
- struct sockaddr_in write_sock_addr;
int write_bufp;
char write_buf[512];
struct timeval tv;
@@ -68,6 +66,7 @@ namespace gr {
int stretch_count ;
bit_vector f_body;
imbe_vocoder vocoder;
+ const op25_audio& op25audio;
std::deque<uint8_t> &output_queue;
@@ -75,12 +74,10 @@ namespace gr {
bool opt_verbose;
int opt_stretch_amt;
int opt_stretch_sign;
- int opt_udp_port;
/* local methods */
void append_imbe_codeword(bit_vector& frame_body, int16_t frame_vector[], unsigned int& codeword_ct);
void compress_frame(int16_t snd[]);
void add_sample(int16_t samp);
- void init_sock(char* udp_host, int udp_port);
};
} // namespace op25_repeater
diff --git a/op25/gr-op25_repeater/lib/p25p2_framer.cc b/op25/gr-op25_repeater/lib/p25p2_framer.cc
index 819603d..7de5431 100644
--- a/op25/gr-op25_repeater/lib/p25p2_framer.cc
+++ b/op25/gr-op25_repeater/lib/p25p2_framer.cc
@@ -8,7 +8,7 @@
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>
-#include <p25p2_framer.h>
+#include "p25p2_framer.h"
#include "check_frame_sync.h"
diff --git a/op25/gr-op25_repeater/lib/p25p2_tdma.cc b/op25/gr-op25_repeater/lib/p25p2_tdma.cc
index 8bc1afe..18c04e6 100644
--- a/op25/gr-op25_repeater/lib/p25p2_tdma.cc
+++ b/op25/gr-op25_repeater/lib/p25p2_tdma.cc
@@ -1,4 +1,5 @@
-// P25 TDMA Decoder (C) Copyright 2013, 2014 Max H. Parke KA1RBI
+// P25 TDMA Decoder (C) Copyright 2013, 2014, 2021 Max H. Parke KA1RBI
+// Copyright 2017 Graham J. Norbury (modularization rewrite)
//
// This file is part of OP25
//
@@ -24,6 +25,7 @@
#include <iostream>
#include <assert.h>
#include <errno.h>
+#include <sys/time.h>
#include "p25p2_duid.h"
#include "p25p2_sync.h"
@@ -31,9 +33,12 @@
#include "p25p2_vf.h"
#include "mbelib.h"
#include "ambe.h"
+#include "value_string.h"
+#include "crc16.h"
static const int BURST_SIZE = 180;
static const int SUPERFRAME_SIZE = (12*BURST_SIZE);
+static const int which_slot[] = {0,1,0,1,0,1,0,1,0,1,1,0};
static uint16_t crc12(const uint8_t bits[], unsigned int len) {
uint16_t crc=0;
@@ -66,23 +71,28 @@ static bool crc12_ok(const uint8_t bits[], unsigned int len) {
return (crc == crc12(bits,len));
}
-p25p2_tdma::p25p2_tdma(const char* udp_host, int port, int slotid, int debug, std::deque<int16_t> &qptr) : // constructor
+p25p2_tdma::p25p2_tdma(const op25_audio& udp, int slotid, int debug, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &qptr, bool do_audio_output, int msgq_id) : // constructor
+ op25audio(udp),
write_bufp(0),
- write_sock(0),
- d_udp_host(udp_host),
- d_port(port),
tdma_xormask(new uint8_t[SUPERFRAME_SIZE]),
symbols_received(0),
packets(0),
d_slotid(slotid),
+ d_nac(0),
+ d_do_msgq(do_msgq),
+ d_msg_queue(queue),
output_queue_decode(qptr),
d_debug(debug),
- crc_errors(0),
+ d_do_audio_output(do_audio_output),
+ burst_id(-1),
+ ESS_A(28,0),
+ ESS_B(16,0),
+ ess_algid(0x80),
+ ess_keyid(0),
+ d_msgq_id(msgq_id),
p2framer()
{
- if (port > 0)
- init_sock(d_udp_host, d_port);
-
+ memset(tdma_xormask, 0, SUPERFRAME_SIZE);
assert (slotid == 0 || slotid == 1);
mbe_initMbeParms (&cur_mp, &prev_mp, &enh_mp);
}
@@ -101,9 +111,6 @@ void p25p2_tdma::set_slotid(int slotid)
p25p2_tdma::~p25p2_tdma() // destructor
{
- if (write_sock > 0)
- close(write_sock);
-
delete[](tdma_xormask);
}
@@ -113,77 +120,220 @@ p25p2_tdma::set_xormask(const char*p) {
tdma_xormask[i] = p[i] & 3;
}
-int p25p2_tdma::process_mac_pdu(const uint8_t byte_buf[], unsigned int len)
+int p25p2_tdma::process_mac_pdu(const uint8_t byte_buf[], const unsigned int len)
{
unsigned int opcode = (byte_buf[0] >> 5) & 0x7;
unsigned int offset = (byte_buf[0] >> 2) & 0x7;
+ bool my_slot = (which_slot[sync.tdma_slotid()] == d_slotid);
+
+ if (d_debug >= 10) {
+ fprintf(stderr, "%s process_mac_pdu: opcode %d len %d buf %02x %02x %02x\n", logts.get(), opcode, len, byte_buf[0], byte_buf[1], byte_buf[2]);
+ }
+
+ if (opcode == 2) { // MAC_END_PTT
+ uint16_t colorcd = ((byte_buf[1] & 0x0f) << 8) + byte_buf[2];
+ if (colorcd != d_nac && d_debug > 0)
+ fprintf(stderr, "p25p2_tdma_ process_mac_pdu: MAC_END_PTT color code 0x%x does not match d_nac 0x%x channel %d\n", colorcd, d_nac, d_msgq_id);
+ }
+
+ if (opcode == 3 || opcode == 4 || opcode == 6) { // send msg for MAC_IDLE, MAC_ACTIVE, MAC_HANGTIME
+ char nac_color[2];
+ nac_color[0] = d_nac >> 8;
+ nac_color[1] = d_nac & 0xff;
+ send_msg(std::string(nac_color, 2) + std::string((const char *)byte_buf, len), -6);
+ }
+
+ if (opcode != 0 && !my_slot) // for all except MAC_SIGNAL, ignore if on oppo. slot
+ return -1;
+
+ switch (opcode)
+ {
+ case 0: // MAC_SIGNAL
+ handle_mac_signal(byte_buf, len);
+ return -1;
+ break;
+
+ case 1: // MAC_PTT
+ handle_mac_ptt(byte_buf, len);
+ break;
+
+ case 2: // MAC_END_PTT
+ handle_mac_end_ptt(byte_buf, len);
+ break;
+
+ case 3: // MAC_IDLE
+ op25audio.send_audio_flag(op25_audio::DRAIN);
+ break;
+
+ case 4: // MAC_ACTIVE
+ break;
+
+ case 6: // MAC_HANGTIME
+ op25audio.send_audio_flag(op25_audio::DRAIN);
+ break;
+ default:
+ if (d_debug > 0)
+ fprintf(stderr, "p25p2_tdma_ process_mac_pdu: unrecognized opcode 0x%x channel %d\n", opcode, d_msgq_id);
+ break;
+ }
// maps sacch opcodes into phase I duid values
- // 0, 5, 7 - Reserved
- // 1 - MAC_PTT
- // 2 - MAC_END_PTT
- // 3 - MAC_IDLE
- // 4 - MAC_ACTIVE
- // 6 - MAC_HANGTIME
- static const int opcode_map[8] = {3, 5, 15, 15, 5, 3, 3, 3};
+ static const int opcode_map[8] = {7, 5, 15, 15, 5, 3, 3, 3};
return opcode_map[opcode];
- // TODO: decode MAC PDU's
}
-int p25p2_tdma::handle_acch_frame(const uint8_t dibits[], bool fast)
+void p25p2_tdma::handle_mac_signal(const uint8_t byte_buf[], const unsigned int len)
{
- int rc = -1;
+ char nac_color[2];
+ int i;
+ i = (byte_buf[19] << 4) + ((byte_buf[20] >> 4) & 0xf);
+ nac_color[0] = i >> 8;
+ nac_color[1] = i & 0xff;
+ send_msg(std::string(nac_color, 2) + std::string((const char *)byte_buf, len), -6);
+}
+
+void p25p2_tdma::handle_mac_ptt(const uint8_t byte_buf[], const unsigned int len)
+{
+ uint32_t srcaddr = (byte_buf[13] << 16) + (byte_buf[14] << 8) + byte_buf[15];
+ uint16_t grpaddr = (byte_buf[16] << 8) + byte_buf[17];
+ std::string s = "{\"srcaddr\" : " + std::to_string(srcaddr) + ", \"grpaddr\": " + std::to_string(grpaddr) + ", \"nac\" : " + std::to_string(d_nac) + "}";
+ send_msg(s, -3);
+
+ if (d_debug >= 10) {
+ fprintf(stderr, "%s MAC_PTT: srcaddr=%u, grpaddr=%u", logts.get(), srcaddr, grpaddr);
+ }
+ for (int i = 0; i < 9; i++) {
+ ess_mi[i] = byte_buf[i+1];
+ }
+ ess_algid = byte_buf[10];
+ ess_keyid = (byte_buf[11] << 8) + byte_buf[12];
+
+ if (ess_algid == 0) { // workaround spurious algid
+ ess_algid = 128; // unenc
+ if (d_debug)
+ fprintf(stderr, "***mac_ptt detected zero algid, msgq_id %d***\n", d_msgq_id);
+ }
+
+ if (d_debug >= 10) {
+ fprintf(stderr, ", algid=%x, keyid=%x, mi=", ess_algid, ess_keyid);
+ for (int i = 0; i < 9; i++) {
+ fprintf(stderr,"%02x ", ess_mi[i]);
+ }
+ }
+ s = "{\"nac\" : " + std::to_string(d_nac) + ", \"algid\" : " + std::to_string(ess_algid) + ", \"alg\" : \"" + lookup(ess_algid, ALGIDS, ALGIDS_SZ) + "\", \"keyid\": " + std::to_string(ess_keyid) + "}";
+ send_msg(s, -3);
+
+ if (d_debug >= 10) {
+ fprintf(stderr, "\n");
+ }
+
+ reset_vb();
+}
+
+void p25p2_tdma::handle_mac_end_ptt(const uint8_t byte_buf[], const unsigned int len)
+{
+ uint16_t colorcd = ((byte_buf[1] & 0x0f) << 8) + byte_buf[2];
+ uint32_t srcaddr = (byte_buf[13] << 16) + (byte_buf[14] << 8) + byte_buf[15];
+ uint16_t grpaddr = (byte_buf[16] << 8) + byte_buf[17];
+
+ if (d_debug >= 10)
+ fprintf(stderr, "%s MAC_END_PTT: colorcd=0x%03x, srcaddr=%u, grpaddr=%u\n", logts.get(), colorcd, srcaddr, grpaddr);
+
+ //std::string s = "{\"srcaddr\" : " + std::to_string(srcaddr) + ", \"grpaddr\": " + std::to_string(grpaddr) + "}";
+ //send_msg(s, -3); // can cause data display issues if this message is processed after the DUID15
+ op25audio.send_audio_flag(op25_audio::DRAIN);
+}
+
+int p25p2_tdma::handle_acch_frame(const uint8_t dibits[], bool fast, bool is_lcch)
+{
+ int i, j, rc;
uint8_t bits[512];
+ std::vector<uint8_t> HB(63,0);
+ std::vector<int> Erasures;
uint8_t byte_buf[32];
unsigned int bufl=0;
unsigned int len=0;
if (fast) {
- for (int i=11; i < 11+36; i++) {
+ for (i=11; i < 11+36; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
- for (int i=48; i < 48+31; i++) {
+ for (i=48; i < 48+31; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
- for (int i=100; i < 100+32; i++) {
+ for (i=100; i < 100+32; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
- for (int i=133; i < 133+36; i++) {
+ for (i=133; i < 133+36; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
} else {
- for (int i=11; i < 11+36; i++) {
+ for (i=11; i < 11+36; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
- for (int i=48; i < 48+84; i++) {
+ for (i=48; i < 48+84; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
- for (int i=133; i < 133+36; i++) {
+ for (i=133; i < 133+36; i++) {
bits[bufl++] = (dibits[i] >> 1) & 1;
bits[bufl++] = dibits[i] & 1;
}
}
- // FIXME: TODO: add RS decode
- if (fast)
+
+ // Reed-Solomon
+ if (fast) {
+ j = 9;
+ len = 270;
+ Erasures = {0,1,2,3,4,5,6,7,8,54,55,56,57,58,59,60,61,62};
+ }
+ else {
+ j = 5;
+ len = 312;
+ Erasures = {0,1,2,3,4,57,58,59,60,61,62};
+ }
+
+ for (i = 0; i < len; i += 6) { // convert bits to hexbits
+ HB[j] = (bits[i] << 5) + (bits[i+1] << 4) + (bits[i+2] << 3) + (bits[i+3] << 2) + (bits[i+4] << 1) + bits[i+5];
+ j++;
+ }
+ rc = rs28.decode(HB, Erasures);
+// if (d_debug >= 10)
+// fprintf(stderr, "p25p2_tdma: rc28: rc %d\n", rc);
+ if (rc < 0)
+ return -1;
+
+ if (fast) {
+ j = 9;
len = 144;
- else
- len = 168;
- if (crc12_ok(bits, len)) {
- for (int i=0; i<len/8; i++) {
+ }
+ else {
+ j = 5;
+ len = (is_lcch) ? 180 : 168;
+ }
+ for (i = 0; i < len; i += 6) { // convert hexbits back to bits
+ bits[i] = (HB[j] & 0x20) >> 5;
+ bits[i+1] = (HB[j] & 0x10) >> 4;
+ bits[i+2] = (HB[j] & 0x08) >> 3;
+ bits[i+3] = (HB[j] & 0x04) >> 2;
+ bits[i+4] = (HB[j] & 0x02) >> 1;
+ bits[i+5] = (HB[j] & 0x01);
+ j++;
+ }
+
+ bool crc_ok = (is_lcch) ? (crc16(bits, len) == 0) : crc12_ok(bits, len);
+ int olen = (is_lcch) ? 23 : len/8;
+ if (d_debug >= 10)
+ fprintf(stderr, "p25p2_tdma: crc%d result: %s, length %d\n", (is_lcch) ? 16 : 12, (crc_ok) ? "ok" : "failed", olen);
+ rc = -1;
+ if (crc_ok) { // TODO: rewrite crc12 so we don't have to do so much bit manipulation
+ for (int i=0; i<olen; i++) {
byte_buf[i] = (bits[i*8 + 0] << 7) + (bits[i*8 + 1] << 6) + (bits[i*8 + 2] << 5) + (bits[i*8 + 3] << 4) + (bits[i*8 + 4] << 3) + (bits[i*8 + 5] << 2) + (bits[i*8 + 6] << 1) + (bits[i*8 + 7] << 0);
}
- rc = process_mac_pdu(byte_buf, len/8);
- } else {
- crc_errors++;
- }
- // write a zero audio sample (2 bytes) at end of voice to trigger pcm drain
- if (((rc == 3) || (rc == 15)) && (write_sock > 0)) {
- memset(write_buf, 0, 2);
- sendto(write_sock, write_buf, 2, 0, (struct sockaddr *)&write_sock_addr, sizeof(write_sock_addr));
+ rc = process_mac_pdu(byte_buf, olen);
}
return rc;
}
@@ -197,7 +347,7 @@ void p25p2_tdma::handle_voice_frame(const uint8_t dibits[])
int rc = -1;
vf.process_vcw(dibits, b);
- if (b[0] < 120)
+ if (b[0] < 120) // anything above 120 is an erasure or special frame
rc = mbe_dequantizeAmbe2250Parms (&cur_mp, &prev_mp, b);
/* FIXME: check RC */
K = 12;
@@ -216,15 +366,10 @@ void p25p2_tdma::handle_voice_frame(const uint8_t dibits[])
}
write_buf[write_bufp++] = snd & 0xFF ;
write_buf[write_bufp++] = snd >> 8;
-#if 0
- output_queue_decode.push_back(snd);
-#endif
}
- if (write_sock > 0) {
- if (write_bufp >= 0) {
- sendto(write_sock, write_buf, write_bufp, 0, (struct sockaddr *)&write_sock_addr, sizeof(write_sock_addr));
- write_bufp = 0;
- }
+ if (d_do_audio_output && (write_bufp >= 0)) {
+ op25audio.send_audio(write_buf, write_bufp);
+ write_bufp = 0;
}
mbe_moveMbeParms (&cur_mp, &prev_mp);
@@ -241,42 +386,61 @@ int p25p2_tdma::handle_frame(void)
return rc;
}
+static inline bool null_codeword(const uint8_t*bp) {
+ static const int l = 36; // dibits per voice frame
+ for (int i=0; i<l; i++) {
+ if (bp[i])
+ return false;
+ }
+ return true;
+}
+
/* returns true if in sync and slot matches current active slot d_slotid */
int p25p2_tdma::handle_packet(const uint8_t dibits[])
{
int rc = -1;
- static const int which_slot[] = {0,1,0,1,0,1,0,1,0,1,1,0};
packets++;
sync.check_confidence(dibits);
if (!sync.in_sync())
return -1;
const uint8_t* burstp = &dibits[10];
uint8_t xored_burst[BURST_SIZE - 10];
+ bool my_slot = (which_slot[sync.tdma_slotid()] == d_slotid);
int burst_type = duid.duid_lookup(duid.extract_duid(burstp));
- if (which_slot[sync.tdma_slotid()] != d_slotid) // active slot?
- return -1;
for (int i=0; i<BURST_SIZE - 10; i++) {
xored_burst[i] = burstp[i] ^ tdma_xormask[sync.tdma_slotid() * BURST_SIZE + i];
}
- if (d_debug) {
- fprintf(stderr, "p25p2_tdma: burst type %d symbols %u packets %u\n", burst_type, symbols_received, packets);
+ if (d_debug >= 10) {
+ fprintf(stderr, "%s TDMA burst type=%d\n", logts.get(), burst_type);
}
- if (burst_type == 0 || burst_type == 6) { // 4v or 2v (voice) ?
- handle_voice_frame(&xored_burst[11]);
- handle_voice_frame(&xored_burst[48]);
- if (burst_type == 0) { // 4v ?
- handle_voice_frame(&xored_burst[96]);
- handle_voice_frame(&xored_burst[133]);
- }
+ if (burst_type == 0 || burst_type == 6) { // 4V or 2V burst
+ if (!my_slot) // ignore if on oppo. slot
+ return -1;
+ track_vb(burst_type);
+ handle_4V2V_ess(&xored_burst[84]);
+ if ( !encrypted() ) {
+ if(!null_codeword(&burstp[11]))
+ handle_voice_frame(&xored_burst[11]);
+ if(!null_codeword(&burstp[48]))
+ handle_voice_frame(&xored_burst[48]);
+ if (burst_type == 0) {
+ if(!null_codeword(&burstp[96]))
+ handle_voice_frame(&xored_burst[96]);
+ if(!null_codeword(&burstp[133]))
+ handle_voice_frame(&xored_burst[133]);
+ }
+ }
return -1;
- } else if (burst_type == 3) { // scrambled sacch
- rc = handle_acch_frame(xored_burst, 0);
- } else if (burst_type == 9) { // scrambled facch
- rc = handle_acch_frame(xored_burst, 1);
- } else if (burst_type == 12) { // unscrambled sacch
- rc = handle_acch_frame(burstp, 0);
- } else if (burst_type == 15) { // unscrambled facch
- rc = handle_acch_frame(burstp, 1);
+ } else if (burst_type == 3) { // scrambled sacch
+ rc = handle_acch_frame(xored_burst, 0, false);
+ } else if (burst_type == 9) { // scrambled facch
+ rc = handle_acch_frame(xored_burst, 1, false);
+ } else if (burst_type == 12) { // unscrambled sacch
+ rc = handle_acch_frame(burstp, 0, false);
+ } else if (burst_type == 13) { // TDMA CC OECI
+ rc = handle_acch_frame(burstp, 0, true);
+ } else if (burst_type == 15) { // unscrambled facch
+ rc = handle_acch_frame(burstp, 1, false);
} else {
// unsupported type duid
return -1;
@@ -284,22 +448,66 @@ int p25p2_tdma::handle_packet(const uint8_t dibits[])
return rc;
}
-void p25p2_tdma::init_sock(const char* udp_host, int udp_port)
+void p25p2_tdma::handle_4V2V_ess(const uint8_t dibits[])
{
- memset (&write_sock_addr, 0, sizeof(write_sock_addr));
- write_sock = socket(PF_INET, SOCK_DGRAM, 17); // UDP socket
- if (write_sock < 0) {
- fprintf(stderr, "op25_ambe_vocoder: socket: %d\n", errno);
- write_sock = 0;
- return;
- }
- if (!inet_aton(udp_host, &write_sock_addr.sin_addr)) {
- fprintf(stderr, "op25_ambe_vocoder: inet_aton: bad IP address\n");
- close(write_sock);
- write_sock = 0;
- return;
+ std::string s = "";
+ if (d_debug >= 10) {
+ fprintf(stderr, "%s %s_BURST ", logts.get(), (burst_id < 4) ? "4V" : "2V");
}
- write_sock_addr.sin_family = AF_INET;
- write_sock_addr.sin_port = htons(udp_port);
+
+ if (burst_id < 4) {
+ for (int i=0; i < 12; i += 3) { // ESS-B is 4 hexbits / 12 dibits
+ ESS_B[(4 * burst_id) + (i / 3)] = (uint8_t) ((dibits[i] << 4) + (dibits[i+1] << 2) + dibits[i+2]);
+ }
+ }
+ else {
+ int i, j, k, ec;
+
+ j = 0;
+ for (i = 0; i < 28; i++) { // ESS-A is 28 hexbits / 84 dibits
+ ESS_A[i] = (uint8_t) ((dibits[j] << 4) + (dibits[j+1] << 2) + dibits[j+2]);
+ j = (i == 15) ? (j + 4) : (j + 3); // skip dibit containing DUID#3
+ }
+
+ ec = rs28.decode(ESS_B, ESS_A);
+
+ if (ec >= 0) { // save info if good decode
+ ess_algid = (ESS_B[0] << 2) + (ESS_B[1] >> 4);
+ ess_keyid = ((ESS_B[1] & 15) << 12) + (ESS_B[2] << 6) + ESS_B[3];
+
+ if (ess_algid == 0) { // workaround spurious algid
+ ess_algid = 128; // unenc
+ if (d_debug)
+ fprintf(stderr, "***burst detected zero algid, msgq_id %d***\n", d_msgq_id);
+ }
+
+ j = 0;
+ for (i = 0; i < 9;) {
+ ess_mi[i++] = (uint8_t) (ESS_B[j+4] << 2) + (ESS_B[j+5] >> 4);
+ ess_mi[i++] = (uint8_t) ((ESS_B[j+5] & 0x0f) << 4) + (ESS_B[j+6] >> 2);
+ ess_mi[i++] = (uint8_t) ((ESS_B[j+6] & 0x03) << 6) + ESS_B[j+7];
+ j += 4;
+ }
+ s = "{\"nac\" : " + std::to_string(d_nac) + ", \"algid\" : " + std::to_string(ess_algid) + ", \"alg\" : \"" + lookup(ess_algid, ALGIDS, ALGIDS_SZ) + "\", \"keyid\": " + std::to_string(ess_keyid) + "}";
+ send_msg(s, -3);
+ }
+ }
+
+ if (d_debug >= 10) {
+ fprintf(stderr, "ESS: algid=%x, keyid=%x, mi=", ess_algid, ess_keyid);
+ for (int i = 0; i < 9; i++) {
+ fprintf(stderr,"%02x ", ess_mi[i]);
+ }
+ fprintf(stderr, "\n");
+ }
}
+void p25p2_tdma::send_msg(const std::string msg_str, long msg_type)
+{
+ unsigned char hdr[4] = {0xaa, 0x55, (unsigned char)((d_msgq_id >> 8) & 0xff), (unsigned char)(d_msgq_id & 0xff)};
+ if (!d_do_msgq || d_msg_queue->full_p())
+ return;
+
+ gr::message::sptr msg = gr::message::make_from_string(std::string((char*)hdr, 4) + msg_str, msg_type, 0, 0);
+ d_msg_queue->insert_tail(msg);
+}
diff --git a/op25/gr-op25_repeater/lib/p25p2_tdma.h b/op25/gr-op25_repeater/lib/p25p2_tdma.h
index d7e30c3..1b9966c 100644
--- a/op25/gr-op25_repeater/lib/p25p2_tdma.h
+++ b/op25/gr-op25_repeater/lib/p25p2_tdma.h
@@ -22,9 +22,8 @@
#include <stdint.h>
#include <deque>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
+#include <vector>
+#include <gnuradio/msg_queue.h>
#include "mbelib.h"
#include "imbe_decoder.h"
#include "software_imbe_decoder.h"
@@ -32,12 +31,16 @@
#include "p25p2_sync.h"
#include "p25p2_vf.h"
#include "p25p2_framer.h"
+#include "op25_audio.h"
+#include "log_ts.h"
-class p25p2_tdma;
+#include "ezpwd/rs"
+
+//class p25p2_tdma;
class p25p2_tdma
{
public:
- p25p2_tdma(const char* udp_host, int port, int slotid, int debug, std::deque<int16_t> &qptr) ; // constructor
+ p25p2_tdma(const op25_audio& udp, int slotid, int debug, bool do_msgq, gr::msg_queue::sptr queue, std::deque<int16_t> &qptr, bool do_audio_output, int msgq_id) ; // constructor
int handle_packet(const uint8_t dibits[]) ;
void set_slotid(int slotid);
uint8_t* tdma_xormask;
@@ -45,6 +48,7 @@ public:
uint32_t packets;
~p25p2_tdma(); // destructor
void set_xormask(const char*p);
+ void set_nac(int nac) { d_nac = nac; }
bool rx_sym(uint8_t sym);
int handle_frame(void) ;
private:
@@ -52,26 +56,49 @@ private:
p25p2_duid duid;
p25p2_vf vf;
int write_bufp;
- int write_sock;
- struct sockaddr_in write_sock_addr;
char write_buf[512];
- const char* d_udp_host;
- int d_port;
int d_slotid;
+ int d_nac;
mbe_parms cur_mp;
mbe_parms prev_mp;
mbe_parms enh_mp;
software_imbe_decoder software_decoder;
+ gr::msg_queue::sptr d_msg_queue;
std::deque<int16_t> &output_queue_decode;
+ bool d_do_msgq;
+ bool d_do_audio_output;
+ const op25_audio& op25audio;
+ log_ts logts;
int d_debug;
- unsigned long int crc_errors;
+
+ int burst_id;
+ inline int track_vb(int burst_type) { return burst_id = (burst_type == 0) ? (++burst_id % 5) : 4; }
+ inline void reset_vb(void) { burst_id = -1; }
+
+ ezpwd::RS<63,35> rs28; // Reed-Solomon decoder object
+ std::vector<uint8_t> ESS_A; // ESS_A and ESS_B are hexbits vectors
+ std::vector<uint8_t> ESS_B;
+
+ uint16_t ess_keyid;
+ uint16_t ess_algid;
+ uint8_t ess_mi[9] = {0};
+ int d_msgq_id;
p25p2_framer p2framer;
- int handle_acch_frame(const uint8_t dibits[], bool fast) ;
+ int handle_acch_frame(const uint8_t dibits[], bool fast, bool is_lcch) ;
void handle_voice_frame(const uint8_t dibits[]) ;
- int process_mac_pdu(const uint8_t byte_buf[], unsigned int len) ;
- void init_sock(const char* udp_host, int udp_port);
+ int process_mac_pdu(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_signal(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_ptt(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_end_ptt(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_idle(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_active(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_mac_hangtime(const uint8_t byte_buf[], const unsigned int len) ;
+ void handle_4V2V_ess(const uint8_t dibits[]);
+ inline bool encrypted() { return (ess_algid != 0x80); }
+
+ void send_msg(const std::string msg_str, long msg_type);
};
#endif /* INCLUDED_P25P2_TDMA_H */
diff --git a/op25/gr-op25_repeater/lib/p25p2_vf.cc b/op25/gr-op25_repeater/lib/p25p2_vf.cc
index cab6f7d..592befe 100644
--- a/op25/gr-op25_repeater/lib/p25p2_vf.cc
+++ b/op25/gr-op25_repeater/lib/p25p2_vf.cc
@@ -20,6 +20,7 @@
#include <stdio.h>
#include <stdint.h>
#include <string.h>
+#include "op25_golay.h"
#include "p25p2_vf.h"
#include "rs.h"
@@ -817,9 +818,11 @@ static const int m_list[] = {0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 17, 18, 19, 20, 2
static const int d_list[] = {7, 1, 11, 21, 31, 25, 35, 45, 55, 49, 59, 69, 6, 0, 10, 20, 30, 24, 34, 44, 54, 48, 58, 68, 5, 15, 9, 19, 29, 39, 33, 43, 53, 63, 57, 67, 4, 14, 8, 18, 28, 38, 32, 42, 52, 62, 56, 66, 3, 13, 23, 17, 27, 37, 47, 41, 51, 61, 71, 65, 2, 12, 22, 16, 26, 36, 46, 40, 50, 60, 70, 64};
+static const int alt_d_list[] = {0, 12, 24, 36, 48, 60, 1, 13, 25, 37, 49, 61, 2, 14, 26, 38, 50, 62, 3, 15, 27, 39, 51, 63, 4, 16, 28, 40, 52, 64, 5, 17, 29, 41, 53, 65, 6, 18, 30, 42, 54, 66, 7, 19, 31, 43, 55, 67, 8, 20, 32, 44, 56, 68, 9, 21, 33, 45, 57, 69, 10, 22, 34, 46, 58, 70, 11, 23, 35, 47, 59, 71};
+
static const int b_lengths[] = {7,4,6,9,7,4,4,4,3};
-void p25p2_vf::encode_dstar(uint8_t result[72], const int b[9]) {
+void p25p2_vf::encode_dstar(uint8_t result[72], const int b[9], bool alt_dstar_interleave) {
uint8_t pbuf[48];
uint8_t tbuf[48];
@@ -842,15 +845,21 @@ void p25p2_vf::encode_dstar(uint8_t result[72], const int b[9]) {
store_reg(c1, pre_buf+24, 24);
memcpy(pre_buf+48, pbuf+24, 24);
for (int i=0; i < 72; i++)
- result[d_list[i]] = pre_buf[i];
+ if (alt_dstar_interleave)
+ result[i] = pre_buf[alt_d_list[i]];
+ else
+ result[d_list[i]] = pre_buf[i];
}
-void p25p2_vf::decode_dstar(const uint8_t codeword[72], int b[9]) {
+void p25p2_vf::decode_dstar(const uint8_t codeword[72], int b[9], bool alt_dstar_interleave) {
uint8_t pre_buf[72];
uint8_t post_buf[48];
uint8_t tbuf[48];
for (int i=0; i < 72; i++)
- pre_buf[i] = codeword[d_list[i]];
+ if (alt_dstar_interleave)
+ pre_buf[alt_d_list[i]] = codeword[i];
+ else
+ pre_buf[i] = codeword[d_list[i]];
uint32_t c0 = load_reg(pre_buf, 24);
uint32_t c1 = load_reg(pre_buf+24, 24);
diff --git a/op25/gr-op25_repeater/lib/p25p2_vf.h b/op25/gr-op25_repeater/lib/p25p2_vf.h
index b86d500..9b9b63e 100644
--- a/op25/gr-op25_repeater/lib/p25p2_vf.h
+++ b/op25/gr-op25_repeater/lib/p25p2_vf.h
@@ -26,8 +26,8 @@ class p25p2_vf {
public:
void process_vcw(const uint8_t vf[], int* b);
void encode_vcw(uint8_t vf[], const int* b);
- void encode_dstar(uint8_t result[72], const int b[9]);
- void decode_dstar(const uint8_t codeword[72], int b[9]);
+ void encode_dstar(uint8_t result[72], const int b[9], bool alt_dstar_interleave);
+ void decode_dstar(const uint8_t codeword[72], int b[9], bool alt_dstar_interleave);
private:
void extract_vcw(const uint8_t _vf[], int& _c0, int& _c1, int& _c2, int& _c3);
void interleave_vcw(uint8_t _vf[], int _c0, int _c1, int _c2, int _c3);
diff --git a/op25/gr-op25_repeater/lib/rs.cc b/op25/gr-op25_repeater/lib/rs.cc
index 2a5b774..272776e 100644
--- a/op25/gr-op25_repeater/lib/rs.cc
+++ b/op25/gr-op25_repeater/lib/rs.cc
@@ -4,7 +4,6 @@
#include <stdint.h>
#include <vector>
#include <assert.h>
-#include <op25_imbe_frame.h>
#ifdef DEBUG
/*
@@ -27,52 +26,6 @@ dump_cw(const_bit_vector cw, int len, FILE* fp) // len in bytes
}
#endif // DEBUG
-// this table used for HDU and also for TDU codeword mapping.
-// FIXME: possible dup of GOLAY_CODEWORDS in hdu.cc ?
-static const uint16_t hdu_codeword_bits[658] = { // 329 symbols = 324 + 5 pad
- 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
- 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 144, 145, 146, 147,
- 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
- 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
- 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195,
- 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,
- 212, 213, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229,
- 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
- 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
- 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277,
- 278, 279, 280, 281, 282, 283, 284, 285, 288, 289, 290, 291, 292, 293, 294, 295,
- 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311,
- 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327,
- 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343,
- 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 360, 361,
- 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377,
- 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393,
- 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409,
- 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425,
- 426, 427, 428, 429, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443,
- 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459,
- 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475,
- 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491,
- 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 504, 505, 506, 507, 508, 509,
- 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525,
- 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541,
- 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557,
- 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573,
- 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591,
- 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607,
- 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623,
- 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639,
- 640, 641, 642, 643, 644, 645, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657,
- 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673,
- 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689,
- 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705,
- 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 720, 721, 722, 723,
- 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739,
- 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755,
- 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771,
- 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787,
- 788, 789 };
-
static const uint32_t gly23127DecTbl[2048] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 147459,
1, 2, 2, 3, 2, 3, 3, 4268035, 2, 3, 3, 1574915, 3, 2097155, 294915, 4099,
@@ -203,260 +156,543 @@ static const uint32_t gly23127DecTbl[2048] = {
4718595, 16387, 16387, 16386, 1048579, 2138115, 65539, 16387, 2099203, 69635, 1343491, 16387, 131075, 262147, 4206595, 526339,
1048579, 69635, 141315, 16387, 1048578, 1048579, 1048579, 4456451, 69635, 69634, 524291, 69635, 1048579, 69635, 2113539, 163843 };
-static const uint32_t hmg1063EncTbl[64] = {
- 0, 12, 3, 15, 7, 11, 4, 8, 11, 7, 8, 4, 12, 0, 15, 3,
- 13, 1, 14, 2, 10, 6, 9, 5, 6, 10, 5, 9, 1, 13, 2, 14,
- 14, 2, 13, 1, 9, 5, 10, 6, 5, 9, 6, 10, 2, 14, 1, 13,
- 3, 15, 0, 12, 4, 8, 7, 11, 8, 4, 11, 7, 15, 3, 12, 0 };
-static const uint32_t hmg1063DecTbl[16] = {
- 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 8, 1, 16, 32, 0 };
-
-static const uint32_t rsGFexp[64] = {
- 1, 2, 4, 8, 16, 32, 3, 6, 12, 24, 48, 35, 5, 10, 20, 40,
- 19, 38, 15, 30, 60, 59, 53, 41, 17, 34, 7, 14, 28, 56, 51, 37,
- 9, 18, 36, 11, 22, 44, 27, 54, 47, 29, 58, 55, 45, 25, 50, 39,
- 13, 26, 52, 43, 21, 42, 23, 46, 31, 62, 63, 61, 57, 49, 33, 0 };
-static const uint32_t rsGFlog[64] = {
- 63, 0, 1, 6, 2, 12, 7, 26, 3, 32, 13, 35, 8, 48, 27, 18,
- 4, 24, 33, 16, 14, 52, 36, 54, 9, 45, 49, 38, 28, 41, 19, 56,
- 5, 62, 25, 11, 34, 31, 17, 47, 15, 23, 53, 51, 37, 44, 55, 40,
- 10, 61, 46, 30, 50, 22, 39, 43, 29, 60, 42, 21, 20, 59, 57, 58 };
-
-int hmg1063Dec (uint32_t Dat, uint32_t Par) {
- assert ((Dat < 64) && (Par < 16));
- return Dat ^ hmg1063DecTbl [ hmg1063EncTbl[Dat] ^ Par];
-}
-
-int
-rsDec (int nroots, int FirstInfo, uint8_t HB[]) {
-
-//RS (63,63-nroots,nroots+1) decoder where nroots = number of parity bits
-// rsDec(8, 39) rsDec(16, 27) rsDec(12, 39)
-
-
-int lambda[18] ;//Err+Eras Locator poly
-int S[17] ;//syndrome poly
-int b[18] ;
-int t[18] ;
-int omega[18] ;
-int root[17] ;
-int reg[18] ;
-int locn[17] ;
-
-int i,j, count, r, el, SynError, DiscrR, q, DegOmega, tmp, num1, num2, den, DegLambda;
-
-//form the syndromes; i.e., evaluate HB(x) at roots of g(x)
-
-for (i = 0; i <= nroots - 1; i++) {
- S[i] = HB[0];
-}
-for (j = 1; j <= 62; j++) {
- for (i = 0; i <= nroots - 1; i++) {
- if (S[i] == 0) {
- S[i] = HB[j];
- } else {
- S[i] = HB[j] ^ rsGFexp[(rsGFlog[S[i]] + i + 1) % 63];
- }
- }
-}
-
-
-
-//convert syndromes to index form, checking for nonzero condition
-
-SynError = 0;
-
-for (i = 0; i <= nroots - 1; i++) {
- SynError = SynError | S[i];
- S[i] = rsGFlog[S[i]];
-}
-
-if (SynError == 0) {
- //if syndrome is zero, rsData[] is a codeword and there are
- //no errors to correct. So return rsData[] unmodified
- count = 0;
- goto rsDecFinish;
-}
-
-for (i = 1; i <= nroots; i++) {
- lambda[i] = 0;
-}
-lambda[0] = 1;
-
-for (i = 0; i <= nroots; i++) {
- b[i] = rsGFlog[lambda[i]];
-}
-
-
-
-//begin Berlekamp-Massey algorithm to determine error+erasure
-//locator polynomial
-
-r = 0;
-el = 0;
-while ( r < nroots) { //r is the step number
- r = r + 1;
- //compute discrepancy at the r-th step in poly-form
- DiscrR = 0;
- for (i = 0; i <= r - 1; i++) {
- if ((lambda[i] != 0) && (S[r - i - 1] != 63)) {
- DiscrR = DiscrR ^ rsGFexp[(rsGFlog[lambda[i]] + S[r - i - 1]) % 63];
- }
- }
- DiscrR = rsGFlog[DiscrR] ;//index form
-
- if (DiscrR == 63) {
- //shift elements upward one step
- for (i = nroots; i >= 1; i += -1){b[i] = b[i - 1]; } b[0] = 63;
- } else {
- //t(x) <-- lambda(x) - DiscrR*x*b(x)
- t[0] = lambda[0];
- for (i = 0; i <= nroots - 1; i++) {
- if (b[i] != 63) {
- t[i + 1] = lambda[i + 1] ^ rsGFexp[(DiscrR + b[i]) % 63];
- } else {
- t[i + 1] = lambda[i + 1];
- }
- }
- if (2 * el <= r - 1) {
- el = r - el;
- //b(x) <-- inv(DiscrR) * lambda(x)
- for (i = 0; i <= nroots; i++) {
- if (lambda[i]) { b[i] = (rsGFlog[lambda[i]] - DiscrR + 63) % 63; } else { b[i] = 63; }
- }
- } else {
- //shift elements upward one step
- for (i = nroots; i >= 1; i += -1){b[i] = b[i - 1]; } b[0] = 63;
- }
- for (i = 0; i <= nroots; i++) { lambda[i] = t[i]; }
- }
-} /* end while() */
-
-
-
-//convert lambda to index form and compute deg(lambda(x))
-
-DegLambda = 0;
-for (i = 0; i <= nroots; i++) {
- lambda[i] = rsGFlog[lambda[i]];
- if (lambda[i] != 63) { DegLambda = i; }
+static const uint32_t gly24128EncTbl[4096] = {
+ 0, 6379, 10558, 12757, 19095, 21116, 25513, 31554,
+ 36294, 38189, 42232, 48147, 51025, 57274, 61039, 63108,
+ 66407, 72588, 76377, 78514, 84464, 86299, 90318, 96293,
+ 102049, 104010, 108447, 114548, 115766, 122077, 126216, 128483,
+ 132813, 138790, 143347, 145176, 150618, 152753, 157028, 163215,
+ 166667, 168928, 172597, 178910, 180636, 186743, 190626, 192585,
+ 198058, 204097, 208020, 210047, 216893, 219094, 222723, 229096,
+ 231532, 233607, 237906, 244153, 246523, 252432, 256965, 258862,
+ 265625, 267634, 271527, 277580, 280334, 286693, 290352, 292571,
+ 295007, 301236, 305505, 307594, 314056, 315939, 320502, 326429,
+ 331518, 333333, 337856, 343851, 345193, 351362, 355671, 357820,
+ 361272, 367571, 371206, 373485, 379311, 381252, 385169, 391290,
+ 396116, 398271, 402026, 408193, 410051, 416040, 420093, 421910,
+ 427666, 433785, 438188, 440135, 445445, 447726, 451899, 458192,
+ 460851, 463064, 467213, 473574, 475812, 481871, 486298, 488305,
+ 493045, 498974, 502987, 504864, 511842, 513929, 517724, 523959,
+ 525274, 531249, 535268, 537103, 543053, 545190, 548979, 555160,
+ 560668, 562935, 567074, 573385, 574603, 580704, 585141, 587102,
+ 590013, 596054, 600451, 602472, 608810, 611009, 615188, 621567,
+ 626043, 628112, 631877, 638126, 641004, 646919, 650962, 652857,
+ 656663, 663036, 666665, 668866, 675712, 677739, 681662, 687701,
+ 690385, 692282, 696815, 702724, 705094, 711341, 715640, 717715,
+ 722544, 728731, 733006, 735141, 740583, 742412, 746969, 752946,
+ 756662, 758621, 762504, 768611, 770337, 776650, 780319, 782580,
+ 790083, 792232, 796541, 802710, 804052, 810047, 814570, 816385,
+ 820101, 826222, 830139, 832080, 837906, 840185, 843820, 850119,
+ 855332, 857551, 861210, 867569, 870323, 876376, 880269, 882278,
+ 884962, 890889, 895452, 897335, 903797, 905886, 910155, 916384,
+ 919694, 921701, 926128, 932187, 934425, 940786, 944935, 947148,
+ 951624, 957859, 961654, 963741, 970719, 972596, 976609, 982538,
+ 986089, 987906, 991959, 997948, 999806, 1005973, 1009728, 1011883,
+ 1017391, 1023684, 1027857, 1030138, 1035448, 1037395, 1041798, 1047917,
+ 1050548, 1056607, 1060490, 1062497, 1068323, 1070536, 1074205, 1080566,
+ 1084018, 1086105, 1090380, 1096615, 1097957, 1103886, 1108443, 1110320,
+ 1115347, 1121336, 1125869, 1127686, 1134148, 1136303, 1140602, 1146769,
+ 1149205, 1151486, 1155115, 1161408, 1164162, 1170281, 1174204, 1176151,
+ 1180025, 1186194, 1189959, 1192108, 1199086, 1200901, 1204944, 1210939,
+ 1215679, 1217620, 1222017, 1228138, 1230376, 1236675, 1240854, 1243133,
+ 1245726, 1252085, 1256224, 1258443, 1263753, 1265762, 1270199, 1276252,
+ 1282008, 1283891, 1287910, 1293837, 1295695, 1301924, 1305713, 1307802,
+ 1313325, 1315526, 1319699, 1326072, 1327290, 1333329, 1337732, 1339759,
+ 1345515, 1351424, 1355477, 1357374, 1363324, 1365399, 1369154, 1375401,
+ 1378634, 1380769, 1384564, 1390751, 1393629, 1399606, 1403619, 1405448,
+ 1410188, 1416295, 1420722, 1422681, 1429019, 1431280, 1435429, 1441742,
+ 1445088, 1446923, 1451486, 1457461, 1459831, 1466012, 1470281, 1472418,
+ 1474854, 1481165, 1484824, 1487091, 1493937, 1495898, 1499791, 1505892,
+ 1511303, 1513324, 1517241, 1523282, 1525008, 1531387, 1535022, 1537221,
+ 1540673, 1546922, 1551231, 1553300, 1558742, 1560637, 1565160, 1571075,
+ 1573998, 1580165, 1584464, 1586619, 1593081, 1594898, 1599431, 1605420,
+ 1608104, 1610051, 1613974, 1620093, 1622847, 1629140, 1632769, 1635050,
+ 1640201, 1646562, 1650231, 1652444, 1658270, 1660277, 1664160, 1670219,
+ 1673935, 1675812, 1680369, 1686298, 1687640, 1693875, 1698150, 1700237,
+ 1704611, 1710664, 1715101, 1717110, 1722420, 1724639, 1728778, 1735137,
+ 1740645, 1742734, 1746523, 1752752, 1754610, 1760537, 1764556, 1766439,
+ 1769924, 1775919, 1779962, 1781777, 1788755, 1790904, 1794669, 1800838,
+ 1805314, 1807593, 1811772, 1818071, 1820309, 1826430, 1830827, 1832768,
+ 1837559, 1839388, 1843401, 1849378, 1852256, 1858443, 1862238, 1864373,
+ 1868849, 1875162, 1879311, 1881572, 1887910, 1889869, 1894296, 1900403,
+ 1903248, 1905275, 1909678, 1915717, 1916935, 1923308, 1927481, 1929682,
+ 1935190, 1941437, 1945192, 1947267, 1953217, 1955114, 1959167, 1965076,
+ 1969978, 1972177, 1975812, 1982191, 1983917, 1989958, 1993875, 1995896,
+ 1999612, 2005527, 2010050, 2011945, 2017387, 2019456, 2023765, 2030014,
+ 2034781, 2036918, 2041187, 2047368, 2049738, 2055713, 2060276, 2062111,
+ 2064795, 2070896, 2074789, 2076750, 2083596, 2085863, 2089522, 2095833,
+ 2101096, 2103171, 2106966, 2113213, 2115071, 2120980, 2124993, 2126890,
+ 2130606, 2136645, 2141072, 2143099, 2148409, 2150610, 2154759, 2161132,
+ 2165775, 2168036, 2172209, 2178522, 2180760, 2186867, 2191270, 2193229,
+ 2195913, 2201890, 2205943, 2207772, 2214750, 2216885, 2220640, 2226827,
+ 2230693, 2232654, 2236571, 2242672, 2245426, 2251737, 2255372, 2257639,
+ 2262115, 2268296, 2272605, 2274742, 2281204, 2283039, 2287562, 2293537,
+ 2296514, 2298409, 2302972, 2308887, 2310229, 2316478, 2320747, 2322816,
+ 2328324, 2334703, 2338362, 2340561, 2346387, 2348408, 2352301, 2358342,
+ 2360049, 2365978, 2370511, 2372388, 2377830, 2379917, 2384216, 2390451,
+ 2395959, 2398172, 2401801, 2408162, 2409888, 2415947, 2419870, 2421877,
+ 2425238, 2431357, 2435240, 2437187, 2444033, 2446314, 2449983, 2456276,
+ 2460752, 2462907, 2467182, 2473349, 2475719, 2481708, 2486265, 2488082,
+ 2491452, 2497751, 2501890, 2504169, 2510507, 2512448, 2516885, 2523006,
+ 2525690, 2527505, 2531524, 2537519, 2540397, 2546566, 2550355, 2552504,
+ 2557787, 2564016, 2567781, 2569870, 2575820, 2577703, 2581746, 2587673,
+ 2591389, 2593398, 2597795, 2603848, 2605066, 2611425, 2615604, 2617823,
+ 2624690, 2626649, 2631052, 2637159, 2639397, 2645710, 2649883, 2652144,
+ 2654580, 2660767, 2664522, 2666657, 2673635, 2675464, 2679517, 2685494,
+ 2691029, 2692926, 2696939, 2702848, 2704706, 2710953, 2714748, 2716823,
+ 2720275, 2726648, 2730797, 2732998, 2738308, 2740335, 2744762, 2750801,
+ 2755199, 2757268, 2761537, 2767786, 2769128, 2775043, 2779606, 2781501,
+ 2787257, 2793298, 2797191, 2799212, 2805038, 2807237, 2810896, 2817275,
+ 2820376, 2822643, 2826278, 2832589, 2835343, 2841444, 2845361, 2847322,
+ 2852062, 2858037, 2862560, 2864395, 2870857, 2872994, 2877303, 2883484,
+ 2883883, 2890176, 2893845, 2896126, 2902972, 2904919, 2908802, 2914921,
+ 2919661, 2921478, 2926035, 2932024, 2934394, 2940561, 2944836, 2946991,
+ 2949708, 2955943, 2960242, 2962329, 2967771, 2969648, 2974181, 2980110,
+ 2985866, 2987873, 2991796, 2997855, 2999581, 3005942, 3009571, 3011784,
+ 3016678, 3022605, 3026648, 3028531, 3034481, 3036570, 3040335, 3046564,
+ 3050016, 3052235, 3056414, 3062773, 3063991, 3070044, 3074441, 3076450,
+ 3081345, 3087466, 3091903, 3093844, 3100182, 3102461, 3106600, 3112899,
+ 3115335, 3117484, 3121273, 3127442, 3130320, 3136315, 3140334, 3142149,
+ 3147996, 3149879, 3154402, 3160329, 3162699, 3168928, 3173237, 3175326,
+ 3179802, 3186161, 3189796, 3192015, 3198861, 3200870, 3204787, 3210840,
+ 3214267, 3216208, 3220101, 3226222, 3227948, 3234247, 3237906, 3240185,
+ 3245693, 3251862, 3256131, 3258280, 3263722, 3265537, 3270100, 3276095,
+ 3280401, 3282682, 3286831, 3293124, 3294342, 3300461, 3304888, 3306835,
+ 3310551, 3316540, 3320553, 3322370, 3328320, 3330475, 3334270, 3340437,
+ 3345782, 3347869, 3351624, 3357859, 3360737, 3366666, 3370719, 3372596,
+ 3375280, 3381339, 3385742, 3387749, 3394087, 3396300, 3400473, 3406834,
+ 3409221, 3415470, 3419259, 3421328, 3428306, 3430201, 3434220, 3440135,
+ 3442819, 3444840, 3449277, 3455318, 3457556, 3463935, 3468074, 3470273,
+ 3474978, 3481289, 3485468, 3487735, 3493045, 3495006, 3499403, 3505504,
+ 3509220, 3511055, 3515098, 3521073, 3522931, 3529112, 3532877, 3535014,
+ 3539848, 3545955, 3549878, 3551837, 3557663, 3559924, 3563553, 3569866,
+ 3575374, 3577509, 3581808, 3587995, 3589337, 3595314, 3599847, 3601676,
+ 3604719, 3610628, 3615185, 3617082, 3623544, 3625619, 3629894, 3636141,
+ 3640617, 3642818, 3646487, 3652860, 3655614, 3661653, 3665536, 3667563,
+ 3672838, 3675117, 3678776, 3685075, 3686801, 3692922, 3696815, 3698756,
+ 3704512, 3710507, 3715070, 3716885, 3722327, 3724476, 3728745, 3734914,
+ 3737697, 3739786, 3744095, 3750324, 3752694, 3758621, 3763144, 3765027,
+ 3769767, 3775820, 3779737, 3781746, 3788592, 3790811, 3794446, 3800805,
+ 3804619, 3806496, 3810549, 3816478, 3819356, 3825591, 3829346, 3831433,
+ 3833869, 3840230, 3844403, 3846616, 3852954, 3854961, 3859364, 3865423,
+ 3870380, 3872327, 3876754, 3882873, 3884091, 3890384, 3894533, 3896814,
+ 3900266, 3906433, 3910228, 3912383, 3918333, 3920150, 3924163, 3930152,
+ 3933855, 3939956, 3944353, 3946314, 3951624, 3953891, 3958070, 3964381,
+ 3967833, 3969970, 3973735, 3979916, 3981774, 3987749, 3991792, 3993627,
+ 3999224, 4005139, 4009158, 4011053, 4018031, 4020100, 4023889, 4030138,
+ 4032574, 4034773, 4038912, 4045291, 4047529, 4053570, 4058007, 4060028,
+ 4063314, 4069561, 4073836, 4075911, 4082373, 4084270, 4088827, 4094736,
+ 4099476, 4101503, 4105386, 4111425, 4114179, 4120552, 4124221, 4126422,
+ 4129589, 4135902, 4139531, 4141792, 4147618, 4149577, 4153500, 4159607,
+ 4165363, 4167192, 4171725, 4177702, 4179044, 4185231, 4189530, 4191665,
+ 4195899, 4202192, 4206341, 4208622, 4213932, 4215879, 4220306, 4226425,
+ 4230141, 4231958, 4235971, 4241960, 4243818, 4249985, 4253780, 4255935,
+ 4261212, 4267447, 4271202, 4273289, 4280267, 4282144, 4286197, 4292126,
+ 4294810, 4296817, 4301220, 4307279, 4309517, 4315878, 4320051, 4322264,
+ 4325622, 4331549, 4336072, 4337955, 4344417, 4346506, 4350815, 4357044,
+ 4361520, 4363739, 4367374, 4373733, 4376487, 4382540, 4386457, 4388466,
+ 4391825, 4397946, 4401839, 4403780, 4409606, 4411885, 4415544, 4421843,
+ 4427351, 4429500, 4433769, 4439938, 4441280, 4447275, 4451838, 4453653,
+ 4459426, 4461385, 4465308, 4471415, 4473141, 4479454, 4483083, 4485344,
+ 4490852, 4497039, 4501338, 4503473, 4508915, 4510744, 4515277, 4521254,
+ 4524229, 4526126, 4530683, 4536592, 4538962, 4545209, 4549484, 4551559,
+ 4556035, 4562408, 4566077, 4568278, 4575124, 4577151, 4581034, 4587073,
+ 4590959, 4593028, 4596817, 4603066, 4605944, 4611859, 4615878, 4617773,
+ 4620457, 4626498, 4630935, 4632956, 4639294, 4641493, 4645632, 4652011,
+ 4656648, 4658915, 4663094, 4669405, 4670623, 4676724, 4681121, 4683082,
+ 4686798, 4692773, 4696816, 4698651, 4704601, 4706738, 4710503, 4716684,
+ 4720097, 4726026, 4730079, 4731956, 4738934, 4741021, 4744776, 4751011,
+ 4753447, 4755660, 4759833, 4766194, 4768432, 4774491, 4778894, 4780901,
+ 4785798, 4791917, 4796344, 4798291, 4803601, 4805882, 4810031, 4816324,
+ 4819776, 4821931, 4825726, 4831893, 4833751, 4839740, 4843753, 4845570,
+ 4850476, 4856775, 4860434, 4862713, 4868539, 4870480, 4874373, 4880494,
+ 4886250, 4888065, 4892628, 4898623, 4899965, 4906134, 4910403, 4912552,
+ 4915275, 4921504, 4925813, 4927902, 4934364, 4936247, 4940770, 4946697,
+ 4951437, 4953446, 4957363, 4963416, 4966170, 4972529, 4976164, 4978383,
+ 4982904, 4984979, 4989254, 4995501, 4997871, 5003780, 5008337, 5010234,
+ 5014974, 5021013, 5024896, 5026923, 5033769, 5035970, 5039639, 5046012,
+ 5049119, 5051380, 5055009, 5061322, 5063048, 5069155, 5073078, 5075037,
+ 5080793, 5086770, 5091303, 5093132, 5098574, 5100709, 5105008, 5111195,
+ 5115573, 5117534, 5121931, 5128032, 5129250, 5135561, 5139740, 5142007,
+ 5145459, 5151640, 5155405, 5157542, 5163492, 5165327, 5169370, 5175345,
+ 5180882, 5182777, 5186796, 5192711, 5195589, 5201838, 5205627, 5207696,
+ 5210132, 5216511, 5220650, 5222849, 5229187, 5231208, 5235645, 5241686,
+ 5243279, 5249380, 5253297, 5255258, 5262104, 5264371, 5268006, 5274317,
+ 5278793, 5280930, 5285239, 5291420, 5293790, 5299765, 5304288, 5306123,
+ 5309160, 5315075, 5319638, 5321533, 5326975, 5329044, 5333313, 5339562,
+ 5345070, 5347269, 5350928, 5357307, 5359033, 5365074, 5368967, 5370988,
+ 5375810, 5382057, 5385852, 5387927, 5393877, 5395774, 5399787, 5405696,
+ 5409412, 5411439, 5415866, 5421905, 5423123, 5429496, 5433645, 5435846,
+ 5440549, 5446862, 5451035, 5453296, 5459634, 5461593, 5465996, 5472103,
+ 5474787, 5476616, 5480669, 5486646, 5489524, 5495711, 5499466, 5501601,
+ 5508118, 5510397, 5514536, 5520835, 5523073, 5529194, 5533631, 5535572,
+ 5538256, 5544251, 5548270, 5550085, 5557063, 5559212, 5563001, 5569170,
+ 5574513, 5576602, 5580367, 5586596, 5588454, 5594381, 5598424, 5600307,
+ 5604023, 5610076, 5614473, 5616482, 5621792, 5624011, 5628190, 5634549,
+ 5638875, 5640752, 5645285, 5651214, 5652556, 5658791, 5663090, 5665177,
+ 5670685, 5677046, 5680675, 5682888, 5688714, 5690721, 5694644, 5700703,
+ 5704124, 5706071, 5709954, 5716073, 5718827, 5725120, 5728789, 5731070,
+ 5735546, 5741713, 5745988, 5748143, 5754605, 5756422, 5760979, 5766968,
+ 5767765, 5774014, 5778283, 5780352, 5785794, 5787689, 5792252, 5798167,
+ 5803923, 5805944, 5809837, 5815878, 5817604, 5823983, 5827642, 5829841,
+ 5833010, 5839321, 5842956, 5845223, 5852069, 5854030, 5857947, 5864048,
+ 5868788, 5870623, 5875146, 5881121, 5883491, 5889672, 5893981, 5896118,
+ 5899416, 5905523, 5909926, 5911885, 5918223, 5920484, 5924657, 5930970,
+ 5933406, 5935541, 5939296, 5945483, 5948361, 5954338, 5958391, 5960220,
+ 5965823, 5971732, 5975745, 5977642, 5983592, 5985667, 5989462, 5995709,
+ 5999161, 6001362, 6005511, 6011884, 6013102, 6019141, 6023568, 6025595,
+ 6033356, 6035239, 6039282, 6045209, 6047067, 6053296, 6057061, 6059150,
+ 6062602, 6068961, 6073140, 6075359, 6080669, 6082678, 6087075, 6093128,
+ 6098091, 6100032, 6104469, 6110590, 6112828, 6119127, 6123266, 6125545,
+ 6127981, 6134150, 6137939, 6140088, 6147066, 6148881, 6152900, 6158895,
+ 6162689, 6164970, 6168639, 6174932, 6177686, 6183805, 6187688, 6189635,
+ 6194375, 6200364, 6204921, 6206738, 6213200, 6215355, 6219630, 6225797,
+ 6228582, 6230669, 6234968, 6241203, 6242545, 6248474, 6253007, 6254884,
+ 6260640, 6266699, 6270622, 6272629, 6278455, 6280668, 6284297, 6290658,
+ 6293843, 6295992, 6299757, 6305926, 6308804, 6314799, 6318842, 6320657,
+ 6325397, 6331518, 6335915, 6337856, 6344194, 6346473, 6350652, 6356951,
+ 6359604, 6361823, 6365962, 6372321, 6373539, 6379592, 6384029, 6386038,
+ 6391794, 6397721, 6401740, 6403623, 6409573, 6411662, 6415451, 6421680,
+ 6426526, 6428533, 6432416, 6438475, 6440201, 6446562, 6450231, 6452444,
+ 6455896, 6462131, 6466406, 6468493, 6473935, 6475812, 6480369, 6486298,
+ 6491385, 6493202, 6497735, 6503724, 6506094, 6512261, 6516560, 6518715,
+ 6521151, 6527444, 6531073, 6533354, 6540200, 6542147, 6546070, 6552189,
+ 6554826, 6560801, 6565364, 6567199, 6573661, 6575798, 6580067, 6586248,
+ 6588684, 6590951, 6594610, 6600921, 6603675, 6609776, 6613669, 6615630,
+ 6621101, 6627142, 6631059, 6633080, 6638906, 6641105, 6644740, 6651119,
+ 6654571, 6656640, 6660949, 6667198, 6668540, 6674455, 6678978, 6680873,
+ 6685191, 6691564, 6695737, 6697938, 6703248, 6705275, 6709678, 6715717,
+ 6721473, 6723370, 6727423, 6733332, 6735190, 6741437, 6745192, 6747267,
+ 6750560, 6756747, 6760542, 6762677, 6769655, 6771484, 6775497, 6781474,
+ 6786214, 6788173, 6792600, 6798707, 6800945, 6807258, 6811407, 6813668,
+ 6818441, 6820450, 6824887, 6830940, 6832158, 6838517, 6842656, 6844875,
+ 6850383, 6856612, 6860401, 6862490, 6868440, 6870323, 6874342, 6880269,
+ 6883822, 6885637, 6889680, 6895675, 6898553, 6904722, 6908487, 6910636,
+ 6915112, 6921411, 6925590, 6927869, 6934207, 6936148, 6940545, 6946666,
+ 6949956, 6952111, 6956410, 6962577, 6964947, 6970936, 6975469, 6977286,
+ 6979970, 6986089, 6990012, 6991959, 6998805, 7001086, 7004715, 7011008,
+ 7016227, 7018440, 7022109, 7028470, 7030196, 7036255, 7040138, 7042145,
+ 7045861, 7051790, 7056347, 7058224, 7063666, 7065753, 7070028, 7076263,
+ 7079696, 7086075, 7089710, 7091909, 7097735, 7099756, 7103673, 7109714,
+ 7113430, 7115325, 7119848, 7125763, 7127105, 7133354, 7137663, 7139732,
+ 7144567, 7150748, 7155017, 7157154, 7163616, 7165451, 7170014, 7175989,
+ 7178673, 7180634, 7184527, 7190628, 7193382, 7199693, 7203352, 7205619,
+ 7209437, 7215414, 7219427, 7221256, 7228234, 7230369, 7234164, 7240351,
+ 7244827, 7247088, 7251237, 7257550, 7259788, 7265895, 7270322, 7272281,
+ 7275194, 7281233, 7285636, 7287663, 7292973, 7295174, 7299347, 7305720,
+ 7311228, 7313303, 7317058, 7323305, 7325163, 7331072, 7335125, 7337022,
+ 7343847, 7345676, 7350233, 7356210, 7357552, 7363739, 7368014, 7370149,
+ 7373601, 7379914, 7383583, 7385844, 7391670, 7393629, 7397512, 7403619,
+ 7409024, 7411051, 7414974, 7421013, 7423767, 7430140, 7433769, 7435970,
+ 7438406, 7444653, 7448952, 7451027, 7457489, 7459386, 7463919, 7469828,
+ 7473194, 7475393, 7479572, 7485951, 7488189, 7494230, 7498627, 7500648,
+ 7505388, 7511303, 7515346, 7517241, 7524219, 7526288, 7530053, 7536302,
+ 7539533, 7541670, 7545459, 7551640, 7553498, 7559473, 7563492, 7565327,
+ 7571083, 7577184, 7581621, 7583582, 7588892, 7591159, 7595298, 7601609,
+ 7603070, 7609237, 7612992, 7615147, 7621097, 7622914, 7626967, 7632956,
+ 7638712, 7640659, 7645062, 7651181, 7652399, 7658692, 7662865, 7665146,
+ 7667737, 7674098, 7678247, 7680460, 7686798, 7688805, 7693232, 7699291,
+ 7704031, 7705908, 7709921, 7715850, 7718728, 7724963, 7728758, 7730845,
+ 7734707, 7740760, 7744653, 7746662, 7753508, 7755727, 7759386, 7765745,
+ 7768181, 7770270, 7774539, 7780768, 7783138, 7789065, 7793628, 7795511,
+ 7800532, 7806527, 7811050, 7812865, 7818307, 7820456, 7824765, 7830934,
+ 7834386, 7836665, 7840300, 7846599, 7848325, 7854446, 7858363, 7860304,
+ 7867709, 7869910, 7873539, 7879912, 7882666, 7888705, 7892628, 7894655,
+ 7897339, 7903248, 7907781, 7909678, 7916140, 7918215, 7922514, 7928761,
+ 7933530, 7935665, 7939940, 7946127, 7947469, 7953446, 7958003, 7959832,
+ 7963548, 7969655, 7973538, 7975497, 7981323, 7983584, 7987253, 7993566,
+ 7998448, 8000283, 8004302, 8010277, 8012135, 8018316, 8022105, 8024242,
+ 8029750, 8036061, 8040200, 8042467, 8047777, 8049738, 8054175, 8060276,
+ 8063127, 8065148, 8069545, 8075586, 8077824, 8084203, 8088382, 8090581,
+ 8095057, 8101306, 8105071, 8107140, 8114118, 8116013, 8120056, 8125971,
+ 8126628, 8132687, 8137114, 8139121, 8145459, 8147672, 8151821, 8158182,
+ 8162658, 8164745, 8168540, 8174775, 8177653, 8183582, 8187595, 8189472,
+ 8192963, 8198952, 8203005, 8204822, 8210772, 8212927, 8216682, 8222849,
+ 8228357, 8230638, 8234811, 8241104, 8242322, 8248441, 8252844, 8254791,
+ 8259177, 8265346, 8269655, 8271804, 8277246, 8279061, 8283584, 8289579,
+ 8293295, 8295236, 8299153, 8305274, 8307000, 8313299, 8316934, 8319213,
+ 8324366, 8330725, 8334384, 8336603, 8343449, 8345458, 8349351, 8355404,
+ 8358088, 8359971, 8364534, 8370461, 8372831, 8379060, 8383329, 8385418,
+ 8391797, 8393886, 8398155, 8404384, 8406754, 8412681, 8417244, 8419127,
+ 8421811, 8427864, 8431757, 8433766, 8440612, 8442831, 8446490, 8452849,
+ 8458002, 8460281, 8463916, 8470215, 8471941, 8478062, 8481979, 8483920,
+ 8487636, 8493631, 8498154, 8499969, 8505411, 8507560, 8511869, 8518038,
+ 8522424, 8524371, 8528774, 8534893, 8536111, 8542404, 8546577, 8548858,
+ 8554366, 8560533, 8564288, 8566443, 8572393, 8574210, 8578263, 8584252,
+ 8587743, 8589620, 8593633, 8599562, 8602440, 8608675, 8612470, 8614557,
+ 8619033, 8625394, 8629543, 8631756, 8638094, 8640101, 8644528, 8650587,
+ 8651244, 8657159, 8661202, 8663097, 8670075, 8672144, 8675909, 8682158,
+ 8686634, 8688833, 8693012, 8699391, 8701629, 8707670, 8712067, 8714088,
+ 8716939, 8723040, 8727477, 8729438, 8734748, 8737015, 8741154, 8747465,
+ 8752973, 8755110, 8758899, 8765080, 8766938, 8772913, 8776932, 8778767,
+ 8783649, 8789962, 8793631, 8795892, 8801718, 8803677, 8807560, 8813667,
+ 8817383, 8819212, 8823769, 8829746, 8831088, 8837275, 8841550, 8843685,
+ 8848454, 8854701, 8859000, 8861075, 8867537, 8869434, 8873967, 8879876,
+ 8882560, 8884587, 8888510, 8894549, 8897303, 8903676, 8907305, 8909506,
+ 8916911, 8918852, 8922769, 8928890, 8930616, 8936915, 8940550, 8942829,
+ 8946281, 8952450, 8956759, 8958908, 8964350, 8966165, 8970688, 8976683,
+ 8981704, 8983587, 8988150, 8994077, 8996447, 9002676, 9006945, 9009034,
+ 9011470, 9017829, 9021488, 9023707, 9030553, 9032562, 9036455, 9042508,
+ 9046370, 9048457, 9052252, 9058487, 9061365, 9067294, 9071307, 9073184,
+ 9077924, 9083983, 9088410, 9090417, 9096755, 9098968, 9103117, 9109478,
+ 9112069, 9114350, 9118523, 9124816, 9126034, 9132153, 9136556, 9138503,
+ 9144259, 9150248, 9154301, 9156118, 9162068, 9164223, 9167978, 9174145,
+ 9175606, 9181917, 9186056, 9188323, 9193633, 9195594, 9200031, 9206132,
+ 9211888, 9213723, 9217742, 9223717, 9225575, 9231756, 9235545, 9237682,
+ 9240913, 9247162, 9250927, 9252996, 9259974, 9261869, 9265912, 9271827,
+ 9276567, 9278588, 9282985, 9289026, 9291264, 9297643, 9301822, 9304021,
+ 9307387, 9313296, 9317829, 9319726, 9326188, 9328263, 9332562, 9338809,
+ 9341245, 9343446, 9347075, 9353448, 9356202, 9362241, 9366164, 9368191,
+ 9373596, 9379703, 9383586, 9385545, 9391371, 9393632, 9397301, 9403614,
+ 9407066, 9409201, 9413476, 9419663, 9421005, 9426982, 9431539, 9433368,
+ 9440193, 9442090, 9446143, 9452052, 9453910, 9460157, 9463912, 9465987,
+ 9471495, 9477868, 9482041, 9484242, 9489552, 9491579, 9495982, 9502021,
+ 9504934, 9506893, 9511320, 9517427, 9519665, 9525978, 9530127, 9532388,
+ 9536864, 9543051, 9546846, 9548981, 9555959, 9557788, 9561801, 9567778,
+ 9571596, 9573863, 9577522, 9583833, 9586587, 9592688, 9596581, 9598542,
+ 9601226, 9607201, 9611764, 9613599, 9620061, 9622198, 9626467, 9632648,
+ 9637483, 9639552, 9643861, 9650110, 9651452, 9657367, 9661890, 9663785,
+ 9667501, 9673542, 9677459, 9679480, 9685306, 9687505, 9691140, 9697519,
+ 9700952, 9707187, 9711462, 9713549, 9718991, 9720868, 9725425, 9731354,
+ 9735070, 9737077, 9740960, 9747019, 9748745, 9755106, 9758775, 9760988,
+ 9766207, 9772500, 9776129, 9778410, 9785256, 9787203, 9791126, 9797245,
+ 9799929, 9801746, 9806279, 9812268, 9814638, 9820805, 9825104, 9827259,
+ 9830549, 9836670, 9841067, 9843008, 9849346, 9851625, 9855804, 9862103,
+ 9866579, 9868728, 9872493, 9878662, 9881540, 9887535, 9891578, 9893393,
+ 9896946, 9902873, 9906892, 9908775, 9914725, 9916814, 9920603, 9926832,
+ 9932340, 9934559, 9938698, 9945057, 9946275, 9952328, 9956765, 9958774,
+ 9963547, 9965808, 9969957, 9976270, 9978508, 9984615, 9989042, 9991001,
+ 9995741, 10001718, 10005731, 10007560, 10014538, 10016673, 10020468, 10026655,
+ 10029948, 10032023, 10035778, 10042025, 10043883, 10049792, 10053845, 10055742,
+ 10061498, 10067537, 10071940, 10073967, 10079277, 10081478, 10085651, 10092024,
+ 10096342, 10098237, 10102760, 10108675, 10110017, 10116266, 10120575, 10122644,
+ 10126096, 10132475, 10136110, 10138309, 10144135, 10146156, 10150073, 10156114,
+ 10161585, 10163546, 10167439, 10173540, 10176294, 10182605, 10186264, 10188531,
+ 10190967, 10197148, 10201417, 10203554, 10210016, 10211851, 10216414, 10222389,
+ 10225026, 10231145, 10235068, 10237015, 10243861, 10246142, 10249771, 10256064,
+ 10258500, 10260655, 10264954, 10271121, 10273491, 10279480, 10284013, 10285830,
+ 10290917, 10296846, 10301403, 10303280, 10308722, 10310809, 10315084, 10321319,
+ 10324771, 10326984, 10330653, 10337014, 10338740, 10344799, 10348682, 10350689,
+ 10355535, 10361764, 10365553, 10367642, 10373592, 10375475, 10379494, 10385421,
+ 10391177, 10393186, 10397623, 10403676, 10404894, 10411253, 10415392, 10417611,
+ 10420264, 10426563, 10430742, 10433021, 10439359, 10441300, 10445697, 10451818,
+ 10456558, 10458373, 10462416, 10468411, 10471289, 10477458, 10481223, 10483372,
+ 10486557, 10492918, 10496547, 10498760, 10504586, 10506593, 10510516, 10516575,
+ 10522331, 10524208, 10528741, 10534670, 10536012, 10542247, 10546546, 10548633,
+ 10551418, 10557585, 10561860, 10564015, 10570477, 10572294, 10576851, 10582840,
+ 10587580, 10589527, 10593410, 10599529, 10602283, 10608576, 10612245, 10614526,
+ 10618320, 10624315, 10628334, 10630149, 10637127, 10639276, 10643065, 10649234,
+ 10651670, 10653949, 10658088, 10664387, 10666625, 10672746, 10677183, 10679124,
+ 10684087, 10690140, 10694537, 10696546, 10701856, 10704075, 10708254, 10714613,
+ 10718065, 10720154, 10723919, 10730148, 10732006, 10737933, 10741976, 10743859,
+ 10751620, 10753647, 10758074, 10764113, 10765331, 10771704, 10775853, 10778054,
+ 10781506, 10787753, 10791548, 10793623, 10799573, 10801470, 10805483, 10811392,
+ 10816995, 10818824, 10822877, 10828854, 10831732, 10837919, 10841674, 10843809,
+ 10846245, 10852558, 10856731, 10858992, 10865330, 10867289, 10871692, 10877799,
+ 10881097, 10883234, 10887543, 10893724, 10896094, 10902069, 10906592, 10908427,
+ 10913167, 10919268, 10923185, 10925146, 10931992, 10934259, 10937894, 10944205,
+ 10947374, 10949573, 10953232, 10959611, 10961337, 10967378, 10971271, 10973292,
+ 10979048, 10984963, 10989526, 10991421, 10996863, 10998932, 11003201, 11009450,
+ 11010247, 11016236, 11020793, 11022610, 11029072, 11031227, 11035502, 11041669,
+ 11046145, 11048426, 11052095, 11058388, 11061142, 11067261, 11071144, 11073091,
+ 11076512, 11082571, 11086494, 11088501, 11094327, 11096540, 11100169, 11106530,
+ 11112038, 11114125, 11118424, 11124659, 11126001, 11131930, 11136463, 11138340,
+ 11142666, 11149025, 11153204, 11155423, 11160733, 11162742, 11167139, 11173192,
+ 11176908, 11178791, 11182834, 11188761, 11190619, 11196848, 11200613, 11202702,
+ 11208045, 11214214, 11218003, 11220152, 11227130, 11228945, 11232964, 11238959,
+ 11241643, 11243584, 11248021, 11254142, 11256380, 11262679, 11266818, 11269097,
+ 11275614, 11277749, 11281504, 11287691, 11290569, 11296546, 11300599, 11302428,
+ 11305112, 11311219, 11315622, 11317581, 11323919, 11326180, 11330353, 11336666,
+ 11341369, 11343570, 11347719, 11354092, 11355310, 11361349, 11365776, 11367803,
+ 11371519, 11377428, 11381441, 11383338, 11389288, 11391363, 11395158, 11401405,
+ 11406227, 11408248, 11412141, 11418182, 11419908, 11426287, 11429946, 11432145,
+ 11437653, 11443902, 11448171, 11450240, 11455682, 11457577, 11462140, 11468055,
+ 11471092, 11472927, 11477450, 11483425, 11485795, 11491976, 11496285, 11498422,
+ 11502898, 11509209, 11512844, 11515111, 11521957, 11523918, 11527835, 11533936,
+ 11535529, 11541570, 11546007, 11548028, 11554366, 11556565, 11560704, 11567083,
+ 11569519, 11571588, 11575377, 11581626, 11584504, 11590419, 11594438, 11596333,
+ 11601870, 11607845, 11611888, 11613723, 11619673, 11621810, 11625575, 11631756,
+ 11635208, 11637475, 11641654, 11647965, 11649183, 11655284, 11659681, 11661642,
+ 11666020, 11672207, 11676506, 11678641, 11684083, 11685912, 11690445, 11696422,
+ 11702178, 11704137, 11708060, 11714167, 11715893, 11722206, 11725835, 11728096,
+ 11731203, 11737576, 11741245, 11743446, 11750292, 11752319, 11756202, 11762241,
+ 11766981, 11768878, 11773435, 11779344, 11781714, 11787961, 11792236, 11794311,
+ 11798832, 11801051, 11804686, 11811045, 11813799, 11819852, 11823769, 11825778,
+ 11830518, 11836445, 11840968, 11842851, 11849313, 11851402, 11855711, 11861940,
+ 11864663, 11866812, 11871081, 11877250, 11878592, 11884587, 11889150, 11890965,
+ 11896721, 11902842, 11906735, 11908676, 11914502, 11916781, 11920440, 11926739,
+ 11931645, 11933462, 11937475, 11943464, 11945322, 11951489, 11955284, 11957439,
+ 11960891, 11967184, 11971333, 11973614, 11978924, 11980871, 11985298, 11991417,
+ 11996314, 11998321, 12002724, 12008783, 12011021, 12017382, 12021555, 12023768,
+ 12026204, 12032439, 12036194, 12038281, 12045259, 12047136, 12051189, 12057118,
+ 12060531, 12066712, 12070477, 12072614, 12078564, 12080399, 12084442, 12090417,
+ 12094133, 12096094, 12100491, 12106592, 12107810, 12114121, 12118300, 12120567,
+ 12125204, 12131583, 12135722, 12137921, 12144259, 12146280, 12150717, 12156758,
+ 12159442, 12161337, 12165356, 12171271, 12174149, 12180398, 12184187, 12186256,
+ 12190142, 12196181, 12200064, 12202091, 12208937, 12211138, 12214807, 12221180,
+ 12225656, 12227731, 12232006, 12238253, 12240623, 12246532, 12251089, 12252986,
+ 12255961, 12261938, 12266471, 12268300, 12273742, 12275877, 12280176, 12286363,
+ 12291871, 12294132, 12297761, 12304074, 12305800, 12311907, 12315830, 12317789,
+ 12323562, 12325377, 12329940, 12335935, 12337277, 12343446, 12347715, 12349864,
+ 12355372, 12361671, 12365330, 12367609, 12373435, 12375376, 12379269, 12385390,
+ 12388749, 12390758, 12394675, 12400728, 12403482, 12409841, 12413476, 12415695,
+ 12420171, 12426400, 12430709, 12432798, 12439260, 12441143, 12445666, 12451593,
+ 12454951, 12457164, 12461337, 12467698, 12469936, 12475995, 12480398, 12482405,
+ 12485089, 12491018, 12495071, 12496948, 12503926, 12506013, 12509768, 12516003,
+ 12521280, 12523435, 12527230, 12533397, 12535255, 12541244, 12545257, 12547074,
+ 12550790, 12556909, 12561336, 12563283, 12568593, 12570874, 12575023, 12581316,
+ 12585550, 12587685, 12591984, 12598171, 12599513, 12605490, 12610023, 12611852,
+ 12617608, 12623715, 12627638, 12629597, 12635423, 12637684, 12641313, 12647626,
+ 12650793, 12652994, 12656663, 12663036, 12665790, 12671829, 12675712, 12677739,
+ 12682479, 12688388, 12692945, 12694842, 12701304, 12703379, 12707654, 12713901,
+ 12717187, 12719208, 12723645, 12729686, 12731924, 12738303, 12742442, 12744641,
+ 12747077, 12753326, 12757115, 12759184, 12766162, 12768057, 12772076, 12777991,
+ 12783588, 12785423, 12789466, 12795441, 12797299, 12803480, 12807245, 12809382,
+ 12812834, 12819145, 12823324, 12825591, 12830901, 12832862, 12837259, 12843360,
+ 12847063, 12853052, 12857065, 12858882, 12864832, 12866987, 12870782, 12876949,
+ 12880401, 12882682, 12886831, 12893124, 12894342, 12900461, 12904888, 12906835,
+ 12911792, 12917851, 12922254, 12924261, 12930599, 12932812, 12936985, 12943346,
+ 12945782, 12947869, 12951624, 12957859, 12960737, 12966666, 12970719, 12972596,
+ 12976410, 12982769, 12986404, 12988623, 12995469, 12997478, 13001395, 13007448,
+ 13012188, 13014071, 13018594, 13024521, 13026891, 13033120, 13037429, 13039518,
+ 13042301, 13048470, 13052739, 13054888, 13060330, 13062145, 13066708, 13072703,
+ 13078459, 13080400, 13084293, 13090414, 13092140, 13098439, 13102098, 13104377,
+ 13109652, 13111679, 13115562, 13121601, 13124355, 13130728, 13134397, 13136598,
+ 13141074, 13147321, 13151596, 13153671, 13160133, 13162030, 13166587, 13172496,
+ 13175539, 13177368, 13181901, 13187878, 13189220, 13195407, 13199706, 13201841,
+ 13207349, 13213662, 13217291, 13219552, 13225378, 13227337, 13231260, 13237367,
+ 13242201, 13244338, 13248103, 13254284, 13256142, 13262117, 13266160, 13267995,
+ 13271711, 13277812, 13282209, 13284170, 13289480, 13291747, 13295926, 13302237,
+ 13306942, 13309141, 13313280, 13319659, 13321897, 13327938, 13332375, 13334396,
+ 13337080, 13342995, 13347014, 13348909, 13355887, 13357956, 13361745, 13367994,
+ 13370381, 13376742, 13380915, 13383128, 13389466, 13391473, 13395876, 13401935,
+ 13404619, 13406496, 13410549, 13416478, 13419356, 13425591, 13429346, 13431433,
+ 13436778, 13442945, 13446740, 13448895, 13454845, 13456662, 13460675, 13466664,
+ 13470380, 13472327, 13476754, 13482873, 13484091, 13490384, 13494533, 13496814,
+ 13501120, 13507115, 13511678, 13513493, 13518935, 13521084, 13525353, 13531522,
+ 13537030, 13539309, 13542968, 13549267, 13550993, 13557114, 13561007, 13562948,
+ 13566375, 13572428, 13576345, 13578354, 13585200, 13587419, 13591054, 13597413,
+ 13601889, 13603978, 13608287, 13614516, 13616886, 13622813, 13627336, 13629219,
+ 13635066, 13636881, 13640900, 13646895, 13649773, 13655942, 13659731, 13661880,
+ 13664316, 13670615, 13674754, 13677033, 13683371, 13685312, 13689749, 13695870,
+ 13700765, 13702774, 13707171, 13713224, 13714442, 13720801, 13724980, 13727199,
+ 13730651, 13736880, 13740645, 13742734, 13748684, 13750567, 13754610, 13760537,
+ 13765431, 13767644, 13771273, 13777634, 13779360, 13785419, 13789342, 13791349,
+ 13797105, 13803034, 13807567, 13809444, 13814886, 13816973, 13821272, 13827507,
+ 13830224, 13832379, 13836654, 13842821, 13845191, 13851180, 13855737, 13857554,
+ 13862294, 13868413, 13872296, 13874243, 13881089, 13883370, 13887039, 13893332,
+ 13893731, 13899912, 13904221, 13906358, 13912820, 13914655, 13919178, 13925153,
+ 13929893, 13931854, 13935771, 13941872, 13944626, 13950937, 13954572, 13956839,
+ 13959940, 13966319, 13969978, 13972177, 13978003, 13980024, 13983917, 13989958,
+ 13995714, 13997609, 14002172, 14008087, 14009429, 14015678, 14019947, 14022016,
+ 14026414, 14032453, 14036880, 14038907, 14044217, 14046418, 14050567, 14056940,
+ 14060392, 14062467, 14066262, 14072509, 14074367, 14080276, 14084289, 14086186,
+ 14091721, 14097698, 14101751, 14103580, 14110558, 14112693, 14116448, 14122635,
+ 14125071, 14127332, 14131505, 14137818, 14140056, 14146163, 14150566, 14152525,
+ 14159392, 14161611, 14165790, 14172149, 14173367, 14179420, 14183817, 14185826,
+ 14189542, 14195469, 14199512, 14201395, 14207345, 14209434, 14213199, 14219428,
+ 14224711, 14226860, 14230649, 14236818, 14239696, 14245691, 14249710, 14251525,
+ 14254209, 14260330, 14264767, 14266708, 14273046, 14275325, 14279464, 14285763,
+ 14289133, 14290950, 14295507, 14301496, 14303866, 14310033, 14314308, 14316463,
+ 14320939, 14327232, 14330901, 14333182, 14340028, 14341975, 14345858, 14351977,
+ 14355338, 14357345, 14361268, 14367327, 14369053, 14375414, 14379043, 14381256,
+ 14386764, 14392999, 14397298, 14399385, 14404827, 14406704, 14411237, 14417166,
+ 14418873, 14424914, 14428807, 14430828, 14436654, 14438853, 14442512, 14448891,
+ 14454399, 14456468, 14460737, 14466986, 14468328, 14474243, 14478806, 14480701,
+ 14483678, 14489653, 14494176, 14496011, 14502473, 14504610, 14508919, 14515100,
+ 14519576, 14521843, 14525478, 14531789, 14534543, 14540644, 14544561, 14546522,
+ 14550388, 14556575, 14560330, 14562465, 14569443, 14571272, 14575325, 14581302,
+ 14583986, 14585945, 14590348, 14596455, 14598693, 14605006, 14609179, 14611440,
+ 14616083, 14622456, 14626605, 14628806, 14634116, 14636143, 14640570, 14646609,
+ 14650325, 14652222, 14656235, 14662144, 14664002, 14670249, 14674044, 14676119,
+ 14681382, 14687693, 14691352, 14693619, 14700465, 14702426, 14706319, 14712420,
+ 14715104, 14716939, 14721502, 14727477, 14729847, 14736028, 14740297, 14742434,
+ 14747201, 14753450, 14757759, 14759828, 14765270, 14767165, 14771688, 14777603,
+ 14781319, 14783340, 14787257, 14793298, 14795024, 14801403, 14805038, 14807237,
+ 14812139, 14818048, 14822101, 14823998, 14829948, 14832023, 14835778, 14842025,
+ 14847533, 14849734, 14853907, 14860280, 14861498, 14867537, 14871940, 14873967,
+ 14876812, 14882919, 14887346, 14889305, 14895643, 14897904, 14902053, 14908366,
+ 14912842, 14914977, 14918772, 14924959, 14927837, 14933814, 14937827, 14939656,
+ 14944447, 14946388, 14950785, 14956906, 14959144, 14965443, 14969622, 14971901,
+ 14976377, 14982546, 14986311, 14988460, 14995438, 14997253, 15001296, 15007291,
+ 15010776, 15012659, 15016678, 15022605, 15024463, 15030692, 15034481, 15036570,
+ 15042078, 15048437, 15052576, 15054795, 15060105, 15062114, 15066551, 15072604,
+ 15076978, 15079065, 15083340, 15089575, 15090917, 15096846, 15101403, 15103280,
+ 15106996, 15113055, 15116938, 15118945, 15124771, 15126984, 15130653, 15137014,
+ 15142165, 15144446, 15148075, 15154368, 15157122, 15163241, 15167164, 15169111,
+ 15171795, 15177784, 15182317, 15184134, 15190596, 15192751, 15197050, 15203217,
+ 15206140, 15212055, 15216578, 15218473, 15223915, 15225984, 15230293, 15236542,
+ 15239994, 15242193, 15245828, 15252207, 15253933, 15259974, 15263891, 15265912,
+ 15271323, 15277424, 15281317, 15283278, 15290124, 15292391, 15296050, 15302361,
+ 15304797, 15306934, 15311203, 15317384, 15319754, 15325729, 15330292, 15332127,
+ 15335473, 15341786, 15345935, 15348196, 15354534, 15356493, 15360920, 15367027,
+ 15371767, 15373596, 15377609, 15383586, 15386464, 15392651, 15396446, 15398581,
+ 15401814, 15408061, 15411816, 15413891, 15419841, 15421738, 15425791, 15431700,
+ 15437456, 15439483, 15443886, 15449925, 15451143, 15457516, 15461689, 15463890,
+ 15469413, 15471502, 15475291, 15481520, 15483378, 15489305, 15493324, 15495207,
+ 15500963, 15507016, 15511453, 15513462, 15518772, 15520991, 15525130, 15531489,
+ 15534082, 15536361, 15540540, 15546839, 15549077, 15555198, 15559595, 15561536,
+ 15566276, 15572271, 15576314, 15578129, 15585107, 15587256, 15591021, 15597190,
+ 15601064, 15603011, 15606934, 15613053, 15615807, 15622100, 15625729, 15628010,
+ 15630446, 15636613, 15640912, 15643067, 15649529, 15651346, 15655879, 15661868,
+ 15666895, 15668772, 15673329, 15679258, 15680600, 15686835, 15691110, 15693197,
+ 15696649, 15703010, 15706679, 15708892, 15714718, 15716725, 15720608, 15726667,
+ 15729298, 15735417, 15739820, 15741767, 15747077, 15749358, 15753531, 15759824,
+ 15765332, 15767487, 15771242, 15777409, 15779267, 15785256, 15789309, 15791126,
+ 15794677, 15800606, 15804619, 15806496, 15813474, 15815561, 15819356, 15825591,
+ 15830067, 15832280, 15836429, 15842790, 15845028, 15851087, 15855514, 15857521,
+ 15860831, 15867060, 15871329, 15873418, 15879880, 15881763, 15886326, 15892253,
+ 15894937, 15896946, 15900839, 15906892, 15909646, 15916005, 15919664, 15921883,
+ 15927096, 15933395, 15937030, 15939309, 15945135, 15947076, 15950993, 15957114,
+ 15960830, 15962645, 15967168, 15973163, 15974505, 15980674, 15984983, 15987132,
+ 15994635, 15996896, 16000565, 16006878, 16008604, 16014711, 16018594, 16020553,
+ 16024269, 16030246, 16034803, 16036632, 16042074, 16044209, 16048484, 16054671,
+ 16059500, 16061575, 16065874, 16072121, 16074491, 16080400, 16084933, 16086830,
+ 16089514, 16095553, 16099476, 16101503, 16108349, 16110550, 16114179, 16120552,
+ 16124358, 16126253, 16130296, 16136211, 16139089, 16145338, 16149103, 16151172,
+ 16155648, 16162027, 16166206, 16168405, 16174743, 16176764, 16181161, 16187202,
+ 16190113, 16192074, 16196511, 16202612, 16203830, 16210141, 16214280, 16216547,
+ 16222055, 16228236, 16232025, 16234162, 16240112, 16241947, 16245966, 16251941,
+ 16253256, 16259491, 16263286, 16265373, 16272351, 16274228, 16278241, 16284170,
+ 16288910, 16290917, 16295344, 16301403, 16303641, 16310002, 16314151, 16316364,
+ 16319023, 16325316, 16329489, 16331770, 16337080, 16339027, 16343430, 16349549,
+ 16355305, 16357122, 16361175, 16367164, 16369022, 16375189, 16378944, 16381099,
+ 16385925, 16392046, 16395963, 16397904, 16403730, 16406009, 16409644, 16415943,
+ 16419395, 16421544, 16425853, 16432022, 16433364, 16439359, 16443882, 16445697,
+ 16450786, 16456713, 16461276, 16463159, 16469621, 16471710, 16475979, 16482208,
+ 16484644, 16486863, 16490522, 16496881, 16499635, 16505688, 16509581, 16511590,
+ 16518353, 16520250, 16524783, 16530692, 16533062, 16539309, 16543608, 16545683,
+ 16548119, 16554492, 16558121, 16560322, 16567168, 16569195, 16573118, 16579157,
+ 16584630, 16586589, 16590472, 16596579, 16598305, 16604618, 16608287, 16610548,
+ 16614000, 16620187, 16624462, 16626597, 16632039, 16633868, 16638425, 16644402,
+ 16648732, 16650999, 16655138, 16661449, 16662667, 16668768, 16673205, 16675166,
+ 16680922, 16686897, 16690916, 16692751, 16698701, 16700838, 16704627, 16710808,
+ 16714107, 16716176, 16719941, 16726190, 16729068, 16734983, 16739026, 16740921,
+ 16745661, 16751702, 16756099, 16758120, 16764458, 16766657, 16770836, 16777215
+};
+
+uint32_t gly24128Enc(uint32_t n) {
+ assert (n <= 4095);
+ return gly24128EncTbl[n];
}
-
-
-//Find roots of the error+erasure locator polynomial by Chien search
-
-for (i = 1; i <= nroots; i++) { reg[i] = lambda[i]; }
-count = 0 ;//number of roots of lambda(x)
-for (i = 1; i <= 63; i++) {
- q = 1 ;//lambda[0] is always 0
- for (j = DegLambda; j >= 1; j += -1) {
- if (reg[j] != 63) {
- reg[j] = (reg[j] + j) % 63;
- q = q ^ rsGFexp[reg[j]];
- }
- }
- if (q == 0) { //it is a root
- //store root (index-form) and error location number
- root[count] = i;
- locn[count] = i - 1;
- //if wehave max possible roots, abort search to save time
- count = count + 1; if (count == DegLambda) { break; }
- }
-}
-
-if (DegLambda != count) {
- //deg(lambda) unequal to number of roots => uncorrectable error detected
- count = -1;
- goto rsDecFinish;
-}
-
-
-
-//compute err+eras evaluator poly omega(x)
-// = s(x)*lambda(x) (modulo x**nroots). in index form. Also find deg(omega).
-
-DegOmega = 0;
-for (i = 0; i <= nroots - 1; i++) {
- tmp = 0;
- if (DegLambda < i) { j = DegLambda; } else { j = i; }
- for ( /* j = j */ ; j >= 0; j += -1) {
- if ((S[i - j] != 63) && (lambda[j] != 63)) {
- tmp = tmp ^ rsGFexp[(S[i - j] + lambda[j]) % 63];
- }
- }
- if (tmp) { DegOmega = i; }
- omega[i] = rsGFlog[tmp];
-}
-omega[nroots] = 63;
-
-
-//compute error values in poly-form:
-// num1 = omega(inv(X(l)))
-// num2 = inv(X(l))**(FCR - 1)
-// den = lambda_pr(inv(X(l)))
-
-for (j = count - 1; j >= 0; j += -1) {
- num1 = 0;
- for (i = DegOmega; i >= 0; i += -1) {
- if (omega[i] != 63) {
- num1 = num1 ^ rsGFexp[(omega[i] + i * root[j]) % 63];
- }
- }
- num2 = rsGFexp[0];
- den = 0;
-
- // lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i]
- if (DegLambda < nroots) { i = DegLambda; } else { i = nroots; }
- for (i = i & ~1; i >= 0; i += -2) {
- if (lambda[i + 1] != 63) {
- den = den ^ rsGFexp[(lambda[i + 1] + i * root[j]) % 63];
- }
- }
- if (den == 0) { count = -1; goto rsDecFinish; }
-
- // apply error to data
- if (num1 != 0) {
- if (locn[j] < FirstInfo) { count = -1; goto rsDecFinish ; } //added by me
- HB[locn[j]] = HB[locn[j]] ^ (rsGFexp[(rsGFlog[num1] + rsGFlog[num2] + 63 - rsGFlog[den]) % 63]);
- }
-}
-
-
-rsDecFinish:
-return (count);
-
-}
-
-/*********************************************************************/
-/*********************************************************************/
-/*********************************************************************/
-
uint32_t gly23127GetSyn (uint32_t pattern) {
+ uint32_t aux = 0x400000;
-uint32_t aux = 0x400000;
-
-while(pattern & 0xFFFFF800) {
- while ((aux & pattern) == 0) {
- aux = aux >> 1;
- }
- pattern = pattern ^ (aux / 0x800 * 0xC75) ;//generator is C75
-}
-
-return pattern;
-
+ while(pattern & 0xFFFFF800) {
+ while ((aux & pattern) == 0) {
+ aux = aux >> 1;
+ }
+ pattern = pattern ^ (aux / 0x800 * 0xC75) ;//generator is C75
+ }
+ return pattern;
}
-uint32_t gly24128Dec (uint32_t n) {
-
-//based on gly23127Dec
-
-uint32_t CW = n >> 1 ; //toss the parity bit
-uint32_t correction = gly23127DecTbl[gly23127GetSyn(CW)];
-CW = (CW ^ correction) >> 11;
-
-return CW;
-
+uint32_t gly24128Dec (uint32_t n) { //based on gly23127Dec
+ uint32_t CW = n >> 1 ; //toss the parity bit
+ uint32_t correction = gly23127DecTbl[gly23127GetSyn(CW)];
+ CW = (CW ^ correction) >> 11;
+ return CW;
}
uint32_t gly23127Dec (uint32_t CW) {
uint32_t correction = gly23127DecTbl[gly23127GetSyn(CW)];
@@ -464,109 +700,3 @@ uint32_t gly23127Dec (uint32_t CW) {
return CW;
}
-void ProcHDU(const_bit_vector A) {
-int i, j, k, ec;
-uint8_t HB[63]; // "hexbit" array
-
-//header code word is 324 dibits (padded by 5 trailing zero dibits)
-// 324 dibits = 648 bits = 36 18-bit Golay codewords
-
-//do (18,6,8) shortened Golay decode - make 36 hexbits for rs dec
-for (i = 0; i <= 26; i++) {
- HB[i] = 0;
-}
-k = 0;
-for (i = 0; i < 36; i ++) { // 36 codewords
- uint32_t CW = 0;
- for (j = 0; j < 18; j++) { // 18 bits / cw
- CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
- }
- HB[27 + i] = gly24128Dec(CW) & 63;
-}
-
-//do (36,20,17) RS decode
-ec = rsDec(16, 27, HB);
-//120 info bits = 20 hexbits: (27..46)
- //72 bits MI: (27..38)
- // 8 bits MFID
- // 8 bits ALGID
- //16 bits KID
- //16 bits TGID
-
-uint32_t MFID = HB[39] * 4 + (HB[40] >> 4);
-uint32_t ALGID = (HB[40] & 15) * 16 + (HB[41] >> 2);
-uint32_t KID = (HB[41] & 3) * 16384 + HB[42] * 256 + HB[43] * 4 + (HB[44] >> 4);
-uint32_t TGID = (HB[44] & 15) * 4096 + HB[45] * 64 + HB[46];
-
-fprintf (stderr, " HDU: rc %d mfid %x alg %x kid %x tgid %d", ec, MFID, ALGID, KID, TGID);
-
-}
-
-void ProcLLDU(const_bit_vector A, uint8_t HB[]) {
-int i, j, k;
-for (i = 0; i <= 38; i++) {
- HB[i] = 0;
-}
-k = 0;
-for (i = 0; i < 24; i ++) { // 24 10-bit codewords
- uint32_t CW = 0;
- for (j = 0; j < 10; j++) { // 10 bits / cw
- CW = (CW << 1) + A [ imbe_ldu_ls_data_bits[k++] ];
- }
- HB[39 + i] = hmg1063Dec( CW >> 4, CW & 0xF );
-}
-
-}
-
-void ProcLC(uint8_t HB[]) {
- int ec = rsDec(12, 39, HB);
- int pb = HB[39] >> 5;
- int sf = (HB[39] & 16) >> 4;
- int lco = (HB[39] & 15) * 4 + (HB[40] >> 4);
- fprintf(stderr, " LC: rc %d pb %d sf %d lco %d", ec, pb, sf, lco);
-}
-
-void ProcLDU1(const_bit_vector A) {
- uint8_t HB[63]; // "hexbit" array
-
- ProcLLDU(A, HB);
- ProcLC(HB);
-}
-
-void ProcLDU2(const_bit_vector A) {
- uint8_t HB[63]; // "hexbit" array
-
- ProcLLDU(A, HB);
- int ec = rsDec(8, 39, HB);
-
- uint32_t ALGID = HB[51] * 4 + (HB[52] >> 4);
- uint32_t KID = (HB[52] & 15) * 4096 + HB[53] * 64 + HB[54];
-
- fprintf(stderr, " LDU2: rc %d ALGID %x KID %x MI ", ec, ALGID, KID);
- for (int i = 39; i <= 50; i++) {
- fprintf(stderr, "%02x ", HB[ i ]);
- }
- // fprintf(stderr, "\n");
-}
-
-void ProcTDU(const_bit_vector A) {
-uint8_t HB[63]; // "hexbit" array
-
-int i, j, k;
-for (i = 0; i <= 38; i++) {
- HB[i] = 0;
-}
-k = 0;
-for (i = 0; i <= 22; i += 2) {
- uint32_t CW = 0;
- for (j = 0; j < 12; j++) { // 12 24-bit codewords
- CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
- CW = (CW << 1) + A [ hdu_codeword_bits[k++] ];
- }
- uint32_t D = gly24128Dec(CW);
- HB[39 + i] = D >> 6;
- HB[40 + i] = D & 63;
-}
-ProcLC(HB);
-}
-
diff --git a/op25/gr-op25_repeater/lib/rs.h b/op25/gr-op25_repeater/lib/rs.h
index 37c7c21..d45093f 100644
--- a/op25/gr-op25_repeater/lib/rs.h
+++ b/op25/gr-op25_repeater/lib/rs.h
@@ -5,12 +5,8 @@
#include <stdlib.h>
#include <stdint.h>
#include <vector>
-#include <op25_imbe_frame.h>
-void ProcHDU(const_bit_vector A);
-void ProcTDU(const_bit_vector A);
-void ProcLDU1(const_bit_vector A);
-void ProcLDU2(const_bit_vector A);
+uint32_t gly24128Enc (uint32_t n) ;
uint32_t gly24128Dec (uint32_t n) ;
uint32_t gly23127Dec (uint32_t n) ;
diff --git a/op25/gr-op25_repeater/lib/rx_sync.cc b/op25/gr-op25_repeater/lib/rx_sync.cc
new file mode 100644
index 0000000..bf6c359
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/rx_sync.cc
@@ -0,0 +1,823 @@
+// P25 Decoder (C) Copyright 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <iostream>
+#include <deque>
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "rx_sync.h"
+
+#include "bit_utils.h"
+
+#include "check_frame_sync.h"
+
+#include "p25p2_vf.h"
+#include "mbelib.h"
+#include "ambe.h"
+#include "rs.h"
+#include "crc16.h"
+
+#include "ysf_const.h"
+#include "dmr_const.h"
+#include "p25_frame.h"
+#include "op25_imbe_frame.h"
+#include "software_imbe_decoder.h"
+#include "op25_audio.h"
+
+namespace gr{
+ namespace op25_repeater{
+
+void rx_sync::cbuf_insert(const uint8_t c) {
+ d_cbuf[d_cbuf_idx] = c;
+ d_cbuf[d_cbuf_idx + CBUF_SIZE] = c;
+ d_cbuf_idx = (d_cbuf_idx + 1) % CBUF_SIZE;
+}
+
+void rx_sync::sync_reset(void) {
+ d_threshold = 0;
+ d_shift_reg = 0;
+ d_unmute_until[0] = 0;
+ d_unmute_until[1] = 0;
+}
+
+static inline void debug_dump(const char* s, const uint8_t p[], int l) {
+ char buf[64];
+ for (int i=0; i<l; i++) {
+ if (i*2+3 >= sizeof(buf))
+ break;
+ sprintf(buf+i*2, "%02x", p[i]);
+ }
+ fprintf(stderr, "%s: %s\n", s, buf);
+}
+
+static inline void cfill(uint8_t result[], const uint8_t src[], int len) {
+ for (int i=0; i<len; i++)
+ result[i] = load_i(src+i*8, 8);
+}
+
+static int ysf_decode_fich(const uint8_t src[100], uint8_t dest[32]) { // input is 100 dibits, result is 32 bits
+// return -1 on decode error, else 0
+ static const int pc[] = {0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
+ uint8_t buf[100];
+ for (int i=0; i<20; i++) {
+ for (int j=0; j<5; j++) {
+ buf[j+i*5] = src[i+j*20];
+ }
+ }
+ uint8_t dr = 0;
+ uint8_t ans[100];
+ /* fake trellis decode */
+ /* TODO: make less fake */
+ for (int i=0; i<100; i++) {
+ uint8_t sym = buf[i];
+ uint8_t d0 = ((dr << 1) | 0) & 0x1f;
+ uint8_t r0 = (pc[ d0 & 0x19 ] << 1) + pc[ d0 & 0x17];
+ uint8_t d1 = ((dr << 1) | 1) & 0x1f;
+ uint8_t r1 = (pc[ d1 & 0x19 ] << 1) + pc[ d1 & 0x17];
+ if (sym == r0) {
+ ans[i] = 0;
+ dr = d0;
+ } else if (sym == r1) {
+ ans[i] = 1;
+ dr = d1;
+ } else {
+ return -1; /* decode error */
+ }
+ }
+ uint8_t fich_bits[12*4];
+ store_i(gly24128Dec(load_i(ans+24*0, 24)), fich_bits+12*0, 12);
+ store_i(gly24128Dec(load_i(ans+24*1, 24)), fich_bits+12*1, 12);
+ store_i(gly24128Dec(load_i(ans+24*2, 24)), fich_bits+12*2, 12);
+ store_i(gly24128Dec(load_i(ans+24*3, 24)), fich_bits+12*3, 12);
+ uint16_t crc_result = crc16(fich_bits, 48);
+ if (crc_result != 0)
+ return -1; // crc failure
+ memcpy(dest, fich_bits, 32);
+ return 0;
+}
+
+void rx_sync::ysf_sync(const uint8_t dibitbuf[], bool& ysf_fullrate, bool& unmute) {
+ uint8_t fich_buf[32];
+ int rc = ysf_decode_fich(dibitbuf+20, fich_buf);
+ if (rc == 0) {
+ uint32_t fich = load_i(fich_buf, 32);
+ uint32_t dt = (fich >> 8) & 3;
+ d_shift_reg = dt;
+ }
+ switch(d_shift_reg) {
+ case 0: // voice/data mode 1
+ unmute = false;
+ break;
+ case 1: // data mode
+ unmute = false;
+ break;
+ case 2: // voice/data mode 2
+ unmute = true;
+ ysf_fullrate = false;
+ break;
+ case 3: // voice fr mode
+ unmute = true;
+ ysf_fullrate = true;
+ break;
+ }
+ if (d_debug > 5 && !unmute)
+ fprintf(stderr, "ysf_sync: muting audio: dt: %d, rc: %d\n", d_shift_reg, rc);
+}
+
+static int decode_embedded(uint8_t result_lc[72], const uint8_t src[32*4], int srclen) {
+// return code < 0 indicates decode failure
+ static const int lengths[] = {11, 11, 10, 10, 10, 10, 10};
+ int s_index = 0;
+ uint8_t decode[16*8];
+ uint8_t decode_lc[72+5];
+ int srcp = 0;
+ if (srclen != 32*4)
+ return -4;
+ for (int i=0; i<16; i++) {
+ for (int j=0; j<8; j++){
+ decode[i+16*j] = src[srcp++];
+ }
+ }
+ for (int i=0; i<7; i++) {
+ int v = load_i(&decode[16*i], 16);
+ int rc = hamming_16_11_decode(v);
+ if (rc < 0)
+ return rc;
+ store_i(rc, &decode_lc[11*i], 11);
+ memcpy(&result_lc[s_index], &decode_lc[11*i], lengths[i]);
+ s_index += lengths[i];
+ }
+ uint16_t r_csum = 0;
+ for (int i=0; i<5; i++) {
+ r_csum <<= 1;
+ r_csum |= decode_lc[(i+2)*11+10] & 1;
+ }
+ uint16_t c_csum = 0;
+ for (int i=0; i<9; i++) {
+ c_csum += load_i(&result_lc[i*8], 8);
+ }
+ c_csum = c_csum % 31;
+ if (r_csum != c_csum)
+ return -3;
+ return 0; // OK return
+}
+
+static void init_xlist(int * lp) {
+ for (int i=0; i < XLIST_SIZE; i++) {
+ lp[i] = -1;
+ }
+}
+
+static bool find_xlist(const int grp, const int * lp) {
+ for (int i=0; i < XLIST_SIZE; i++) {
+ if (lp[i] == grp && grp > 0)
+ return true;
+ }
+ return false;
+}
+
+static bool add_xlist(const int grp, int * lp) {
+// returns false if failed (grp bad, dup or list full), otherwise true
+ for (int i=0; i < XLIST_SIZE; i++) {
+ if (lp[i] == grp || grp < 1)
+ return false; // dup or group invalid
+ if (lp[i] == -1) {
+ lp[i] = grp;
+ return true;
+ }
+ }
+ return false;
+}
+
+static int count_xlist(const int * lp) {
+ int res=0;
+ for (int i=0; i < XLIST_SIZE; i++) {
+ if (lp[i] > 0)
+ res += 1;
+ }
+ return res;
+}
+
+void rx_sync::insert_whitelist(int grpaddr) {
+ bool rc = add_xlist(grpaddr, d_whitelist);
+ if (rc == false)
+ fprintf(stderr, "insert_whitelist failed for grp=%d- dup or list full\n", grpaddr);
+ else if (d_debug)
+ fprintf(stderr, "insert_whitelist complete for grp=%d\n", grpaddr);
+}
+
+void rx_sync::insert_blacklist(int grpaddr) {
+ bool rc = add_xlist(grpaddr, d_blacklist);
+ if (rc == false)
+ fprintf(stderr, "insert_blacklist failed for grp=%d- dup or list full\n", grpaddr);
+ else if (d_debug)
+ fprintf(stderr, "insert_blacklist complete for grp=%d\n", grpaddr);
+}
+
+void rx_sync::dmr_sync(const uint8_t bitbuf[], int& current_slot, bool& unmute) {
+ static const int slot_ids[] = {0, 1, 0, 0, 1, 1, 0, 1};
+ static const uint32_t BURST_SZ = 32; // embedded burst size (bits)
+ int tact;
+ int chan;
+ int fstype;
+ uint8_t tactbuf[sizeof(cach_tact_bits)];
+ uint8_t lc72[72];
+
+ for (size_t i=0; i<sizeof(cach_tact_bits); i++)
+ tactbuf[i] = bitbuf[cach_tact_bits[i]];
+ tact = hamming_7_4_decode[load_i(tactbuf, 7)];
+ chan = (tact>>2) & 1;
+ d_shift_reg = (d_shift_reg << 1) + chan;
+ current_slot = slot_ids[d_shift_reg & 7];
+
+ if (d_groupid_valid[current_slot] > 0)
+ d_groupid_valid[current_slot] -= 1;
+
+ uint64_t sync = load_reg64(bitbuf + (MODE_DATA[RX_TYPE_DMR].sync_offset << 1), MODE_DATA[RX_TYPE_DMR].sync_len);
+ if (check_frame_sync(DMR_VOICE_SYNC_MAGIC ^ sync, d_threshold, MODE_DATA[RX_TYPE_DMR].sync_len))
+ fstype = 1;
+ else if (check_frame_sync(DMR_IDLE_SYNC_MAGIC ^ sync, d_threshold, MODE_DATA[RX_TYPE_DMR].sync_len))
+ fstype = 2;
+ else
+ fstype = 0;
+ if (fstype > 0)
+ d_expires = d_symbol_count + MODE_DATA[d_current_type].expiration;
+ if (fstype == 1) {
+ if (!d_unmute_until[current_slot] && d_debug > 5)
+ fprintf(stderr, "%d unmute slot %d\n", d_symbol_count, current_slot);
+ d_unmute_until[current_slot] = d_symbol_count + MODE_DATA[d_current_type].expiration;
+ } else if (fstype == 2) {
+ if (d_unmute_until[current_slot] && d_debug > 5)
+ fprintf(stderr, "%d mute slot %d\n", d_symbol_count, current_slot);
+ d_unmute_until[current_slot] = 0;
+ }
+ if (d_unmute_until[current_slot] <= d_symbol_count) {
+ d_unmute_until[current_slot] = 0;
+ }
+ unmute = d_unmute_until[current_slot] > 0;
+ if (fstype == 0) {
+ uint16_t emb = (load_i(bitbuf+132, 8) << 8) + load_i(bitbuf+172, 8);
+ int emb_decode = hamming_16_7_decode(emb);
+ if (emb_decode >= 0) {
+ uint8_t cc = emb_decode >> 3;
+ uint8_t pi = (emb_decode >> 2) & 1;
+ uint8_t lcss = emb_decode & 3;
+ switch (lcss) {
+ case 0:
+ break;
+ case 1:
+ memcpy(d_burstb[current_slot], bitbuf+140, BURST_SZ);
+ d_burstl[current_slot] = BURST_SZ;
+ break;
+ case 2:
+ if (d_burstl[current_slot] && d_burstl[current_slot]+BURST_SZ <= sizeof(d_burstb)) {
+ memcpy(d_burstb[current_slot] + d_burstl[current_slot], bitbuf+140, BURST_SZ);
+ d_burstl[current_slot] += BURST_SZ;
+ int rc = decode_embedded(lc72, d_burstb[current_slot], d_burstl[current_slot]);
+ if (rc >= 0) {
+ int opcode = load_i(lc72+2, 6);
+ if (opcode == 0) { // group voice channel user
+ int grpaddr = load_i(lc72+24, 24);
+ if (grpaddr > 0) {
+ d_groupid[current_slot] = grpaddr;
+ d_groupid_valid[current_slot] = 20;
+ }
+ }
+ } else {
+ if (d_debug)
+ fprintf(stderr, "decode_embedded failed, code %d\n", rc);
+ }
+ }
+ d_burstl[current_slot] = 0;
+ break;
+ case 3:
+ if (d_burstl[current_slot] && d_burstl[current_slot]+BURST_SZ <= sizeof(d_burstb)) {
+ memcpy(d_burstb[current_slot] + d_burstl[current_slot], bitbuf+140, BURST_SZ);
+ d_burstl[current_slot] += BURST_SZ;
+ } else {
+ d_burstl[current_slot] = 0;
+ }
+ break;
+ }
+ } else {
+ d_burstl[current_slot] = 0;
+ }
+ }
+ if (unmute && d_groupid_valid[current_slot] > 0) {
+ if (count_xlist(d_whitelist) > 0 && !find_xlist(d_groupid[current_slot], d_whitelist)) {
+ if (d_debug)
+ fprintf(stderr, "%d group %d not in whitelist, muting slot %d\n", d_symbol_count, d_groupid[current_slot], current_slot);
+ unmute = 0;
+ if (d_unmute_until[current_slot] && d_debug > 5)
+ fprintf(stderr, "%d mute slot %d\n", d_symbol_count, current_slot);
+ d_unmute_until[current_slot] = 0;
+ }
+ if (count_xlist(d_blacklist) > 0 && find_xlist(d_groupid[current_slot], d_blacklist)) {
+ if (d_debug)
+ fprintf(stderr, "group %d in blacklist, muting slot %d\n", d_groupid[current_slot], current_slot);
+ unmute = 0;
+ if (d_unmute_until[current_slot] && d_debug > 5)
+ fprintf(stderr, "%d mute slot %d\n", d_symbol_count, current_slot);
+ d_unmute_until[current_slot] = 0;
+ }
+ }
+}
+
+rx_sync::rx_sync(const char * options, int debug, gr::msg_queue::sptr queue, int msgq_id) : // constructor
+ d_symbol_count(0),
+ d_sync_reg(0),
+ d_cbuf_idx(0),
+ d_current_type(RX_TYPE_NONE),
+ d_rx_count(0),
+ d_expires(0),
+ d_stereo(false),
+ d_debug(debug),
+ d_audio(options, debug),
+ d_msg_queue(queue),
+ d_previous_nxdn_sync(0),
+ d_previous_nxdn_sr_structure(-1),
+ d_previous_nxdn_sr_ran(-1),
+ d_msgq_id(msgq_id)
+{
+ mbe_initMbeParms (&cur_mp[0], &prev_mp[0], &enh_mp[0]);
+ mbe_initMbeParms (&cur_mp[1], &prev_mp[1], &enh_mp[1]);
+ sync_reset();
+ d_burstl[0] = 0;
+ d_burstl[1] = 0;
+ init_xlist(d_whitelist);
+ init_xlist(d_blacklist);
+ d_groupid[0] = 0;
+ d_groupid_valid[0] = 0;
+ d_groupid[1] = 0;
+ d_groupid_valid[1] = 0;
+}
+
+rx_sync::~rx_sync() // destructor
+{
+}
+
+
+void rx_sync::codeword(const uint8_t* cw, const enum codeword_types codeword_type, int slot_id) {
+ static const int x=4;
+ static const int y=26;
+ static const uint8_t majority[8] = {0,0,0,1,0,1,1,1};
+
+ int b[9];
+ uint8_t buf[4*26];
+ uint8_t tmp_codeword [144];
+ uint32_t E0, ET;
+ uint32_t u[8];
+ bool do_fullrate = false;
+ bool do_silence = false;
+ voice_codeword fullrate_cw(voice_codeword_sz);
+
+ switch(codeword_type) {
+ case CODEWORD_DMR:
+ case CODEWORD_NXDN_EHR: // halfrate
+ interleaver.process_vcw(cw, b);
+ if (b[0] < 120)
+ mbe_dequantizeAmbe2250Parms(&cur_mp[slot_id], &prev_mp[slot_id], b);
+ break;
+ case CODEWORD_DSTAR:
+ interleaver.decode_dstar(cw, b, false);
+ if (b[0] < 120)
+ mbe_dequantizeAmbe2400Parms(&cur_mp[slot_id], &prev_mp[slot_id], b);
+ break;
+ case CODEWORD_YSF_HALFRATE: // 104 bits
+ for (int i=0; i<x; i++) {
+ for (int j=0; j<y; j++)
+ buf[j+i*y] = cw[i+j*x];
+ }
+ ysf_scramble(buf, 104);
+ for (int i=0; i<27; i++)
+ tmp_codeword[i] = majority[ (buf[0+i*3] << 2) | (buf[1+i*3] << 1) | buf[2+i*3] ];
+
+ memcpy(tmp_codeword+27, buf+81, 22);
+ decode_49bit(b, tmp_codeword);
+ if (b[0] < 120)
+ mbe_dequantizeAmbe2250Parms(&cur_mp[slot_id], &prev_mp[slot_id], b);
+ break;
+ case CODEWORD_P25P2:
+ break;
+ case CODEWORD_P25P1: // 144 bits
+ for (int i=0; i<144; i++)
+ fullrate_cw[i] = cw[i];
+ imbe_header_decode(fullrate_cw, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7], E0, ET);
+ do_fullrate = true;
+ break;
+ case CODEWORD_YSF_FULLRATE: // 144 bits
+ for (int i=0; i<144; i++)
+ fullrate_cw[i] = cw[ysf_permutation[i]];
+ imbe_header_decode(fullrate_cw, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7], E0, ET);
+ do_fullrate = true;
+ break;
+ }
+ mbe_moveMbeParms (&cur_mp[slot_id], &prev_mp[slot_id]);
+ if (do_fullrate) {
+ d_software_decoder[slot_id].decode(fullrate_cw);
+ } else { /* halfrate */
+ if (b[0] >= 120) {
+ do_silence = true;
+ } else {
+ d_software_decoder[slot_id].decode_tap(cur_mp[slot_id].L, 0, cur_mp[slot_id].w0, &cur_mp[slot_id].Vl[1], &cur_mp[slot_id].Ml[1]);
+ }
+ }
+ audio_samples *samples = d_software_decoder[slot_id].audio();
+ float snd;
+ int16_t samp_buf[NSAMP_OUTPUT];
+ for (int i=0; i < NSAMP_OUTPUT; i++) {
+ if ((!do_silence) && samples->size() > 0) {
+ snd = samples->front();
+ samples->pop_front();
+ } else {
+ snd = 0;
+ }
+ if (do_fullrate)
+ snd *= 32768.0;
+ samp_buf[i] = snd;
+ }
+ output(samp_buf, slot_id);
+}
+
+void rx_sync::output(int16_t * samp_buf, const ssize_t slot_id) {
+ if (!d_stereo) {
+ d_audio.send_audio_channel(samp_buf, NSAMP_OUTPUT * sizeof(int16_t), slot_id);
+ return;
+ }
+}
+
+bool rx_sync::nxdn_gate(enum rx_types sync_detected) {
+ // if nxdn sync is detected while another type is already active,
+ // we require two consecutive nxdn frames before allowing change to new type
+ // (to try to prevent falsing due to shortened nxdn sync signature size)
+ // returns false if sync is either not present or should be ignored
+ static const int NXDN_FRSIZE = 192;
+ bool rc;
+ if (sync_detected == RX_TYPE_NONE)
+ return false;
+ if (sync_detected == d_current_type)
+ return true;
+ if (sync_detected != RX_TYPE_NXDN)
+ return true;
+ if (d_current_type == RX_TYPE_NONE)
+ return true;
+ // trying to switch from another type to nxdn
+ if (d_symbol_count - d_previous_nxdn_sync != NXDN_FRSIZE) {
+ if (d_debug)
+ fprintf(stderr, "ignoring NXDN frame sync in state %s, count %d, symbol %d\n", MODE_DATA[d_current_type].type, d_symbol_count - d_previous_nxdn_sync, d_symbol_count);
+ rc = false;
+ } else {
+ if (d_debug)
+ fprintf(stderr, "changing to NXDN from state %s, symbol %d\n", MODE_DATA[d_current_type].type, d_symbol_count);
+ rc = true;
+ }
+ d_previous_nxdn_sync = d_symbol_count;
+ return rc;
+}
+
+void rx_sync::rx_sym(const uint8_t sym)
+{
+ uint8_t bitbuf[864*2];
+ enum rx_types sync_detected = RX_TYPE_NONE;
+ int current_slot;
+ bool unmute;
+ uint8_t tmpcw[144];
+ bool ysf_fullrate;
+
+ d_symbol_count ++;
+ d_sync_reg = (d_sync_reg << 2) | (sym & 3);
+ for (int i = 1; i < RX_N_TYPES; i++) {
+ if (check_frame_sync(MODE_DATA[i].sync ^ d_sync_reg, (i == d_current_type) ? d_threshold : 0, MODE_DATA[i].sync_len)) {
+ sync_detected = (enum rx_types) i;
+ break;
+ }
+ }
+ cbuf_insert(sym);
+ if (d_current_type == RX_TYPE_NONE && sync_detected == RX_TYPE_NONE)
+ return;
+ d_rx_count ++;
+ if (d_debug && sync_detected == RX_TYPE_NONE && d_rx_count == MODE_DATA[d_current_type].sync_offset + (MODE_DATA[d_current_type].sync_len >> 1))
+ fprintf(stderr, "missing expected %s sync, symbol %d\n", MODE_DATA[d_current_type].type, d_symbol_count);
+ if (nxdn_gate(sync_detected)) {
+ if (d_current_type != sync_detected) {
+ d_current_type = sync_detected;
+ d_expires = d_symbol_count + MODE_DATA[d_current_type].expiration;
+ d_rx_count = 0;
+ }
+ if (d_rx_count != MODE_DATA[d_current_type].sync_offset + (MODE_DATA[d_current_type].sync_len >> 1)) {
+ if (d_debug)
+ fprintf(stderr, "resync at count %d symbol %d for protocol %s\n", d_rx_count, d_symbol_count, MODE_DATA[d_current_type].type);
+ sync_reset();
+ d_rx_count = MODE_DATA[d_current_type].sync_offset + (MODE_DATA[d_current_type].sync_len >> 1);
+ } else {
+ d_threshold = std::min(d_threshold + 1, (d_current_type == RX_TYPE_NXDN) ? 0 : 2);
+ }
+ d_expires = d_symbol_count + MODE_DATA[d_current_type].expiration;
+ }
+ if (d_symbol_count >= d_expires) {
+ if (d_debug)
+ fprintf(stderr, "%s: timeout, symbol %d\n", MODE_DATA[d_current_type].type, d_symbol_count);
+ d_current_type = RX_TYPE_NONE;
+ return;
+ }
+ if (d_rx_count < MODE_DATA[d_current_type].fragment_len)
+ return;
+ d_rx_count = 0;
+ int start_idx = d_cbuf_idx + CBUF_SIZE - MODE_DATA[d_current_type].fragment_len;
+ assert (start_idx >= 0);
+ uint8_t * symbol_ptr = d_cbuf+start_idx;
+ uint8_t * bit_ptr = symbol_ptr;
+ if (d_current_type != RX_TYPE_DSTAR) {
+ dibits_to_bits(bitbuf, symbol_ptr, MODE_DATA[d_current_type].fragment_len);
+ bit_ptr = bitbuf;
+ }
+ switch (d_current_type) {
+ case RX_TYPE_NONE:
+ break;
+ case RX_TYPE_P25:
+ for (unsigned int codeword_ct=0; codeword_ct < nof_voice_codewords; codeword_ct++) {
+ for (unsigned int i=0; i<voice_codeword_sz; i++)
+ tmpcw[i] = bit_ptr[voice_codeword_bits[codeword_ct][i]];
+ codeword(tmpcw, CODEWORD_P25P1, 0); // 144 bits
+ }
+ break;
+ case RX_TYPE_DMR:
+ dmr_sync(bit_ptr, current_slot, unmute);
+ if (!unmute)
+ break;
+ codeword(symbol_ptr+12, CODEWORD_DMR, current_slot);
+ memcpy(tmpcw, symbol_ptr+48, 18);
+ memcpy(tmpcw+18, symbol_ptr+90, 18);
+ codeword(tmpcw, CODEWORD_DMR, current_slot);
+ codeword(symbol_ptr+108, CODEWORD_DMR, current_slot);
+ break;
+ case RX_TYPE_DSTAR:
+ codeword(bit_ptr, CODEWORD_DSTAR, 0); // 72 bits = 72 symbols
+ break;
+ case RX_TYPE_YSF:
+ ysf_sync(symbol_ptr, ysf_fullrate, unmute);
+ if (!unmute)
+ break;
+ for (int vcw = 0; vcw < 5; vcw++) {
+ if (ysf_fullrate) {
+ codeword(bit_ptr + 2*(vcw*72 + 120), CODEWORD_YSF_FULLRATE, 0); // 144 bits
+ } else { /* halfrate */
+ codeword(bit_ptr + 2*(vcw*72 + 120 + 20), CODEWORD_YSF_HALFRATE, 0); // 104 bits
+ }
+ }
+ break;
+ case RX_TYPE_NXDN:
+ nxdn_frame(symbol_ptr);
+ break;
+ case RX_N_TYPES:
+ assert(0==1); /* should not occur */
+ break;
+ }
+}
+
+static inline void qmsg(const gr::msg_queue::sptr msg_queue, const uint8_t s[], int len, int msgq_id) {
+ unsigned char hdr[4] = {0xaa, 0x55, (unsigned char)((msgq_id >> 8) & 0xff), (unsigned char)(msgq_id & 0xff)};
+ if (!msg_queue->full_p()) {
+ gr::message::sptr msg = gr::message::make_from_string(std::string((char*)hdr, 4) + std::string((char*)s, len), -5, 0, 0);
+ msg_queue->insert_tail(msg);
+ }
+}
+
+void rx_sync::nxdn_frame(const uint8_t symbol_ptr[])
+{ // length is implicitly 192, with frame sync in first 10 dibits
+ uint8_t dbuf[182];
+ uint8_t lich;
+ int answer_len=0;
+ uint8_t answer[32];
+ uint8_t sacch_answer[32];
+ uint8_t lich_buf[8];
+ int lich_parity_received;
+ int lich_parity_computed;
+ int voice=0;
+ int facch=0;
+ int facch2=0;
+ int sacch=0;
+ int cac=0;
+ int sr_structure;
+ int sr_ran;
+
+ memcpy(lich_buf, symbol_ptr+10, sizeof(lich_buf));
+ nxdn_descramble(lich_buf, sizeof(lich_buf));
+ lich = 0;
+ for (int i=0; i<8; i++)
+ lich |= (lich_buf[i] >> 1) << (7-i);
+ lich_parity_received = lich & 1;
+ lich_parity_computed = ((lich >> 7) + (lich >> 6) + (lich >> 5) + (lich >> 4)) & 1;
+ lich = lich >> 1;
+ if (lich_parity_received != lich_parity_computed) {
+ if (d_debug)
+ fprintf(stderr, "NXDN lich parity error, ignoring frame at symbol %d\n", d_symbol_count);
+ return;
+ }
+ voice = 0;
+ facch = 0;
+ facch2 = 0;
+ sacch = 0;
+ cac = 0;
+ switch(lich) {
+ case 0x01: // CAC type
+ case 0x05:
+ cac = 1;
+ break;
+ case 0x28:
+ case 0x29:
+ case 0x2e:
+ case 0x2f:
+ case 0x48:
+ case 0x49:
+ case 0x4e:
+ case 0x4f:
+ case 0x69:
+ case 0x6f:
+ facch2 = 1;
+ break;
+ case 0x32:
+ case 0x33:
+ case 0x52:
+ case 0x53:
+ case 0x73:
+ voice = 2; // second half is voice
+ facch = 1;
+ sacch = 1;
+ break;
+ case 0x34:
+ case 0x35:
+ case 0x54:
+ case 0x55:
+ case 0x75:
+ voice = 1; // first half is voice
+ facch = 2;
+ sacch = 1;
+ break;
+ case 0x36:
+ case 0x37:
+ case 0x56:
+ case 0x57:
+ case 0x77:
+ voice = 3; // voice in both first and last
+ facch = 0;
+ sacch = 1;
+ break;
+ case 0x20:
+ case 0x21:
+ case 0x30:
+ case 0x31:
+ case 0x40:
+ case 0x41:
+ case 0x50:
+ case 0x51:
+ case 0x61:
+ case 0x71:
+ voice = 0;
+ facch = 3; // facch in both
+ sacch = 1;
+ break;
+ case 0x38:
+ case 0x39:
+ sacch = 1;
+ break;
+ default:
+ if (d_debug)
+ fprintf(stderr, "unsupported NXDN lich type 0x%x, symbol %d\n", lich, d_symbol_count);
+ voice = 0;
+ break;
+ } // end of switch(lich)
+ if (d_debug > 3)
+ fprintf(stderr, "nxdn lich %x voice %d facch %d sacch %d cac %d symbol %d\n", lich, voice, facch, sacch, cac, d_symbol_count);
+ if (voice || facch || facch2 || sacch || cac) {
+ memcpy(dbuf, symbol_ptr+10, sizeof(dbuf));
+ nxdn_descramble(dbuf, sizeof(dbuf));
+ }
+ if (voice & 1)
+ for (int vcw = 0; vcw < 2; vcw++)
+ codeword(dbuf+38+36*vcw, CODEWORD_NXDN_EHR, 0);
+ if (voice & 2)
+ for (int vcw = 2; vcw < 4; vcw++)
+ codeword(dbuf+38+36*vcw, CODEWORD_NXDN_EHR, 0);
+ if (sacch) {
+ bool non_superframe = (lich == 0x20 || lich == 0x21 || lich == 0x61 || lich == 0x40 || lich == 0x41) ? true : false;
+ answer_len = sizeof(sacch_answer);
+ nxdn_decode_sacch(dbuf+8, 30, sacch_answer, answer_len); // sacch size = 30 dibits, 26 bits returned if successful
+ sr_structure = load_i(sacch_answer, 2) & 3;
+ if (answer_len > 0 && non_superframe == true && sr_structure == 0) {
+ answer[0] = 's';
+ answer[1] = lich;
+ int nbytes = (answer_len + 7) / 8;
+ cfill(answer+2, sacch_answer, nbytes);
+ qmsg(d_msg_queue, answer, nbytes+2, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: sacch", answer, nbytes+2);
+ } else if (answer_len > 0 && non_superframe == false) {
+ sr_ran = load_i(sacch_answer+2, 6) & 0x3f;
+ bool ok = true;
+ if (d_previous_nxdn_sr_structure == -1 && sr_structure != 3)
+ ok = false;
+ else if (sr_structure < 3 && sr_structure+1 != d_previous_nxdn_sr_structure)
+ ok = false;
+ else if (sr_structure < 3 && d_previous_nxdn_sr_ran != sr_ran)
+ ok = false;
+ if (ok) {
+ int seg = 3 - sr_structure;
+ memcpy(d_sacch_buf + 18*seg, sacch_answer + 8, 18);
+ if (sr_structure > 0) {
+ d_previous_nxdn_sr_ran = sr_ran;
+ d_previous_nxdn_sr_structure = sr_structure;
+ } else {
+ answer[0] = 'S';
+ answer[1] = lich;
+ answer[2] = sr_ran;
+ int nbytes = 9;
+ cfill(answer+3, d_sacch_buf, nbytes);
+ qmsg(d_msg_queue, answer, nbytes+3, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: sacch", answer, nbytes+3);
+ d_previous_nxdn_sr_ran = -1;
+ d_previous_nxdn_sr_structure = -1;
+ }
+ } else {
+ d_previous_nxdn_sr_ran = -1;
+ d_previous_nxdn_sr_structure = -1;
+ }
+ }
+ }
+ if (facch & 1) {
+ answer_len = sizeof(answer)-2;
+ nxdn_decode_facch(dbuf+38, 72, answer+2, answer_len); // facch size = 72 dibits
+ if (answer_len > 0) {
+ answer[0] = 'f';
+ answer[1] = lich;
+ qmsg(d_msg_queue, answer, answer_len+2, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: facch", answer, answer_len+2);
+ }
+ }
+ if (facch & 2) {
+ if ((facch & 1) && !memcmp(dbuf+38, dbuf+38+72, 72)) {
+ if (d_debug > 5)
+ fprintf(stderr, "nxdn: skipping duplicate facch\n");
+ } else {
+ answer_len = sizeof(answer)-2;
+ nxdn_decode_facch(dbuf+38+72, 72, answer+2, answer_len);
+ if (answer_len > 0) {
+ answer[0] = 'f';
+ answer[1] = lich;
+ qmsg(d_msg_queue, answer, answer_len+2, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: facch", answer, answer_len+2);
+ }
+ }
+ }
+ if (facch2) {
+ answer_len = sizeof(answer)-2;
+ nxdn_decode_facch2_udch(dbuf+8, 174, answer+2, answer_len);
+ if (answer_len > 0) {
+ answer[0] = 'u';
+ answer[1] = lich;
+ qmsg(d_msg_queue, answer, answer_len+2, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: facch2", answer, answer_len+2);
+ }
+ }
+ if (cac) {
+ answer_len = sizeof(answer)-2;
+ nxdn_decode_cac(dbuf+8, 150, answer+2, answer_len);
+ if (answer_len > 0) {
+ answer[0] = 'c';
+ answer[1] = lich;
+ qmsg(d_msg_queue, answer, answer_len+2, d_msgq_id);
+ if (d_debug > 2)
+ debug_dump("nxdn: cac", answer, answer_len+2);
+ }
+ }
+}
+
+ } // end namespace op25_repeater
+} // end namespace gr
diff --git a/op25/gr-op25_repeater/lib/rx_sync.h b/op25/gr-op25_repeater/lib/rx_sync.h
new file mode 100644
index 0000000..35d9eb5
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/rx_sync.h
@@ -0,0 +1,146 @@
+// P25 Decoder (C) Copyright 2013, 2014, 2015, 2016, 2017 Max H. Parke KA1RBI
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+#ifndef INCLUDED_RX_SYNC_H
+#define INCLUDED_RX_SYNC_H
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <iostream>
+#include <deque>
+#include <assert.h>
+#include <gnuradio/msg_queue.h>
+
+#include "bit_utils.h"
+#include "check_frame_sync.h"
+
+#include "p25p2_vf.h"
+#include "mbelib.h"
+#include "ambe.h"
+
+#include "ysf_const.h"
+#include "dmr_const.h"
+#include "p25_frame.h"
+#include "op25_imbe_frame.h"
+#include "software_imbe_decoder.h"
+#include "op25_audio.h"
+#include "nxdn_const.h"
+#include "nxdn.h"
+
+namespace gr{
+ namespace op25_repeater{
+
+static const uint64_t DSTAR_FRAME_SYNC_MAGIC = 0x444445101440LL; // expanded into dibits
+
+enum rx_types {
+ RX_TYPE_NONE=0,
+ RX_TYPE_P25,
+ RX_TYPE_DMR,
+ RX_TYPE_DSTAR,
+ RX_TYPE_YSF,
+ RX_TYPE_NXDN,
+ RX_N_TYPES
+}; // also used as array index
+
+static const struct _mode_data {
+ const char * type;
+ int sync_len;
+ int sync_offset;
+ int fragment_len; // symbols
+ int expiration;
+ uint64_t sync;
+} MODE_DATA[RX_N_TYPES] = {
+ {"NONE", 0,0,0,0,0},
+ {"P25", 48,0,864,1728, P25_FRAME_SYNC_MAGIC},
+ {"DMR", 48,66,144,1728, DMR_VOICE_SYNC_MAGIC},
+ {"DSTAR", 48,72,96,2016*2, DSTAR_FRAME_SYNC_MAGIC},
+ {"YSF", 40,0,480,480*2, YSF_FRAME_SYNC_MAGIC},
+ {"NXDN", 20,0,192,192*2, NXDN_SYNC_MAGIC}
+}; // index order must match rx_types enum
+
+enum codeword_types {
+ CODEWORD_P25P1,
+ CODEWORD_P25P2,
+ CODEWORD_DMR,
+ CODEWORD_DSTAR,
+ CODEWORD_YSF_FULLRATE,
+ CODEWORD_YSF_HALFRATE,
+ CODEWORD_NXDN_EHR
+};
+
+#define XLIST_SIZE 256
+
+class rx_sync {
+public:
+ void rx_sym(const uint8_t sym);
+ void sync_reset(void);
+ rx_sync(const char * options, int debug, gr::msg_queue::sptr queue, int msgq_id);
+ ~rx_sync();
+ void insert_whitelist(int grpaddr);
+ void insert_blacklist(int grpaddr);
+private:
+ void cbuf_insert(const uint8_t c);
+ void dmr_sync(const uint8_t bitbuf[], int& current_slot, bool& unmute);
+ void ysf_sync(const uint8_t dibitbuf[], bool& ysf_fullrate, bool& unmute);
+ void codeword(const uint8_t* cw, const enum codeword_types codeword_type, int slot_id);
+ void output(int16_t * samp_buf, const ssize_t slot_id);
+ bool nxdn_gate(enum rx_types sync_detected);
+ void nxdn_frame(const uint8_t symbol_ptr[]);
+ static const int CBUF_SIZE=864;
+ static const int NSAMP_OUTPUT = 160;
+
+ unsigned int d_symbol_count;
+ uint64_t d_sync_reg;
+ uint8_t d_cbuf[CBUF_SIZE*2];
+ unsigned int d_cbuf_idx;
+ enum rx_types d_current_type;
+ int d_threshold;
+ int d_rx_count;
+ unsigned int d_expires;
+ int d_shift_reg;
+ unsigned int d_unmute_until[2];
+ p25p2_vf interleaver;
+ mbe_parms cur_mp[2];
+ mbe_parms prev_mp[2];
+ mbe_parms enh_mp[2];
+ software_imbe_decoder d_software_decoder[2];
+ std::deque<int16_t> d_output_queue[2];
+ bool d_stereo;
+ int d_debug;
+ op25_audio d_audio;
+ uint8_t d_burstb[2][32*4];
+ int d_burstl[2]; // in units of bits
+ int d_groupid[2];
+ unsigned int d_groupid_valid[2];
+ int d_whitelist[XLIST_SIZE];
+ int d_blacklist[XLIST_SIZE];
+ gr::msg_queue::sptr d_msg_queue;
+ int d_previous_nxdn_sync;
+ int d_previous_nxdn_sr_structure;
+ int d_previous_nxdn_sr_ran;
+ uint8_t d_sacch_buf[72];
+ int d_msgq_id;
+};
+
+ } // end namespace op25_repeater
+} // end namespace gr
+#endif // INCLUDED_RX_SYNC_H
diff --git a/op25/gr-op25_repeater/lib/software_imbe_decoder.cc b/op25/gr-op25_repeater/lib/software_imbe_decoder.cc
index 77c0b24..86191c6 100644
--- a/op25/gr-op25_repeater/lib/software_imbe_decoder.cc
+++ b/op25/gr-op25_repeater/lib/software_imbe_decoder.cc
@@ -734,6 +734,7 @@ software_imbe_decoder::software_imbe_decoder()
int i,j;
//initialize
OldL = 0;
+ L = 9;
Old = 1; New = 0;
psi1 = 0.0;
for(i=0; i < 58; i++) {
@@ -935,7 +936,6 @@ software_imbe_decoder::decode_tap(int _L, int _K, float _w0, const int * _v, con
int en, tmp_f;
L = _L;
- int K = _K;
w0 = _w0;
for(ell = 1; ell <= L; ell++) {
vee[ell][ New] = _v[ell - 1];
diff --git a/op25/gr-op25_repeater/lib/software_imbe_decoder.h b/op25/gr-op25_repeater/lib/software_imbe_decoder.h
index 7573bd4..cd22f9a 100644
--- a/op25/gr-op25_repeater/lib/software_imbe_decoder.h
+++ b/op25/gr-op25_repeater/lib/software_imbe_decoder.h
@@ -47,7 +47,7 @@ public:
/**
* Decode the compressed audio.
*
- * \cw in IMBE codeword (including parity check bits).
+ * cw in IMBE codeword (including parity check bits).
*/
virtual void decode(const voice_codeword& cw);
diff --git a/op25/gr-op25_repeater/lib/value_string.cc b/op25/gr-op25_repeater/lib/value_string.cc
new file mode 120000
index 0000000..2c72a9b
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/value_string.cc
@@ -0,0 +1 @@
+../../gr-op25/lib/value_string.cc \ No newline at end of file
diff --git a/op25/gr-op25_repeater/lib/value_string.h b/op25/gr-op25_repeater/lib/value_string.h
new file mode 120000
index 0000000..78bca90
--- /dev/null
+++ b/op25/gr-op25_repeater/lib/value_string.h
@@ -0,0 +1 @@
+../../gr-op25/lib/value_string.h \ No newline at end of file
diff --git a/op25/gr-op25_repeater/lib/vocoder_impl.cc b/op25/gr-op25_repeater/lib/vocoder_impl.cc
index 3f2032d..074f7df 100644
--- a/op25/gr-op25_repeater/lib/vocoder_impl.cc
+++ b/op25/gr-op25_repeater/lib/vocoder_impl.cc
@@ -40,6 +40,8 @@
namespace gr {
namespace op25_repeater {
+ static const int FRAGMENT_SIZE = 864;
+
vocoder::sptr
vocoder::make(bool encode_flag, bool verbose_flag, int stretch_amt, char* udp_host, int udp_port, bool raw_vectors_flag)
{
@@ -70,9 +72,12 @@ namespace gr {
output_queue_decode(),
opt_udp_port(udp_port),
opt_encode_flag(encode_flag),
- p1voice_encode(verbose_flag, stretch_amt, udp_host, udp_port, raw_vectors_flag, output_queue),
- p1voice_decode(verbose_flag, udp_host, udp_port, output_queue_decode)
+ op25audio(udp_host, udp_port, 0),
+ p1voice_encode(verbose_flag, stretch_amt, op25audio, raw_vectors_flag, output_queue),
+ p1voice_decode(verbose_flag, op25audio, output_queue_decode)
{
+ if (opt_encode_flag)
+ set_output_multiple(FRAGMENT_SIZE);
}
/*
@@ -131,15 +136,20 @@ vocoder_impl::general_work_encode (int noutput_items,
gr_vector_void_star &output_items)
{
const short *in = (const short *) input_items[0];
+ const int noutput_fragments = noutput_items / FRAGMENT_SIZE;
+ const int fragments_available = output_queue.size() / FRAGMENT_SIZE;
+ const int nsamples_consume = std::min(ninput_items[0], std::max(0,(noutput_fragments - fragments_available) * 9 * 160));
- p1voice_encode.compress_samp(in, ninput_items[0]);
+ if (nsamples_consume > 0) {
+ p1voice_encode.compress_samp(in, nsamples_consume);
- // Tell runtime system how many input items we consumed on
- // each input stream.
+ // Tell runtime system how many input items we consumed on
+ // each input stream.
- consume_each (ninput_items[0]);
+ consume_each (nsamples_consume);
+ }
- if (opt_udp_port > 0) // in udp option, we are a gr sink only
+ if (op25audio.enabled()) // in udp option, we are a gr sink only
return 0;
uint8_t *out = reinterpret_cast<uint8_t*>(output_items[0]);
diff --git a/op25/gr-op25_repeater/lib/vocoder_impl.h b/op25/gr-op25_repeater/lib/vocoder_impl.h
index ce709fd..95dc94a 100644
--- a/op25/gr-op25_repeater/lib/vocoder_impl.h
+++ b/op25/gr-op25_repeater/lib/vocoder_impl.h
@@ -29,6 +29,7 @@
#include <vector>
#include <deque>
+#include "op25_audio.h"
#include "p25p1_voice_encode.h"
#include "p25p1_voice_decode.h"
@@ -67,6 +68,7 @@ namespace gr {
std::deque<int16_t> output_queue_decode;
int opt_udp_port;
bool opt_encode_flag;
+ op25_audio op25audio;
p25p1_voice_encode p1voice_encode;
p25p1_voice_decode p1voice_decode;
diff --git a/op25/gr-op25_repeater/lib/ysf_const.h b/op25/gr-op25_repeater/lib/ysf_const.h
index 3538c50..a9883ab 100644
--- a/op25/gr-op25_repeater/lib/ysf_const.h
+++ b/op25/gr-op25_repeater/lib/ysf_const.h
@@ -1,5 +1,6 @@
//
// YSF Encoder (C) Copyright 2017 Max H. Parke KA1RBI
+// thx gr-ysf fr_vch_decoder_bb_impl.cc * Copyright 2015 Mathias Weyland *
//
// This file is part of OP25
//
@@ -21,6 +22,62 @@
#ifndef INCLUDED_YSF_CONST_H
#define INCLUDED_YSF_CONST_H
+#include <stdint.h>
+
+static void decode_49bit(int b[9], const uint8_t src[49]) {
+ for (int i=0; i<9; i++)
+ b[i] = 0;
+ b[0] |= src[0] << 6;
+ b[0] |= src[1] << 5;
+ b[0] |= src[2] << 4;
+ b[0] |= src[3] << 3;
+ b[1] |= src[4] << 4;
+ b[1] |= src[5] << 3;
+ b[1] |= src[6] << 2;
+ b[1] |= src[7] << 1;
+ b[2] |= src[8] << 4;
+ b[2] |= src[9] << 3;
+ b[2] |= src[10] << 2;
+ b[2] |= src[11] << 1;
+ b[3] |= src[12] << 8;
+ b[3] |= src[13] << 7;
+ b[3] |= src[14] << 6;
+ b[3] |= src[15] << 5;
+ b[3] |= src[16] << 4;
+ b[3] |= src[17] << 3;
+ b[3] |= src[18] << 2;
+ b[3] |= src[19] << 1;
+ b[4] |= src[20] << 6;
+ b[4] |= src[21] << 5;
+ b[4] |= src[22] << 4;
+ b[4] |= src[23] << 3;
+ b[5] |= src[24] << 4;
+ b[5] |= src[25] << 3;
+ b[5] |= src[26] << 2;
+ b[5] |= src[27] << 1;
+ b[6] |= src[28] << 3;
+ b[6] |= src[29] << 2;
+ b[6] |= src[30] << 1;
+ b[7] |= src[31] << 3;
+ b[7] |= src[32] << 2;
+ b[7] |= src[33] << 1;
+ b[8] |= src[34] << 2;
+ b[1] |= src[35];
+ b[2] |= src[36];
+ b[0] |= src[37] << 2;
+ b[0] |= src[38] << 1;
+ b[0] |= src[39];
+ b[3] |= src[40];
+ b[4] |= src[41] << 2;
+ b[4] |= src[42] << 1;
+ b[4] |= src[43];
+ b[5] |= src[44];
+ b[6] |= src[45];
+ b[7] |= src[46];
+ b[8] |= src[47] << 1;
+ b[8] |= src[48];
+}
+
static const int gly_24_12[] = {
0, 6379, 10558, 12757, 19095, 21116, 25513, 31554, 36294, 38189, 42232, 48147, 51025, 57274, 61039, 63108,
66407, 72588, 76377, 78514, 84464, 86299, 90318, 96293, 102049, 104010, 108447, 114548, 115766, 122077, 126216, 128483,
@@ -279,7 +336,9 @@ static const int gly_24_12[] = {
16648732, 16650999, 16655138, 16661449, 16662667, 16668768, 16673205, 16675166, 16680922, 16686897, 16690916, 16692751, 16698701, 16700838, 16704627, 16710808,
16714107, 16716176, 16719941, 16726190, 16729068, 16734983, 16739026, 16740921, 16745661, 16751702, 16756099, 16758120, 16764458, 16766657, 16770836, 16777215 };
-static const uint8_t scramble_code[180] = {
+static inline void ysf_scramble(uint8_t buf[], const int len)
+{ // buffer is (de)scrambled in place
+ static const uint8_t scramble_code[180] = {
1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1,
1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1,
@@ -292,11 +351,19 @@ static const uint8_t scramble_code[180] = {
0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
-};
+ };
+
+ assert(len <= (int)sizeof(scramble_code));
+ for (int i=0; i<len; i++) {
+ buf[i] = buf[i] ^ scramble_code[i];
+ }
+}
// frame sync dibits
static const uint8_t ysf_fs[20] = { 3, 1, 1, 0, 1, 3, 0, 1, 3, 0, 2, 1, 1, 2, 0, 3, 1, 0, 3, 1 };
+static const uint64_t YSF_FRAME_SYNC_MAGIC = 0xd471c9634dLL;
+
/* thx gr-ysf fr_vch_decoder_bb_impl.cc * Copyright 2015 Mathias Weyland */
// I hold Sylvain Munaut in high esteem for figuring this out.
static const uint8_t ysf_permutation[144] = {
diff --git a/op25/gr-op25_repeater/lib/ysf_tx_sb_impl.cc b/op25/gr-op25_repeater/lib/ysf_tx_sb_impl.cc
index 82ae1aa..bac42cb 100644
--- a/op25/gr-op25_repeater/lib/ysf_tx_sb_impl.cc
+++ b/op25/gr-op25_repeater/lib/ysf_tx_sb_impl.cc
@@ -29,7 +29,7 @@
#include "p25p2_vf.h"
#include "ysf_tx_sb_impl.h"
#include "ysf_const.h"
-#include <op25_imbe_frame.h>
+#include "op25_imbe_frame.h"
#include <vector>
#include <stdint.h>
@@ -52,7 +52,7 @@ static inline void print_result(char title[], const uint8_t r[], int len) {
}
#endif
-static inline int store_i(int reg, uint8_t val[], int len) {
+static inline void store_i(int reg, uint8_t val[], int len) {
for (int i=0; i<len; i++){
val[i] = (reg >> (len-1-i)) & 1;
}
@@ -165,14 +165,6 @@ static inline void generate_fich(uint8_t result[100], int fi, int cs, int cm, in
trellis_interleave(result, pre_trellis, 20, 5);
}
-static inline void scramble(uint8_t buf[], int len)
-{
- assert(len <= sizeof(scramble_code));
- for (int i=0; i<len; i++) {
- buf[i] = buf[i] ^ scramble_code[i];
- }
-}
-
// encode DCH - input is bits, result is dibits
static inline void generate_dch(uint8_t result[180], const uint8_t input[160])
{
@@ -180,7 +172,7 @@ static inline void generate_dch(uint8_t result[180], const uint8_t input[160])
memset(pre_trellis, 0, sizeof(pre_trellis));
memcpy(pre_trellis, input, 160);
- scramble(pre_trellis, 160);
+ ysf_scramble(pre_trellis, 160);
uint16_t crc = crc16(pre_trellis, 176);
store_i(crc, pre_trellis+160, 16);
@@ -199,7 +191,7 @@ static inline void generate_dch_vd2(uint8_t result[100], const uint8_t input[80]
memset(pre_trellis, 0, sizeof(pre_trellis));
memcpy(pre_trellis, input, 80);
- scramble(pre_trellis, 80);
+ ysf_scramble(pre_trellis, 80);
uint16_t crc = crc16(pre_trellis, 96);
store_i(crc, pre_trellis+80, 16);
@@ -223,7 +215,7 @@ static inline void generate_vch_vd2(uint8_t result[52], const uint8_t input[49])
}
memcpy(buf+81, input+27, 22);
buf[103] = 0;
- scramble(buf, 104);
+ ysf_scramble(buf, 104);
uint8_t bit_result[104];
int x=4;
diff --git a/op25/gr-op25_repeater/python/CMakeLists.txt b/op25/gr-op25_repeater/python/CMakeLists.txt
index 9958577..bb117a0 100644
--- a/op25/gr-op25_repeater/python/CMakeLists.txt
+++ b/op25/gr-op25_repeater/python/CMakeLists.txt
@@ -31,7 +31,7 @@ endif()
GR_PYTHON_INSTALL(
FILES
__init__.py
- DESTINATION ${GR_PYTHON_DIR}/op25_repeater
+ DESTINATION ${OP25_PYTHON_DIR}/op25_repeater
)
########################################################################
diff --git a/op25/gr-op25_repeater/python/__init__.py b/op25/gr-op25_repeater/python/__init__.py
index 4628ad6..bbbc45a 100644
--- a/op25/gr-op25_repeater/python/__init__.py
+++ b/op25/gr-op25_repeater/python/__init__.py
@@ -31,9 +31,9 @@ try:
from dl import RTLD_GLOBAL as _RTLD_GLOBAL
except ImportError:
try:
- from DLFCN import RTLD_GLOBAL as _RTLD_GLOBAL
+ from DLFCN import RTLD_GLOBAL as _RTLD_GLOBAL
except ImportError:
- pass
+ pass
if _RTLD_GLOBAL != 0:
_dlopenflags = sys.getdlopenflags()
@@ -42,7 +42,7 @@ if _RTLD_GLOBAL != 0:
# import swig generated symbols into the op25_repeater namespace
-from op25_repeater_swig import *
+from .op25_repeater_swig import *
# import any pure python here
#
diff --git a/op25/gr-op25_repeater/swig/CMakeLists.txt b/op25/gr-op25_repeater/swig/CMakeLists.txt
index 1d88bbd..50819d7 100644
--- a/op25/gr-op25_repeater/swig/CMakeLists.txt
+++ b/op25/gr-op25_repeater/swig/CMakeLists.txt
@@ -21,7 +21,7 @@
# Include swig generation macros
########################################################################
find_package(SWIG)
-find_package(PythonLibs 2)
+find_package(PythonLibs 3)
if(NOT SWIG_FOUND OR NOT PYTHONLIBS_FOUND)
return()
endif()
@@ -31,9 +31,7 @@ include(GrPython)
########################################################################
# Setup swig generation
########################################################################
-foreach(incdir ${GNURADIO_RUNTIME_INCLUDE_DIRS})
- list(APPEND GR_SWIG_INCLUDE_DIRS ${incdir}/gnuradio/swig)
-endforeach(incdir)
+set(GR_SWIG_INCLUDE_DIRS $<TARGET_PROPERTY:gnuradio::runtime_swig,INTERFACE_INCLUDE_DIRECTORIES>)
set(GR_SWIG_LIBRARIES gnuradio-op25_repeater)
set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/op25_repeater_swig_doc.i)
@@ -44,7 +42,7 @@ GR_SWIG_MAKE(op25_repeater_swig op25_repeater_swig.i)
########################################################################
# Install the build swig module
########################################################################
-GR_SWIG_INSTALL(TARGETS op25_repeater_swig DESTINATION ${GR_PYTHON_DIR}/op25_repeater)
+GR_SWIG_INSTALL(TARGETS op25_repeater_swig DESTINATION ${OP25_PYTHON_DIR}/op25_repeater)
########################################################################
# Install swig .i files for development
diff --git a/op25/gr-op25_repeater/swig/op25_repeater_swig.i b/op25/gr-op25_repeater/swig/op25_repeater_swig.i
index 1f75c5c..e44c5eb 100644
--- a/op25/gr-op25_repeater/swig/op25_repeater_swig.i
+++ b/op25/gr-op25_repeater/swig/op25_repeater_swig.i
@@ -11,10 +11,12 @@
#include "op25_repeater/vocoder.h"
#include "op25_repeater/gardner_costas_cc.h"
#include "op25_repeater/p25_frame_assembler.h"
+#include "op25_repeater/frame_assembler.h"
#include "op25_repeater/fsk4_slicer_fb.h"
#include "op25_repeater/ambe_encoder_sb.h"
#include "op25_repeater/dmr_bs_tx_bb.h"
#include "op25_repeater/ysf_tx_sb.h"
+#include "op25_repeater/nxdn_tx_sb.h"
#include "op25_repeater/dstar_tx_sb.h"
%}
@@ -27,6 +29,9 @@ GR_SWIG_BLOCK_MAGIC2(op25_repeater, dmr_bs_tx_bb);
%include "op25_repeater/ysf_tx_sb.h"
GR_SWIG_BLOCK_MAGIC2(op25_repeater, ysf_tx_sb);
+%include "op25_repeater/nxdn_tx_sb.h"
+GR_SWIG_BLOCK_MAGIC2(op25_repeater, nxdn_tx_sb);
+
%include "op25_repeater/dstar_tx_sb.h"
GR_SWIG_BLOCK_MAGIC2(op25_repeater, dstar_tx_sb);
@@ -35,8 +40,12 @@ GR_SWIG_BLOCK_MAGIC2(op25_repeater, vocoder);
%include "op25_repeater/gardner_costas_cc.h"
GR_SWIG_BLOCK_MAGIC2(op25_repeater, gardner_costas_cc);
+
%include "op25_repeater/p25_frame_assembler.h"
GR_SWIG_BLOCK_MAGIC2(op25_repeater, p25_frame_assembler);
+%include "op25_repeater/frame_assembler.h"
+GR_SWIG_BLOCK_MAGIC2(op25_repeater, frame_assembler);
+
%include "op25_repeater/fsk4_slicer_fb.h"
GR_SWIG_BLOCK_MAGIC2(op25_repeater, fsk4_slicer_fb);
diff --git a/op25/gr-op25_repeater/www/config/README b/op25/gr-op25_repeater/www/config/README
new file mode 100644
index 0000000..089e50a
--- /dev/null
+++ b/op25/gr-op25_repeater/www/config/README
@@ -0,0 +1 @@
+Saved JSON config files are stored in this directory
diff --git a/op25/gr-op25_repeater/www/config/default.json b/op25/gr-op25_repeater/www/config/default.json
new file mode 100644
index 0000000..a5031cc
--- /dev/null
+++ b/op25/gr-op25_repeater/www/config/default.json
@@ -0,0 +1,66 @@
+{
+ "backend-rx":{
+ "antenna":"",
+ "audio":false,
+ "audio-if":false,
+ "audio-input":"",
+ "audio-output":"default",
+ "calibration":0,
+ "costas-alpha":0.04,
+ "decim-amt":1,
+ "excess-bw":0.2,
+ "fine-tune":0,
+ "gain":null,
+ "gain-mu":0.025,
+ "gains":"",
+ "hamlib-model":null,
+ "ifile":"",
+ "input":"",
+ "logfile-workers":null,
+ "pause":false,
+ "raw-symbols":"",
+ "seek":0,
+ "tone-detect":false,
+ "udp-player":false,
+ "vocoder":false,
+ "wireshark":false,
+ "wireshark-host":"127.0.0.1"
+ },
+ "channels":[
+ {
+ "active":true,
+ "blacklist":[
+ ""
+ ],
+ "cclist":[
+ 0
+ ],
+ "demod_type":"cqpsk",
+ "destination":"udp://127.0.0.1:23456",
+ "filter_type":"rc",
+ "frequency":500000000,
+ "if_rate":24000,
+ "nac":null,
+ "name":"Channel1",
+ "phase2_tdma":false,
+ "plot":"",
+ "tgids":[],
+ "trunked":false,
+ "whitelist":[
+ ""
+ ]
+ }
+ ],
+ "devices":[
+ {
+ "active":true,
+ "args":"rtl",
+ "frequency":500000000,
+ "gains":"lna:45",
+ "name":"Device1",
+ "offset":0,
+ "ppm":0,
+ "rate":1000000
+ }
+ ]
+}
diff --git a/op25/gr-op25_repeater/www/images/1x1.png b/op25/gr-op25_repeater/www/images/1x1.png
new file mode 100644
index 0000000..559d2b0
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/1x1.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/csv.png b/op25/gr-op25_repeater/www/images/csv.png
new file mode 100644
index 0000000..7eacf29
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/csv.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/cx-lite.png b/op25/gr-op25_repeater/www/images/cx-lite.png
new file mode 100644
index 0000000..5fe073a
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/cx-lite.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/cx.png b/op25/gr-op25_repeater/www/images/cx.png
new file mode 100644
index 0000000..de6549f
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/cx.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/da.png b/op25/gr-op25_repeater/www/images/da.png
new file mode 100644
index 0000000..e3749ac
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/da.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/da2.png b/op25/gr-op25_repeater/www/images/da2.png
new file mode 100644
index 0000000..33f0f71
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/da2.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/favicon.ico b/op25/gr-op25_repeater/www/images/favicon.ico
new file mode 100644
index 0000000..b47738f
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/favicon.ico
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/loading.gif b/op25/gr-op25_repeater/www/images/loading.gif
new file mode 100644
index 0000000..c1d8473
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/loading.gif
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/op25-dark.png b/op25/gr-op25_repeater/www/images/op25-dark.png
new file mode 100644
index 0000000..4847302
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/op25-dark.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/op25.png b/op25/gr-op25_repeater/www/images/op25.png
new file mode 100644
index 0000000..a549857
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/op25.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/search.png b/op25/gr-op25_repeater/www/images/search.png
new file mode 100644
index 0000000..cf4df24
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/search.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/sort_asc.png b/op25/gr-op25_repeater/www/images/sort_asc.png
new file mode 100644
index 0000000..e1ba61a
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/sort_asc.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/sort_asc_disabled.png b/op25/gr-op25_repeater/www/images/sort_asc_disabled.png
new file mode 100644
index 0000000..fb11dfe
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/sort_asc_disabled.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/sort_both.png b/op25/gr-op25_repeater/www/images/sort_both.png
new file mode 100644
index 0000000..af5bc7c
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/sort_both.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/sort_desc.png b/op25/gr-op25_repeater/www/images/sort_desc.png
new file mode 100644
index 0000000..0e156de
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/sort_desc.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/sort_desc_disabled.png b/op25/gr-op25_repeater/www/images/sort_desc_disabled.png
new file mode 100644
index 0000000..c9fdd8a
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/sort_desc_disabled.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/status.png b/op25/gr-op25_repeater/www/images/status.png
new file mode 100644
index 0000000..9d28e48
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/status.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/images/temp.png b/op25/gr-op25_repeater/www/images/temp.png
new file mode 100644
index 0000000..c052f3f
--- /dev/null
+++ b/op25/gr-op25_repeater/www/images/temp.png
Binary files differ
diff --git a/op25/gr-op25_repeater/www/www-static/alias-edit.html b/op25/gr-op25_repeater/www/www-static/alias-edit.html
new file mode 100644
index 0000000..ffa564c
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/alias-edit.html
@@ -0,0 +1,116 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+<!DOCTYPE html>
+
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>OP25 - Edit System Site Alias</title>
+ <script src="jquery.js"></script>
+ <script src="editor.js"></script>
+ <script src="main.js"></script>
+ <script src="config.js"></script>
+ <script src="jquery.alerts.js"></script>
+ <link rel="stylesheet" type="text/css" id="style" href="main.css">
+ </head>
+ <body onload="javascript:tsv_onload();">
+ <a href="#" name="top"></a>
+ <div class="tsv-controls">
+ <!-- <table style="width: 705px; border-collapse: collapse; border: 0px solid var(~~bg-color);"> -->
+ <table class="tsv">
+ <tr colspan="2">
+ <td>
+ <div id="title" class="nac" style="font-weight: normal;">Editor - OP25</div>
+ </td>
+ <td>
+ <p align="right"><a href="#" onclick="window.close();" style="text-decoration: none;" title="Close">&#x274C;</a></p>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <button onclick="this.blur(); beginAlias();" id="btnLoad" title="Load from Server">Load</button>&nbsp;&nbsp;
+ <button onclick="this.blur(); saveAliasTable();"id="btnSave1" class="saveButton" title="Save to Server">Save</button>&nbsp;&nbsp;
+<!--
+ <button onclick="this.blur(); dispImport();" title="Import TSV or CSV">Import TODO</button>&nbsp;&nbsp;
+ <button onclick="tsv_csv();" title="Export as CSV">Export TODO</button>
+ -->
+ </td>
+ <td align='right'>
+ <span class="label">Status: </span>
+ <span id="message" class="value">Ready</span>
+ <img src="loading.gif" style="height: 15px;" id="loading">
+ </td>
+ </tr>
+ </table>
+
+ <br>
+ <input type="text" id="searchInput" style="width: 643px;" onkeyup="searchTsvTable()" placeholder="Filter" title="Search">
+ <div id="csv-upload" style="display: none;">
+ <table class=editor><th colspan="2">Import Data</th>
+ <tr><td>
+ <span class="label"> Select a CSV or TSV file to import. <br><br>
+ <input type="file" id="csvfile" name="filename">&nbsp;&nbsp;
+<!-- <button id="importnow" onclick="this.blur(); importNow();">Import Now</button> -->
+ </td>
+ <td style="width: 100px; text-align: center;">
+ <button onclick="document.getElementById('csvfile').value='';" style="width: 80px;"> Reset </button><br>
+ <button onclick="this.blur(); hideImport();" style="width: 80px;"> Cancel </button>
+ </td>
+ </tr>
+ </table>
+ <br><br>
+ </div>
+ </div>
+ <div id="save-div">
+ <br>&nbsp;&nbsp;
+ <!-- <button onclick="saveTable();"id="btnSave" class="saveButton">Save Talkgroups</button>&nbsp;&nbsp;<br>&nbsp;&nbsp; -->
+ <!-- <button onclick="window.location.href='#top;'"id="btnSave" class="saveButton">Top</button>&nbsp;&nbsp;<br>&nbsp; -->
+ </div>
+ <div id="main"></div>
+ <!-- Main Content Area -->
+ <div class="footer">
+ &nbsp;<br><button onclick="saveAliasTable();"id="btnSave2" class="saveButton">Save Talkgroups</button>
+ &nbsp;
+ &nbsp;
+
+ <button onclick="deleteSys()">Delete System</button>
+
+ &nbsp;
+ &nbsp;
+ <button onclick="up();">Go to Top</button>&nbsp;&nbsp;&nbsp;
+<!-- <button onclick="tsv_csv();">Export as CSV</button>&nbsp;&nbsp;&nbsp; -->
+ <button onclick="this.blur(); help();" class="btnHelp">Help</button>&nbsp;&nbsp;
+ <button onclick="window.close();">Close</button>
+ <br>
+ </div>
+ <div style="display: none;"> <!-- placeholder for the color values -->
+ <span id="loadSettings"></span>
+ <input type="color" class="accColor" id="acc1"></input>
+ <input type="color" class="accColor" id="acc2"></input>
+ <input type="color" class="valColor" id="valColor">
+ <input type="color" class="sysColor" id="sysColor"></input>
+ <input type="color" class="btnColor" id="btnColor"></input>
+ </div>
+
+ </body>
+</html>
diff --git a/op25/gr-op25_repeater/www/www-static/config.js b/op25/gr-op25_repeater/www/www-static/config.js
new file mode 100644
index 0000000..c394624
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/config.js
@@ -0,0 +1,616 @@
+// Copyright 2017, 2018, 2019, 2020, 2021 Max H. Parke KA1RBI
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+
+// Functions related to Online Config
+
+function find_parent(ele, tagname) {
+ while (ele) {
+ if (ele.nodeName == tagname)
+ return ele;
+ else if (ele.nodeName == 'HTML')
+ return null;
+ ele = ele.parentNode;
+ }
+ return null;
+}
+
+function f_command(ele, command) {
+ var myrow = find_parent(ele, 'TR');
+ var mytbl = find_parent(ele, 'TABLE');
+ amend_d(myrow, mytbl, command);
+}
+
+function edit_freq(freq, to_ui) {
+ var MHZ = 1000000;
+ if (to_ui) {
+ var f = freq / MHZ + '';
+ if (f.indexOf('.') == -1)
+ f += '.0';
+ return f;
+ } else {
+ var f = parseFloat(freq);
+ if (freq.indexOf('.'))
+ f *= MHZ;
+ return Math.round(f);
+ }
+}
+
+
+function edit_d(d, to_ui) {
+ var new_d = {};
+ var hexints = {
+ 'nac': 1
+ };
+ var ints = {
+ 'if_rate': 1,
+ 'ppm': 1,
+ 'rate': 1,
+ 'offset': 1,
+ 'nac': 1,
+ 'logfile-workers': 1,
+ 'decim-amt': 1,
+ 'seek': 1,
+ 'hamlib-model': 1
+ };
+ var bools = {
+ 'active': 1,
+ 'trunked': 1,
+ 'rate': 1,
+ 'offset': 1,
+ 'phase2_tdma': 1,
+ 'phase2-tdma': 1,
+ 'wireshark': 1,
+ 'udp-player': 1,
+ 'audio-if': 1,
+ 'tone-detect': 1,
+ 'vocoder': 1,
+ 'audio': 1,
+ 'pause': 1
+ };
+ var floats = {
+ 'costas-alpha': 1,
+ 'gain-mu': 1,
+ 'calibration': 1,
+ 'fine-tune': 1,
+ 'gain': 1,
+ 'excess-bw': 1,
+ 'offset': 1,
+ 'excess_bw': 1
+ };
+ var lists = {
+ 'blacklist': 1,
+ 'whitelist': 1,
+ 'cclist': 1
+ };
+ var freqs = {
+ 'frequency': 1,
+ 'cclist': 1
+ };
+ for (var k in d) {
+ if (!to_ui) {
+ if (d[k] == 'None')
+ new_d[k] = '';
+ else
+ new_d[k] = d[k];
+ if (k == 'plot' && !d[k].length)
+ new_d[k] = null;
+ if (k in ints) {
+ new_d[k] = parseInt(new_d[k]);
+ } else if (k in floats) {
+ new_d[k] = parseFloat(new_d[k]);
+ } else if (k in lists) {
+ var l = [];
+ if (new_d[k].length)
+ l = new_d[k].split(',');
+ if (k in freqs && new_d[k].length) {
+ var new_l = [];
+ for (var i in l)
+ new_l.push(edit_freq(l[i], to_ui));
+ new_d[k] = new_l;
+ } else {
+ new_d[k] = l;
+ }
+ } else if (k in freqs) {
+ new_d[k] = edit_freq(new_d[k], to_ui);
+ }
+ } else {
+ if (k in hexints) {
+ if (d[k] == null)
+ new_d[k] = '0x0';
+ else
+ new_d[k] = '0x' + d[k].toString(16);
+ } else if (k in ints) {
+ if (d[k] == null)
+ new_d[k] = '';
+ else
+ new_d[k] = d[k].toString(10);
+ } else if (k in lists) {
+ if (k in freqs) {
+ var new_l = [];
+ for (var i in d[k]) {
+ new_l.push(edit_freq(d[k][i], to_ui));
+ }
+ new_d[k] = new_l.join(',');
+ } else {
+ if (!d[k] || !d[k].length)
+ new_d[k] = [];
+ else
+ new_d[k] = d[k].join(',');
+ }
+ } else if (k in freqs) {
+ new_d[k] = edit_freq(d[k], to_ui);
+ } else {
+ new_d[k] = d[k];
+ }
+ }
+ }
+ return new_d;
+}
+
+
+function edit_l(cfg, to_ui) {
+ var new_d = {
+ 'devices': [],
+ 'channels': []
+ };
+ for (var device in cfg['devices'])
+ new_d['devices'].push(edit_d(cfg['devices'][device], to_ui));
+ for (var channel in cfg['channels'])
+ new_d['channels'].push(edit_d(cfg['channels'][channel], to_ui));
+ new_d['backend-rx'] = edit_d(cfg['backend-rx'], to_ui);
+ return new_d;
+}
+
+function amend_d(myrow, mytbl, command) {
+ var trunk_row = null;
+ if (mytbl.id == 'chtable')
+ trunk_row = find_next(myrow, 'TR');
+ if (command == 'delete') {
+ var ok = confirm('Confirm delete');
+ if (ok) {
+ myrow.parentNode.removeChild(myrow);
+ if (mytbl.id == 'chtable')
+ trunk_row.parentNode.removeChild(trunk_row);
+ }
+ } else if (command == 'clone') {
+ var newrow = myrow.cloneNode(true);
+ newrow.id = find_free_id('id_');
+ if (mytbl.id == 'chtable') {
+ var newrow2 = trunk_row.cloneNode(true);
+ newrow2.id = 'tr_' + newrow.id.substring(3);
+ if (trunk_row.nextSibling) {
+ myrow.parentNode.insertBefore(newrow2, trunk_row.nextSibling);
+ myrow.parentNode.insertBefore(newrow, trunk_row.nextSibling);
+ } else {
+ myrow.parentNode.appendChild(newrow);
+ myrow.parentNode.appendChild(newrow2);
+ }
+ } else {
+ if (myrow.nextSibling)
+ myrow.parentNode.insertBefore(newrow, myrow.nextSibling);
+ else
+ myrow.parentNode.appendChild(newrow);
+ }
+ } else if (command == 'new') {
+ var newrow = null;
+ var parent = null;
+ var pfx = 'id_';
+ if (mytbl.id == 'chtable') {
+ newrow = document.getElementById('chrow').cloneNode(true);
+ parent = document.getElementById('chrow').parentNode;
+ } else if (mytbl.id == 'devtable') {
+ newrow = document.getElementById('devrow').cloneNode(true);
+ parent = document.getElementById('devrow').parentNode;
+ } else if (mytbl.className == 'tgtable') {
+ newrow = mytbl.querySelector('.tgrow').cloneNode(true);
+ parent = mytbl.querySelector('.tgrow').parentNode;
+ pfx = 'tg_';
+ } else {
+ return null;
+ }
+ newrow.style['display'] = '';
+ newrow.id = find_free_id(pfx);
+ parent.appendChild(newrow);
+ if (mytbl.id == 'chtable') {
+ var newrow2 = document.getElementById('trrow').cloneNode(true);
+ newrow2.id = 'tr_' + newrow.id.substring(3);
+ parent.appendChild(newrow2);
+ }
+ return newrow;
+ }
+}
+
+function f_save_list(ele) {
+ var flist = [];
+ for (var nac in enable_status) {
+ if (enable_status[nac])
+ flist.push(nac.toString(10));
+ }
+
+ if (flist.length == 0) {
+ jAlert('Cannot disable all NACs - request ignored.', 'Warning');
+ }
+ document.getElementById('save_list_row').style['display'] = 'none';
+ enable_changed = false;
+ send_command('settings-enable', flist.join(','));
+}
+
+function f_enable_changed(ele, nac) {
+ enable_status[nac] = ele.checked;
+ enable_changed = true;
+ document.getElementById('save_list_row').style['display'] = '';
+}
+
+
+function config_list(d) {
+ var html = '';
+ html += '<select id="config_select" name="cfg-list">';
+ for (var file in d['data']) {
+ html += '<option value="' + d['data'][file] + '">' + d['data'][file] + '</option>';
+ }
+ html += '<option value="New Configuration">New Configuration</option>';
+ html += '</select>';
+ document.getElementById('cfg_list_area').innerHTML = html;
+}
+
+function config_data(d) {
+ var cfg = edit_l(d['data'], true);
+ open_editor();
+ var chtable = document.getElementById('chtable');
+ var devtable = document.getElementById('devtable');
+ var chrow = document.getElementById('chrow');
+ var devrow = document.getElementById('devrow');
+ for (var device in cfg['devices'])
+ rollup_row('dev', amend_d(devrow, devtable, 'new'), cfg['devices'][device]);
+ for (var channel in cfg['channels'])
+ rollup_row('ch', amend_d(chrow, chtable, 'new'), cfg['channels'][channel]);
+ rollup_rx_rows(cfg['backend-rx']);
+}
+
+
+function open_editor() {
+ document.getElementById('edit_settings').style['display'] = '';
+ var rows = document.querySelectorAll('.dynrow');
+ var ct = 0;
+ for (var r in rows) {
+ var row = rows[r];
+ ct += 1;
+ if (row.id && (row.id.substring(0, 3) == 'id_' || row.id.substring(0, 3) == 'tr_')) {
+ row.parentNode.removeChild(row);
+ }
+ }
+ var oldtbl = document.getElementById('rt_1');
+ if (oldtbl)
+ oldtbl.parentNode.removeChild(oldtbl);
+ var tbl = document.getElementById('rxopt-table');
+ var newtbl = tbl.cloneNode(true);
+ newtbl.id = 'rt_1';
+ newtbl.style['display'] = '';
+ var rxrow = newtbl.querySelector('.rxrow');
+ var advrow = newtbl.querySelector('.advrow');
+ rxrow.id = 'rx_1';
+ advrow.id = 'rx_2';
+ if (tbl.nextSibling)
+ tbl.parentNode.insertBefore(newtbl, tbl.nextSibling);
+ else
+ tbl.parentNode.appendChild(newtbl);
+}
+
+function find_next(e, tag) {
+ var n = e.nextSibling;
+ for (var i = 0; i < 25; i++) {
+ if (n == null)
+ return null;
+ if (n.nodeName == tag)
+ return n;
+ n = n.nextSibling;
+ }
+ return null;
+}
+
+function find_free_id(pfx) {
+ for (var seq = 1; seq < 5000; seq++) {
+ var test_id = pfx + seq;
+ var ele = document.getElementById(test_id);
+ if (!ele)
+ return test_id;
+ }
+ return null;
+}
+
+function f_trunked(e) {
+ var row = find_parent(e, 'TR');
+ var trrow = document.getElementById('tr_' + row.id.substring(3));
+ trrow['style']['display'] = e.checked ? '' : 'none';
+}
+
+function read_write_sel(sel_node, def) {
+ var result = [];
+ var elist = sel_node.querySelectorAll('option');
+ for (var e in elist) {
+ var ele = elist[e];
+ if (def) {
+ if (!def[sel_node.name])
+ return;
+ var options = def[sel_node.name].split(',');
+ var opts = {};
+ for (var o in options)
+ opts[options[o]] = 1;
+ if (ele.value in opts)
+ ele.selected = true;
+ else
+ ele.selected = false;
+ } else {
+ if (ele.selected)
+ result.push(ele.value);
+ }
+ }
+ if (!def)
+ return result.join();
+}
+
+function read_write(elist, def) {
+ var result = {};
+ for (var e in elist) {
+ var ele = elist[e];
+ if (ele.nodeName == 'INPUT') {
+ if (ele.type == 'text')
+ if (def)
+ ele.value = def[ele.name];
+ else
+ result[ele.name] = ele.value;
+ else if (ele.type == 'checkbox')
+ if (def)
+ ele.checked = def[ele.name];
+ else
+ result[ele.name] = ele.checked;
+ } else if (ele.nodeName == 'SELECT') {
+ if (def)
+ read_write_sel(ele, def);
+ else
+ result[ele.name] = read_write_sel(ele, def);
+ }
+ }
+ if (!def)
+ return result;
+}
+
+function rollup_row(which, row, def) {
+ var elements = Array.from(row.querySelectorAll('input,select'));
+ if (which == 'ch') {
+ var trrow = document.getElementById('tr_' + row.id.substring(3));
+ var trtable = trrow.querySelector('table.trtable');
+ elements = elements.concat(Array.from(trtable.querySelectorAll('input,select')));
+ if (def)
+ trrow.style['display'] = def['trunked'] ? '' : 'none';
+ } else if (which == 'rx') {
+ var advrow = document.getElementById('rx_2');
+ elements = elements.concat(Array.from(advrow.querySelectorAll('input,select')));
+ }
+ var result = read_write(elements, def);
+ if (which == 'ch') {
+ var tgtable = trrow.querySelector('table.tgtable');
+ var tgrow = trrow.querySelector('tr.tgrow');
+ if (def) {
+ for (var k in def['tgids']) {
+ var val = def['tgids'][k];
+ var newrow = amend_d(tgrow, tgtable, 'new');
+ var inputs = newrow.querySelectorAll('input');
+ read_write(inputs, {
+ 'tg_id': k,
+ 'tg_tag': val
+ });
+ }
+ } else {
+ var tgids = {};
+ var rows = tgtable.querySelectorAll('tr.tgrow');
+ for (var i = 0; i < rows.length; i++) {
+ if (rows[i].id == null || rows[i].id.substring(0, 3) != 'tg_')
+ continue;
+ var inputs = rows[i].querySelectorAll('input');
+ var vals = read_write(inputs, null);
+ tgids[vals['tg_id']] = vals['tg_tag'];
+ }
+ result['tgids'] = tgids;
+ }
+ }
+ if (!def)
+ return result;
+}
+
+function rollup(which, def) {
+ var result = [];
+ var mytbl = document.getElementById(which + 'table');
+ var elements = mytbl.querySelectorAll('.dynrow');
+ for (var e in elements) {
+ var row = elements[e];
+ if (row.id != null && row.id.substring(0, 3) == 'id_')
+ result.push(rollup_row(which, row, def));
+ }
+ if (!def)
+ return result;
+}
+
+function rollup_rx_rows(def) {
+ return rollup_row('rx', document.getElementById('rx_1'), def);
+}
+
+function f_save() {
+ var name = document.getElementById('config_name');
+ if (!name.value) {
+ alert('Name is required');
+ name.focus();
+ return;
+ }
+ if (name.value == 'New Configuration') {
+ alert("'" + name.value + "' is a reserved name, please retry");
+ name.value = '';
+ name.focus();
+ return;
+ }
+ var cfg = {
+ 'devices': rollup('dev', null),
+ 'channels': rollup('ch', null),
+ 'backend-rx': rollup_rx_rows(null)
+ };
+ cfg = edit_l(cfg, false);
+ var request = {
+ 'name': name.value,
+ 'value': cfg
+ };
+ send_command('config-save', request);
+ f_list();
+}
+
+function f_list() {
+ var inp = document.getElementById('include_tsv');
+ send_command('config-list', inp.checked ? 'tsv' : '');
+}
+
+function f_start() {
+ var sel = document.getElementById('config_select');
+ if (!sel)
+ return;
+ var val = read_write_sel(sel, null);
+ if (!val || val == 'New Configuration') {
+ alert('You must select a valid configuration to start');
+ return;
+ }
+ if (val.indexOf('[TSV]') >= 0) {
+ alert('TSV files not supported. First, invoke "Edit"; inspect the resulting configuration; then click "Save".');
+ return;
+ }
+ send_command('rx-start', val);
+}
+
+
+function f_stop() {
+ send_command('rx-stop', '');
+}
+
+function f_load() {
+ var sel = document.getElementById('config_select');
+ if (!sel)
+ return;
+ var val = read_write_sel(sel, null);
+ if (!val) {
+ alert('You must select a configuration to edit');
+ return;
+ }
+ if (val == 'New Configuration') {
+ open_editor();
+ } else {
+ send_command('config-load', val);
+ var ele = document.getElementById('config_name');
+ ele.value = val;
+ }
+}
+
+function show_advanced(o) {
+ var tbl = find_parent(o, 'TABLE');
+ var row = tbl.querySelector('.advrow');
+ toggle_show_hide(o, row);
+}
+
+function toggle_show_hide(o, ele) {
+ if (o.value == 'Show') {
+ o.value = 'Hide';
+ ele.style['display'] = '';
+ } else {
+ o.value = 'Show';
+ ele.style['display'] = 'none';
+ }
+}
+
+function f_tags(o) {
+ var mydiv = find_parent(o, 'DIV');
+ var tbl = mydiv.querySelector('.tgtable');
+ toggle_show_hide(o, tbl);
+}
+
+// communicate w/ HTTP server functions
+
+function http_req_cb() {
+ req_cb_count += 1;
+ s = http_req.readyState;
+ if (s != 4) {
+ nfinal_count += 1;
+ return;
+ }
+ if (http_req.status != 200) {
+ n200_count += 1;
+ return;
+ }
+ r200_count += 1;
+ dispatch_commands(http_req.responseText);
+}
+
+function send_command(command, data) {
+ var d = {
+ 'command': command,
+ 'data': data
+ };
+ send(d);
+}
+
+function send(d) {
+ request_count += 1;
+ if (send_queue.length >= SEND_QLIMIT) {
+ send_qfull += 1;
+ send_queue.unshift();
+ }
+ send_queue.push(d);
+ send_process();
+}
+
+function send_process() {
+ s = http_req.readyState;
+ if (s != 0 && s != 4) {
+ send_busy += 1;
+ return;
+ }
+ http_req.open('POST', '/');
+ http_req.onreadystatechange = http_req_cb;
+ http_req.setRequestHeader('Content-type', 'application/json');
+ cmd = JSON.stringify(send_queue);
+ send_queue = [];
+ http_req.send(cmd);
+}
+
+
+function save_tsv(command, data, file) {
+ var d = {
+ 'command': command,
+ 'data': data,
+ 'file': file
+ };
+ send(d);
+}
+ // command, data
+
+function reload_tsv(data) { // commands OP25 to reload the tsv talkgroup/source tag data
+ console.log('sending reload command...');
+ var command = "reload_tags";
+ var d = {
+ 'command': command,
+ 'data': data
+ };
+ send(d);
+} \ No newline at end of file
diff --git a/op25/gr-op25_repeater/www/www-static/editor.js b/op25/gr-op25_repeater/www/www-static/editor.js
new file mode 100644
index 0000000..f41725e
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/editor.js
@@ -0,0 +1,1247 @@
+// Copyright 2017, 2018, 2019, 2020 Max H. Parke KA1RBI
+// Copyright 2020, 2021 Michael Rose
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+// Last Update: 04-Jun-2021
+
+
+var delay = 250;
+
+const params = new URLSearchParams(window.location.search); // load query string from url
+
+ window.file = params.get('file');
+ window.mode = params.get('mode');
+ window.nac = params.get('nac');
+ window.sys = params.get('sys');
+ var css = params.get('css') ? params.get('css') : 'dark';
+
+// file - the tsv filename to work with (only matters for tg, src, sa - hard coded in the python for color)
+// id - the talkgroup or source ID to jump to upon load
+// css - [ light | dark ] - the display mode
+// mode - [ tg | src | color ] what is being worked on
+
+ window.imp = false;
+ var unsaved = false;
+
+var error1 = "ID and Tag fields are required. \n\n Error 1";
+var error2 = "Talkgroup and Priority / Color fields must be an integer. \n\n Error 2";
+var error3 = "Priority / Color field must be an integer. \n\n Error 3";
+var error4 = "ID already exists and must be unique. \n\n Error 4";
+var error5 = "Import file not specified. \n\n Error 5";
+var error6 = "Editor table not present. \n\n Error 6";
+var error7 = 'not supported. Expecting CSV or TSV. \n\n Error 7';
+var error8 = 'Failed to load file: ';
+var error9 = '';
+var error10 = 'All fields are required. \n\n Error 10';
+var error11 = 'Duplicate rffs/site entries not permitted. \n\n Error 11';
+var error12 = 'Invalid system ID. Input out of range. \n\n Error 12';
+var error13 = 'Duplicate System ID. \n\nError 13';
+
+$(window).on('load', function() {
+ document.documentElement.setAttribute('data-theme', css);
+ var tgid = params.get('id');
+ if (tgid)
+ var x = setTimeout(function(){ scrollToAnchor(tgid) }, 300);
+ var oc = "this.blur(); command_reload_tsv(" + nac + ");";
+ $('#btnReload').attr("onclick", oc);
+ $('#searchInput').val(null);
+ $('#csv-upload').hide();
+ $('#loading').hide();
+ $('#csvfile').val(null).on('change',readSingleFile);
+ generateCSS();
+ beginJsonSettings();
+ accColorSel();
+ uiColorRefresh();
+
+ switch(mode) {
+ case 'tg':
+ window.modeTitle = "Talkgroup";
+ $('#btnLoad').text('Load Talkgroups');
+ document.querySelectorAll('button.saveButton').forEach(elem => {
+ elem.innerHTML = "Save Talkgroups";
+ });
+ $('#title').text('Talkgroup TSV Editor - OP25');
+ break;
+
+ case 'src':
+ window.modeTitle = "Source";
+ $('#btnLoad').text('Load Source IDs');
+ document.querySelectorAll('button.saveButton').forEach(elem => {
+ elem.innerHTML = "Save Source IDs";
+ });
+ $('#title').text('Source IDs TSV Editor - OP25');
+ break;
+
+ case 'alias':
+ window.modeTitle = "Alias";
+ $('#btnLoad').text('Load Aliases');
+ document.querySelectorAll('button.saveButton').forEach(elem => {
+ elem.innerHTML = "Save Aliases";
+ });
+ $('#title').text('System Site Alias Editor - OP25');
+ break;
+
+ case 'color':
+ window.modeTitle = "Color";
+ $('#btnLoad').text('Load Colors');
+ document.querySelectorAll('button.saveButton').forEach(elem => {
+ elem.innerHTML = "Save Colors";
+ });
+ $('#title').text('Colors Editor - OP25');
+ $('#btnColorEditor').hide();
+ $('.importExport').hide(); // hide these buttons -- import/export function not written yet
+ break;
+ } // end switch
+
+});
+
+$(document).ready(function() {
+ // nothing here right now
+});
+
+window.onbeforeunload = function(){
+ if (unsaved == true)
+ return 'Are you sure you want to leave? Unsaved changes will be lost.';
+};
+
+// delete button
+$('input[class="delbutton"]').click(function(e){
+ $(this).closest('tr').remove();
+})
+
+function tsv_onload() {
+ switch(mode) {
+ case "alias":
+ beginAlias();
+ break;
+ case "color":
+ beginColor();
+ break;
+ default:
+ begin();
+ }
+}
+
+function begin() {
+// console.log('begin() started...');
+ $( "#loading" ).show();
+ if (begin.caller.name != "completeSave")
+ $('#talkgroups').hide(250);
+ $("#message").text("Fetching TSV...");
+ file = window.file;
+ $.ajax({
+ url : file,
+ type : 'GET',
+ success : buildTable,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('File Acces Error: \n\nFile:' + file + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+function beginAlias() {
+// console.log('beginAlias() started...');
+ $( "#loading" ).show();
+ if (beginAlias.caller.name != "completeSave")
+ $('#talkgroups').hide(250);
+ $("#message").text("Fetching Info...");
+ file = window.file;
+ $.ajax({
+ url : file,
+ type : 'GET',
+ success : buildAliasTable,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('File Acces Error: \n\nFile:' + file + '\n\n' + errorThrown + '\n\n'); buildAliasTable();}
+ });
+}
+
+function beginColor() {
+ console.log('beginColor started...');
+ $('#searchInput').hide();
+ $("#main").html('Loading...');
+ $(".saveButton").attr("onclick", "this.blur(); saveColorTable();");
+ $("#btnLoad").attr("onclick", "this.blur(); beginColor();");
+ $( "#loading" ).show();
+ generateCSS();
+ colorFile = 'color-map.json';
+ $.ajax({
+ url : colorFile,
+ type : 'GET',
+ success : buildColorTable,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('File Acces Error: \n\nFile:' + colorFile + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+
+function buildTable(d) {
+// console.log('build table started... ~207');
+ if (!d) {
+ location.reload();
+ }
+
+ $("#message").text("Building table...");
+
+ var x = "";
+ lines = [];
+
+ data = d.split(/\r?\n/); // split by newline
+
+ for(var i = 0; i < data.length; i++){
+ lines.push(data[i].split(/['\t']+/)); // split by tab \t
+ }
+
+ i = 0;
+ // TODO split priority and color into 2 fields?
+ aLen = lines.length;
+
+ var html = '<div id="editor">';
+ html += '<table class="editor" id="tsv-editor">';
+ html += '<th>New ' + window.modeTitle + ' ID</th>';
+ html += '<th>New ' + window.modeTitle + ' Tag</th>';
+ html += '<th class="pricol">Priority / Color</th>';
+ html += '<th>Actions</th>';
+
+ html += '<tr><td><input type="text" id="newtg"></td>';
+ html += ' <td><input type="text" id="newtag"></td>';
+ html += ' <td><input type="text" id="newcol"></td>';
+ html += ' <td align="center"><button id="btnAddNew" onclick="this.blur; addNew();"> Add New </button></td></tr>';
+ html += '</table><br>';
+
+ html += '<span class="label">Editing TSV: </span><span class="value">' + file + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span id="records">&nbsp;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span class="label">NAC: </span><span class="value">' + (nac) + ' - 0x' + (hex(parseInt(nac)).toUpperCase()) + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span class="value" id="unsaved" style="display: none;">Unsaved Changes</span>';
+ html += '<br><br>';
+
+ html += '<table class="editor" id="talkgroups">';
+ html += '<th>Row</th>';
+ html += '<th>' + window.modeTitle + ' ID</th>';
+ html += '<th>' + window.modeTitle + ' Tag</th>';
+ html += '<th class="pricol" >Priority / Color</th>';
+ html += '<th>Actions</th>';
+
+ for (var i = 0; i < aLen - 1; i++) {
+
+ x = i;
+ var id = lines[i][0];
+ var tag = lines[i][1];
+ var col = lines[i][2]; // ? lines[i][2] : 0;
+
+ var eleid_id = 'ID' + i + id + parseInt(Math.random() * 10000000); // unique IDs for each td, not used for anything right now.
+ var eleid_tag = 'ID' + i + id + parseInt(Math.random() * 10000000);
+ var eleid_col = 'ID' + i + col + parseInt(Math.random() * 10000000);
+
+ html += '<tr>';
+ html += '<td id="">' + (i + 1) + '<a href="#" name="'+ id + '"></a></td>';
+
+ html += '<td id="' + (eleid_id) + '" style="width: 150px;"><input type="text" id="' + x + '" value="' + id + '" class="tg tedit"></td>';
+ html += '<td id="' + (eleid_tag) + '"><input type="text" id="tag' + x + '" value="' + tag + '" class="tag tedit"></td>';
+ html += '<td id="' + (eleid_col) + '" style="width: 150px;"><input maxlength="4" type="text" id="col' + x + '" value="' + col + '" class="col tedit"></td>';
+
+ html += '<td align="center">';
+ html += '<button title="Delete" class="delbutton" onclick="this.blur; deleteRow(\'' + id + '\', \'' + tag +'\');">&#x2718;</button></td>';
+
+ html += '</tr>';
+ }
+
+ html += '</table></div><br><br><br><br>';
+
+ var s = document.getElementById("main"); // todo - use jQ attri() method to assign custom attributes.
+ s.innerHTML = html;
+ s.content = 'editor';
+
+ $('#main').data('content', 'editor');
+
+ $("#main").html(html);
+ $('#talkgroups').show(150);
+
+ $('#records').html('<span class="label">Records: </span><span class="value">' + (getHigh() + 1) + ' </span>');
+
+ $('#message').text('Ready');
+
+ if (mode == 'src') $('.pricol').text('Color');
+
+ document.querySelectorAll(".tedit").forEach(item => {
+ item.addEventListener('change', event => {
+ isUnsaved();
+ });
+ });
+
+ // enter key behavior (clicks Add New button)
+ $('#newtg').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ }
+ });
+
+ $('#newtag').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ }
+ });
+
+ $('#newcol').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ $('#newtg').focus();
+ }
+ });
+
+ $( "#loading" ).hide();
+ if (window.imp == true) //only flag as unsaved if buildTable was used after import
+ isUnsaved();
+}
+
+function deleteRow(id, tag) {
+ var r = confirm(id + ' - ' + tag + '\n\nConfirm delete.');
+ if (r == true) {
+ var td = event.target.parentNode;
+ var tr = td.parentNode; // the row to be removed
+ tr.parentNode.removeChild(tr);
+ isUnsaved();
+ }
+}
+
+function saveTable() {
+// console.log('saveTable()');
+ if (!document.getElementById("talkgroups")) {
+ jAlert(error6, 'Error');
+ return 0;
+ }
+
+ $( "#loading" ).show();
+ window.location.href = "#top";
+ // $('#talkgroups').hide(250);
+ $('#message').text('Saving...');
+ disableSave(); // disable save buttons momentarily
+
+ var tgs, tag, col;
+ data = [];
+
+ table = document.getElementById("talkgroups");
+ rows = table.rows.length;
+
+ var els = document.getElementsByClassName("tg"); // only the ID field is "tg"
+
+ for(var i = 0; i < els.length; i++) {
+
+ x = els[i].id;
+
+ tgs = document.getElementById(x).value;
+ tag = document.getElementById("tag" + (x)).value;
+ col = document.getElementById("col" + (x)).value;
+
+ if (tgs == "" || tag == "") {
+ jAlert(error1 + '\n\nEmpty fields on Row ' + (i + 1) + '\n\n', 'Error');
+ enableSave();
+ return;
+ }
+
+ if (!Number.isInteger(Number(tgs)) && mode=='tg') {
+ jAlert(error2 + ' \n\n' + tgs + ' looks like a ' + (typeof tgs) + ' on Row ' + (i + 1) + '.', 'Error');
+ enableSave();
+ return;
+ }
+
+ if (!Number.isInteger(Number(col))) {
+ jAlert(error3 + ' \n\n' + col + ' looks like a ' + (typeof col) + ' on Row ' + (i + 1) + '.', 'Error');
+ enableSave();
+ return;
+ }
+
+ data[i] = new Array(tgs, tag, col);
+
+ }
+
+ if (mode == "tg") {
+ data.sort(function(a, b) {
+ return a[0] - b[0];
+ });
+ }
+
+ // have to sort Source IDs differently because there could be wildcards/strings in there.
+ if (mode == "src") {
+ data.sort(function( a , b){
+ if(a[0] > b[0]) return 1;
+ if(a[0] < b[0]) return -1;
+ return 0;
+ });
+
+ data.sort(function(a, b){
+ return a[0].length - b[0].length;
+ });
+ }
+
+ //json output - not currently used here
+ var jsonOutput = JSON.stringify(data, undefined, 2);
+
+ var textOutput = "";
+ for(var i = 0; i < data.length; i++) {
+ textOutput += (data[i][0] + '\t' + data[i][1] + '\t' + data[i][2] + '\n');
+ }
+
+ save_tsv('config-tsvsave', textOutput, window.file); // send data to server
+
+ setTimeout(completeSave, delay); // artificial delays to allow http_server.py time to process things
+ setTimeout(function(){ command_reload_tsv(nac); }, delay); // tell OP25 to reload the TSVs
+ setTimeout(enableSave, delay);
+ $('#talkgroups').show(delay);
+ $( "#loading" ).hide();
+ isSaved();
+
+}
+
+function addNew() {
+ var id = getHigh() + 1;
+ var table = document.getElementById("talkgroups");
+ var x;
+
+ var newtg = $('#newtg').val(); // we're re-using the same AddNew code in Alias editor as well, hence the variable names.
+ var newtag = $('#newtag').val();
+ var newcol = $('#newcol').val();
+
+ var alias = newtg;
+ var r = newtag;
+ var s = newcol;
+
+ if (mode=="tg" || mode == "src") {
+ if (newtg == "" || newtag == "" ) { // || newcol == "") {
+ jAlert(error1, 'Error');
+ return;
+ }
+
+ if (!Number.isInteger(Number(newtg)) && mode=='tg') {
+ jAlert(error2 + ' \n\n<b>' + newtg + '</b> looks like a ' + (typeof newtg) + '.', 'Error');
+ return;
+ }
+
+ if (!Number.isInteger(Number(newcol))) {
+ jAlert(error3 + ' \n\n<b>' + newcol + '</b> looks like a ' + (typeof newtg) + '.', 'Error');
+ return;
+ }
+
+ var els = document.getElementsByClassName("tg");
+ for(var i = 0; i < els.length; i++) {
+ x = parseInt(els[i].value);
+ if (newtg == x) {
+ jAlert(error4, 'Error');
+ return;
+ }
+ }
+ }
+
+ if (mode=="alias") {
+ if (alias == "" || r == "" || s == "") {
+ jAlert(error10, 'Error');
+ return;
+ }
+ }
+
+ var row = table.insertRow(1);
+ var cell0 = row.insertCell(0);
+ var cell1 = row.insertCell(1);
+ var cell2 = row.insertCell(2);
+ var cell3 = row.insertCell(3);
+ var cell4 = row.insertCell(4);
+
+ if (mode == "tg" || mode == "src") {
+
+ cell0.innerHTML = '<span class="newtg">New</span>';
+ cell1.innerHTML = '<td><span class="newtg"><input type="text" id="' + id + '" value="' + newtg + '" class="tg"></td>';
+ cell2.innerHTML = '<td><span class="newtg"><td><input type="text" id="tag' + id + '" value="' + newtag + '"></td>';
+ cell3.innerHTML = '<td style="width: 100px;"><span class="newtg"><input type="text" id="col' + id + '" value="' + newcol + '"></td>';
+ cell4.innerHTML = '<td align="center"><button class="saveButton" id="btnSave3" onclick="this.blur; saveTable();"> Save </button>&nbsp;&nbsp;';
+ cell4.style = "text-align:center";
+ cell4.innerHTML += '<button title="Delete" class="delbutton" onclick="this.blur; deleteRow();">&#x2718;</button></td>';
+ }
+
+ if (mode == "alias") {
+
+ cell0.innerHTML = '<span class="newtg">New</span>';
+ cell1.innerHTML = '<td><span class="newtg"><input type="text" id="' + id + '" value="' + alias + '" class="tg"></td>';
+ cell2.innerHTML = '<td><span class="newtg"><td><input type="text" id="rfss' + id + '" value="' + r + '"></td>';
+ cell3.innerHTML = '<td style="width: 100px;"><span class="newtg"><input type="text" id="site' + id + '" value="' + s + '"></td>';
+ cell4.innerHTML = '';
+ cell4.style = "text-align:center";
+ cell4.innerHTML += '<button title="Delete" class="delbutton" onclick="this.blur; deleteRow();">&#x2718;</button></td>';
+ }
+
+
+ $('#newtg').val('');
+ $('#newtag').val('');
+ $('#newcol').val('');
+
+ isUnsaved();
+}
+
+function getHigh() {
+ var x = [];
+ var els = document.getElementsByClassName("tg");
+ for(var i = 0; i < els.length; i++) {
+ x[i] = (parseInt(els[i].id));
+ }
+ x = Math.max(...x);
+// console.log(x);
+ if (x == -Infinity) x = -1;
+ return x;
+}
+
+function scrollToAnchor(a){
+ var f;
+ var els = document.getElementsByClassName("tg");
+ for(var i = 0; i < els.length; i++) {
+ if (a == (parseInt(els[i].value))) {
+ var x = document.getElementById(i);
+ x.focus();
+ x.scrollIntoView({
+ behavior : 'smooth',
+ block : 'center',
+ inline : 'center'
+ });
+ return;
+ }
+ }
+
+ jAlert (modeTitle + ' ' + a + ' not found. There may be wildcard matches. \n\n Creating new. ', 'Add New');
+ $('#newtg').val(a);
+ $('#newtg').focus();
+}
+
+function tsv_csv() { // export to CSV file
+ var filetag = 'op25_tsv_' + mode;
+ var csv = "";
+ var separator = ",";
+ var rows = [];
+ var tgs = $('.tg');
+ var tag = $('.tag');
+ var col = $('.col');
+
+ for(var i = 0; i < tgs.length; i++) {
+ rows.push ( [ tgs[i].value, tag[i].value, col[i].value ] );
+ }
+
+ var filename = 'export_' + filetag + '_' + new Date().toLocaleDateString() + '.csv';
+ $("#unsaved").show();
+ exportToCsv(filename, rows); // in main.js
+
+}
+
+function clearMessage() {
+ $('#message').text('');
+}
+
+function refresh() {
+ location.reload();
+}
+
+function up() {
+ window.location.href = '#top';
+}
+
+function completeSave() {
+ switch(mode) {
+ case "alias":
+ beginAlias();
+ break;
+ case "color":
+ beginColor();
+ break;
+ default:
+// console.log('executing default...');
+ begin();
+ }
+}
+
+function disableSave() {
+ $('.saveButton').prop('disabled', true);
+// document.querySelectorAll('button.saveButton').forEach(elem => {
+// elem.disabled = true;
+// });
+}
+
+function enableSave(){
+ $('.saveButton').prop('disabled', false);
+// document.querySelectorAll('button.saveButton').forEach(elem => {
+// elem.disabled = false;
+// });
+}
+
+function help(){
+ $.ajax({
+ url : 'tsv-help.html',
+ type : 'GET',
+ success : dispHelp
+ });
+}
+
+function dispHelp(h) {
+ var s = document.getElementById("main");
+// if (s.content == 'help')
+// return;
+
+ if ($('#main').data('content') == 'help')
+ return;
+
+// window.editorTable = s.innerHTML;
+// s.innerHTML = h;
+ window.editorTable = $('#main').html();
+ $('#main').html(h);
+ s.content = 'help';
+ $('#main').data('content', 'help');
+}
+
+function closeHelp() {
+ var s = document.getElementById("main");
+ s.innerHTML = window.editorTable;
+ s.content = 'editor';
+ $('#main').data('content', 'editor');
+}
+
+function isNum(x) {
+ if (!x) return;
+ y = Number.isInteger(x);
+ return y;
+}
+
+function command_reload_tsv(nac) {
+ $('#message').text('Sending command...');
+ reload_tsv(parseInt(nac));
+ $('#message').text('Command Sent');
+}
+
+function dispImport() {
+ $('#csv-upload').show();
+}
+
+function hideImport() {
+ $('#csv-upload').hide();
+}
+
+function isUnsaved() {
+ unsaved = true;
+ $( "#unsaved" ).show();
+}
+
+function isSaved() {
+ $( "#unsaved" ).hide();
+ unsaved = false;
+}
+
+function readSingleFile(evt) {
+ if (!evt.target.files) {
+ alert(error5);
+ return;
+ }
+
+ var f = evt.target.files[0];
+ if (f) {
+ isUnsaved();
+ var ftype = (evt.target.value).substr((evt.target.value).length - 3).toUpperCase();
+
+ switch (ftype) {
+ case 'CSV':
+ var sep = ",";
+ break;
+ case 'TSV':
+ var sep = "\t";
+ break;
+ default:
+ jAlert('File type ' + ftype + ' ' + error7, 'Error');
+ return;
+ }
+
+ var r = new FileReader();
+ if (!r) return;
+ r.onload = function(e) {
+ var contents = e.target.result;
+// document.write("File Uploaded! <br />" + "name: " + f.name + "<br />" + "content: " + 'contents hidden' + "<br />" + "type: " + f.type + "<br />" + "size: " + f.size + " bytes <hr />");
+ var lines = contents.split("\n"), output = [];
+ for (var i=0; i<lines.length; i++){
+ if (lines[i].length > 0)
+ output.push(lines[i].split(sep).join("\t") + "\n");
+ }
+ output = "" + output.join("") + "";
+ isUnsaved();
+ window.imp = true;
+ buildTable(output);
+ }
+ r.readAsText(f);
+ isUnsaved();
+ } else {
+ jAlert(error8 + evt.target.value, 'Error');
+ }
+}
+
+function buildAliasTable(d) { // geting JSON with this one
+
+ if (!d) {
+ location.reload();
+ }
+ var lines = [];
+ var i = 0;
+ var sysid = window.sys;
+ var alias;
+ var systems = [];
+ window.aliasData = d;
+
+ for (r in d) {
+ systems.push(r);
+ }
+
+ for (r in d[sysid]) {
+ for (s in d[sys][r]) {
+ alias = d[sys][r][s]['alias'];
+// console.log (sysid + ' / ' + hex(parseInt(sysid)).toUpperCase() + ' - ' + alias + ' - R=' + r + ' - S=' + s);
+ lines.push([alias, r, s]);
+ }
+ }
+
+ $("#message").text("Building table...");
+ aLen = lines.length;
+
+ var html = '<div id="editor">';
+ html += '<table class="editor" id="tsv-editor">';
+ html += '<th>New ' + window.modeTitle + '</th>';
+ html += '<th>RFSS ID (dec)</th>';
+ html += '<th>Site ID (dec)</th>';
+ html += '<th>Actions</th>';
+
+ html += '<tr><td><input type="text" id="newtg"></td>';
+ html += ' <td><input type="text" id="newtag"></td>';
+ html += ' <td><input type="text" id="newcol"></td>';
+ html += ' <td align="center"><button id="btnAddNew" onclick="this.blur; addNew();"> Add New </button></td></tr>';
+ html += '</table><br>';
+
+ html += '<span class="label">Editing: </span><span class="value">' + file + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span id="records">&nbsp;</span>&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span class="label">System: </span><span class="value">' + (sysid) + ' - 0x' + (hex(parseInt(sysid)).toUpperCase()) + '</span>&nbsp;&nbsp;&nbsp;&nbsp;';
+ html += '<span class="label">Change: </span>';
+ html += '<span><select name="selSystem" id="selSystem" style="width: 100px;"></select></span>';
+ html += '<span class="value" id="unsaved" style="display: none;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Unsaved</span>';
+ html += '<br><br>';
+
+ html += '<table class="editor" id="talkgroups">';
+
+ html += '<th width="">Row</th>';
+ html += '<th width="300">' + window.modeTitle + '</th>';
+ html += '<th width="">RFSS ID<br>(dec)</th>';
+ html += '<th width="">Site ID<br>(dec)</th>';
+ html += '<th wifth="120">Actions</th>';
+
+ if (aLen == 0) {
+ jAlert('No Site Aliases found for System ' + sysid + '. Try creating some.', 'Create New');
+ }
+
+ for (var i = 0; i < aLen; i++) {
+
+ x = i;
+ var alias = lines[i][0];
+ var rfss = lines[i][1];
+ var site = lines[i][2];
+
+ var eleid_alias = 'ID' + i + site + parseInt(Math.random() * 10000000); // unique IDs for each td, not used for anything right now.
+ var eleid_rfss = 'ID' + i + site + parseInt(Math.random() * 10000000);
+ var eleid_site = 'ID' + i + site + parseInt(Math.random() * 10000000);
+
+ html += '<tr>';
+ html += '<td id="">' + (i + 1) + '<a href="#" name="'+ alias + '"></a></td>';
+
+ html += '<td id="' + (eleid_alias) + '" style="width: 150px;"><input type="text" id="' + x + '" value="' + alias + '" class="tg tedit"></td>';
+ html += '<td id="' + (eleid_rfss) + '"><input type="text" id="rfss' + x + '" value="' + rfss + '" class="rfss tedit"></td>';
+ html += '<td id="' + (eleid_site) + '" style="width: 150px;"><input maxlength="4" type="text" id="site' + x + '" value="' + site + '" class="site tedit"></td>';
+
+ html += '<td align="center">';
+ html += '<button title="Delete" class="delbutton" onclick="this.blur; deleteRow(\'' + alias + '\', \'' + site +'\');">&#x2718;</button></td>';
+
+ html += '</tr>';
+ }
+
+ html += '</table></div><br><br><br><br>';
+
+ var s = document.getElementById("main"); // todo - use jQ attri() method to assign custom attributes.
+ s.innerHTML = html;
+ s.content = 'editor';
+
+ $('#main').data('content', 'editor');
+
+ $("#main").html(html);
+ $('#talkgroups').show(150);
+
+ $('#records').html('<span class="label">Records: </span><span class="value">' + (getHigh() + 1) + ' </span>');
+
+ $('#message').text('Ready');
+
+ if (mode == 'src') $('.pricol').text('Color');
+
+ document.querySelectorAll(".tedit").forEach(item => {
+ item.addEventListener('change', event => {
+ isUnsaved();
+ });
+ });
+
+ $( "#loading" ).hide();
+ if (window.imp == true) //only flag as unsaved if buildTable was used after import
+ isUnsaved();
+
+ // enter key behavior (clicks Add New button)
+ $('#newtg').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ }
+ });
+
+ $('#newtag').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ }
+ });
+
+ $('#newcol').on('keypress', function(e) {
+ if(e.which == 13) {
+ $('#btnAddNew').trigger('click');
+ $('#newtg').focus();
+ }
+ });
+
+ populateChange(systems);
+
+}
+
+function populateChange(sys) {
+ var s, h;
+ $('#selSystem').append('<option value="' + 0 + '">' + 'Select...' + '</option>');
+ for (i in sys) {
+ s = sys[i];
+ h = hex(parseInt(s));
+ $('#selSystem').append('<option value="' + s + '">' + s + ' - 0x' + h.toUpperCase() + '</option>');
+ }
+ $('#selSystem').append('<option value="' + 'new' + '">' + 'Add New...' + '</option>');
+ $('#selSystem').on('change', function() {
+ changeSys(sys);
+ });
+}
+
+function changeSys(sys) {
+
+ if (sys == 0)
+ return;
+
+ var sel = $('#selSystem').val();
+
+ var sysd = 0;
+
+ if (sel == 'new') {
+ var p = prompt('Enter new System ID in hex.\n\n');
+
+ if (!p) { // Cancel btn
+ $('#selSystem').val(0);
+ return;
+ }
+
+ if (!(p.match("^[0-9a-fA-F]+$") !== null)) { // valid hex?
+ jAlert(error12, 'Invalid Entry');
+ $('#selSystem').val(0);
+ return;
+ }
+
+ sysd = dec(p);
+
+ if (sysd < 1 || sysd > 4095) {
+ jAlert(error12, 'Invalid Entry');
+ $('#selSystem').val(0);
+ return;
+ }
+
+ if (sys.includes( sysd.toString())) {
+ jAlert(error13, 'Invalid Entry');
+ $('#selSystem').val(0);
+ return;
+ }
+
+ $('#selSystem').val(0);
+
+ sel = sysd;
+
+ } // end if new
+
+ var url = 'alias-edit.html?file=site-alias.json&mode=alias&sys=' + sel;
+ window.sys = sel;
+ beginAlias();
+}
+
+function deleteSys() {
+ system = window.sys;
+
+ if (Object.keys(aliasData).length == 1) {
+// console.log('cannot delete last system');
+ return;
+ }
+
+ var r = confirm("Confirm: Delete site aliases for System " + system + ' - 0x' + hex(parseInt(sys)).toUpperCase() + '\n\nWARNING: This action cannot be reversed.\n\n');
+ if (r == true) {
+ delete window.aliasData[system.toString()];
+ $('#selSystem option[value="' + system + '"]').remove();
+ var jsonOutput = JSON.stringify(aliasData, undefined, 2);
+ $( "#loading" ).show();
+ save_tsv('config-tsvsave', jsonOutput, window.file); // send data to server
+ $('#selSystem :nth-child(1)').prop('selected', true); // select first option (below Select...)
+ var newSys = $('#selSystem option').eq(1).val();
+ window.sys = newSys;
+ $('#loading').hide();
+ beginAlias();
+ } else {
+ // cancel
+ return;
+ }
+}
+
+function saveAliasTable() {
+ if (!document.getElementById("talkgroups")) {
+ jAlert(error6, 'Error');
+ return 0;
+ }
+
+ d = window.aliasData;
+ var sysid = window.sys;
+
+ $( "#loading" ).show();
+ window.location.href = "#top";
+ // $('#talkgroups').hide(250);
+ $('#message').text('Saving...');
+
+ disableSave(); // disable save buttons momentarily
+
+ var tgs, tag, col;
+ data = [];
+ out = [];
+ rs = [];
+
+ table = document.getElementById("talkgroups");
+ rows = table.rows.length;
+
+ // check for dupe rfss/site combos
+ var els = document.getElementsByClassName("tg");
+ for(var y = 0; y < els.length; y++) {
+ rfss = document.getElementById("rfss" + (y)).value;
+ site = document.getElementById("site" + (y)).value;
+ rs.push([rfss, site]);
+ }
+ var arr = rs.map(JSON.stringify);
+ rl = arr.length;
+ var sar = new Set(arr);
+ sl = sar.size;
+ if (rl != sl ) {
+ jAlert(error11, 'Error');
+ $('#message').text('Ready');
+ $( "#loading" ).hide();
+ enableSave();
+ return;
+ }
+
+ for(var i = 0; i < els.length; i++) {
+
+ x = els[i].id;
+
+ alias = document.getElementById(x).value;
+ rfss = document.getElementById("rfss" + (x)).value;
+ site = document.getElementById("site" + (x)).value;
+
+ if (alias == "" || rfss == "" || site == "") {
+ jAlert(error10 + '\n\nEmpty fields on Row ' + (i + 1) + '\n\n', 'Error');
+ enableSave();
+ return;
+ }
+
+ data[i] = new Array(alias, rfss, site);
+
+ }
+
+ data.sort(function(a, b) {
+ return a[2] - b[2];
+ });
+
+ // these get added to site-alias.json when no data is present initially - just delete them.
+ delete d['readyState'];
+ delete d['responseText'];
+ delete d['status'];
+ delete d['statusText'];
+
+ delete d[sys];
+
+ for(var i = 0; i < data.length; i++) {
+ alias = data[i][0];
+ r = data[i][1];
+ s = data[i][2];
+ d[sys] = d[sys] || {};
+ d[sys][r] = d[sys][r] || {};
+ d[sys][r][s] = d[sys][r][s] || {};
+ d[sys][r][s]['alias'] = alias;
+ }
+
+ //json output
+ var jsonOutput = JSON.stringify(d, undefined, 2);
+ save_tsv('config-tsvsave', jsonOutput, window.file); // send data to server
+
+ setTimeout(completeSave, delay); // artificial delays to allow http_server.py time to process things
+ setTimeout(enableSave, delay);
+ $('#talkgroups').show(delay);
+ $('#loading').hide();
+ localStorage.AliasTableUpdated == true;
+ isSaved();
+
+}
+
+function buildColorTable(d) {
+
+// console.log('build color table started...');
+
+ var html = '<span class="value" id="unsaved" style="display: none;">Unsaved Changes</span>';
+ html += '<br><br>';
+
+ html += '<div id="editor">';
+ html += '<table class="editor" id="tsv-editor">';
+
+ html += '<th>Color</th>';
+ html += '<th>Font Color</th>';
+ html += '<th>Background</th>';
+ html += '<th title="thank Max for this...">Blink</th>';
+ html += '<th>Sample Text</th>';
+
+ for (i in d) {
+ if (!d[i])
+ continue;
+ if (d[i][0] > 99)
+ continue;
+
+ var x = i;
+
+ var color = d[i][1];
+ var backg = d[i][2];
+ var blink = d[i][3];
+
+ var blinkOpt = (d[i][3] == true) ? "Yes" : "No";
+
+ html += '<tr>';
+
+ html += '<td style="text-align: center;" id=""><b>' + (parseInt(x)) + '</b></td>';
+
+ html += '<td style="width: 150px; text-align: center;"><input title="' + x + '" type="text" id="' + (x + 'color') + '" value="' + color + '" class="tg tedit coloredit"></td>';
+
+ html += '<td style="width: 150px; text-align: center;"><input title="' + x + '" type="text" id="' + (x + 'backg') + '" value="' + backg + '" class="tg tedit bgedit"></td>';
+
+ html += '<td style="width: 150px; text-align: center;">';
+ html += '<input type="checkbox" title="' + x + '" id="' + (x + 'blink') + '" class="tg tedit blinkedit">';
+ html += '<label for="' + (x + 'blink') + '"><span></span></label>';
+ html +='</td>';
+
+ html += '<td style="text-align: center;"><span id="s' + x + '" class="c' + parseInt(x) + '">Sample Text 12345 </span>';
+
+ html += '</tr>';
+
+ }
+
+ html += '</table></div><br><br><br><br>';
+ generateCSS();
+ var s = document.getElementById("main"); // todo - use jQ attri() method to assign custom attributes.
+ s.innerHTML = html;
+ s.content = 'editor';
+
+ $('#main').data('content', 'editor');
+
+ $("#main").html(html);
+ $('#talkgroups').show(150);
+
+ for (i in d) {
+ if (!d[i])
+ continue;
+ if (d[i][0] > 99)
+ continue;
+ $('#' + (i) + 'blink').prop('checked', d[i][3]);
+ }
+
+ // color picker: Spectrum - https://github.com/bgrins/spectrum
+ // Copyright (c) Brian Grinstead
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining
+ // a copy of this software and associated documentation files (the
+ // "Software"), to deal in the Software without restriction, including
+ // without limitation the rights to use, copy, modify, merge, publish,
+ // distribute, sublicense, and/or sell copies of the Software, and to
+ // permit persons to whom the Software is furnished to do so, subject to
+ // the following conditions...
+ // ** see complete license in source css & js
+
+ $(".coloredit").spectrum({
+ preferredFormat: "hex",
+ localStorageKey: "spectrum.homepage",
+ chooseText: "Select",
+ clickoutFiresChange: false,
+ containerClassName: 'colorPicker',
+ replacerClassName: 'colorReplacer',
+ showInput: true,
+ showPalette: true,
+ showInitial: true,
+ allowEmpty: false,
+ palette: [
+ ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
+ ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
+ ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
+ ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
+ ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
+ ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
+ ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
+ ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
+ ]
+ });
+
+ $(".bgedit").spectrum({
+ preferredFormat: "hex",
+ localStorageKey: "spectrum.homepage",
+ clickoutFiresChange: false,
+ containerClassName: 'colorPicker',
+ replacerClassName: 'colorReplacer',
+ chooseText: "Select",
+ showInput: true,
+ showPalette: true,
+ showInitial: true,
+ allowEmpty: true,
+ palette: [
+ ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
+ ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
+ ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
+ ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
+ ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
+ ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
+ ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
+ ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
+ ]
+ });
+
+ $('.coloredit').on('change', function(){
+ var v = this.value ? this.value : "initial";
+ var target = '#s' + (this.title);
+ $(target).css('color', v);
+ isUnsaved();
+ });
+
+ $('.bgedit').on('change', function(){
+ var v = this.value ? this.value : "initial";
+ var target = '#s' + (this.title);
+ $(target).css('background-color', v);
+ isUnsaved();
+ });
+
+ $('.blinkedit').on('change', function(){
+ var target = '#s' + (this.title);
+ var z = this.checked == true ? "blinker 1s linear infinite" : "none";
+ $(target).css('animation', z);
+ isUnsaved();
+ });
+
+ $('#loading').hide();
+ $('#message').text('Ready');
+}
+
+function saveColorTable() {
+
+ $( "#loading" ).show();
+ window.location.href = "#top";
+ $('#message').text('Saving...');
+
+ var i = null;
+ var c = null;
+ var b = null;
+ var blink = null;
+ var css = [];
+ css[0] = new Array (500,"placeholder","do-not-use",false); // hack shack :( avoids a NULL at [0] in the resulting json
+ for (i = 1; i < 100; i++){
+ c = $('#' + (i) + 'color').val();
+ b = $('#' + (i) + 'backg').val();
+ blink = $('#' + (i) + 'blink').is(':checked') ? true : false;
+ css[i] = new Array(i, c, b, blink);
+ }
+
+ var jsonOutput = JSON.stringify(css, undefined, 2);
+
+ save_tsv('config-tsvsave', jsonOutput, 'color-map.json');
+ $('#message').text('Colors saved. Ready.');
+ setTimeout(function() { $( "#loading" ).hide(); }, 250); // a little delay for the UI's benefit.
+ localStorage.ColorsTableUpdated == true;
+ isSaved();
+}
+
+function generateCSS() {
+// console.log('generateCSS started...');
+ if (localStorage.ColorsTableUpdated == false)
+ return;
+ colorFile = 'color-map.json';
+ $.ajax({
+ url : colorFile,
+ type : 'GET',
+ success : applyCSS,
+// error : function(XMLHttpRequest, textStatus, errorThrown) { alert('File Acces Error: \n\nFile:' + colorFile + '\n\n' + errorThrown + '\n\n'); }
+ });
+
+}
+
+function applyCSS(d) {
+ var sheet = (function() {
+ var sheets = document.styleSheets,
+ stylesheet = sheets[(sheets.length - 1)];
+
+ for(var i in document.styleSheets ){
+ if( sheets[i].title == 'tgcolors') {
+ for (var y=0; y<sheets[i].cssRules.length; y++) {
+ sheets[i].deleteRule (y);
+ }
+ return sheets[i]; // re-use the same inline style sheet
+ }
+ }
+ var style = document.createElement("style");
+ style.title = 'tgcolors';
+ // WebKit hack :(
+ style.appendChild(document.createTextNode(""));
+ // Add the <style> element to the page
+ document.head.appendChild(style);
+ localStorage.ColorsTableUpdated == false;
+ return style.sheet;
+
+ })();
+
+ for (i in d) {
+ if (d[i]) {
+ w = ' .c' + d[i][0] + ' { ';
+ x = 'color: ' + d[i][1] + '; ';
+ y = 'background-color: ' + d[i][2] + '; ';
+ z = 'animation: ' + (d[i][3] == true ? "blinker 1s linear infinite;" : "none;") + '} \n';
+ sheet.insertRule( (w + x + y + z) );
+ }
+ }
+
+ setTimeout(enableSave, delay);
+ $('#talkgroups').show(delay);
+ $( "#loading" ).hide();
+}
+
+function reloadCss() { // not used right now
+ var links = document.getElementsByTagName("link");
+ for (var cl in links)
+ {
+ var link = links[cl];
+ if (link.rel === "stylesheet")
+ link.href += "";
+ }
+}
diff --git a/op25/gr-op25_repeater/www/www-static/help.html b/op25/gr-op25_repeater/www/www-static/help.html
new file mode 100644
index 0000000..d6b2b15
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/help.html
@@ -0,0 +1,125 @@
+
+<h2 class='nac'>Keyboard Shortcuts</h2>
+
+<p>These keyboard shortcuts are used throughout the UI on any tab and allow available information to be displayed in a variety of ways.</p>
+G - Go To<br>
+L - Lockout<br>
+H - Hold<br>
+S - Skip/Scan<br>
+V - View (light/dark toggle)<br>
+R - RX Screen<br>
+J - Home Screen<br>
+M - Minify<br>
+P - Show / Hide Plots<br>
+A - Show / Hide Adjacent Sites<br>
+B - Set display text BOLD<br>
+N - Set display text NORMAL<br>
+1 - Show / Hide Call History<br>
+2 - Show / Hide Events<br>
+3 - Show / Hide Logs Block<br>
+4 - Show / Hide Channel ID Band Plan<br>
+0 - Show / Hide Main Display<br><br>
+
+<div align="center"><h2 class='nac'>Home Tab</h2></div>
+The Home tab contains:
+
+<h3>Main Display</h3>
+<p>
+<b>List of systems included in the trunk.tsv file.</b> Each of these may be enabled or disabled. The last time a
+TSBK was received and total TSBKs received since OP25 was started is also displayed. Under the Alias column
+there can be as many as 3 links shown, TA, SRC, SA, for Talkgroup Alias, Source ID Alias, and Site Alias,
+respectively. See the Editors section below.
+</p>
+<p><b>Plots</b> - Plots are displayed if defined in the config files.</p>
+<p>Blocks from the RX Tab may be added to this display using the keyboard shortcuts.</p>
+
+
+<div align="center"><h2 class='nac'>Config Tab</h2></div>
+
+<p><span class="value">UI Display Mode Toggle:</span> Set the theme to light or dark. Default is dark.</p>
+<p><span class="value">System Font Size: </span> The front size of the System Name in the Main Display.</p>
+<p><span class="value">Talkgroup Font Size: </span> The font size of the Talkgroup Name in the Main Display.</p>
+<p><span class="value">Main Display Font Style (Normal / Bold): </span> System and Talkgroup Name normal or bold selection in the Main Display.</p>
+<p><span class="value">Animation Speed:</span> UI animation of transitions between tabs. Set to 0 to turn off.</p>
+<p><span class="value">Color Code for Unknown Talkgroups:</span> Talkgroups which do not appear in the talkgroup tag id list will be assigned this color code.</p>
+<p><span class="value">Max Display String Length:</span> Talkgroup names will be truncated beyond this number of characters.</p>
+<p><span class="value">Show Adjacent Sites on RX Tab:</span> Adjacent Sites will be shown on the RX tab.</p>
+<p><span class="value">Show Trailing Zeros on Frequencies:</span> Zeros will be appended so all frequencies appear with 5 characters after the decimal.</p>
+<p><span class="value">Use TG Colors on Main Display - System / Talkgroup:</span> When selected, the color code for the talkgroup will be applied to the system and/or talkgroup elements in the Main Display.</p>
+<p><span class="value">Show Band Plan on RX Screen: </span> The band plan advertised by the control channel will be displayed on the RX tab for each active system.</p>
+<p><span class="value">Exclude Encrypted Calls from Call History: </span> Encrypted calls will be excluded from the Call History log.</p>
+<p><span class="value">Show Timeslots in Call History Log: </span> When selected TDMA timeslots will be shown in the Call History Log, “Svc” column. See RX Tab, below.</p>
+<p><span class="value">Use SmartColors: </span> SmartColors searches the Talkgroup Tag string for each item in the list and applies the color on a match. Colors defined in the Talkgroup tag config file take priority over SmartColors. Entries in these fields are case-insensitive.</p>
+<p><span class="value">UI Colors:</span> colors of the UI elements may be changed as follows:</p>
+
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tag Colors Editor - Access the Tag Colors Editor</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accent 1 and 2 - the “fade” effect behind the Main Display</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Values - Values presented in the Main Display, System Information Table, and elsewhere</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System / Talkgroup - The color of the System Name text and Talkgroup Tag text when “Use TG in Main Display” options are unchecked.</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Buttons - Button text color (all)</p>
+
+<p><span class="value">Log Events in Browser:</span> Selected events will be logged in the browser. These options do not affect server-side logging. The available options are:</p>
+
+<p><span class="value">Control Channel Events (CC)</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Joins - subscriber joins the talkgroup</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Login / Logout - subscriber logs into or out of the system</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Calls - a voice chanel grant</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Denials - a voice channel request was denied</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Change Frequency (CF) - these events are used to update the Main Display</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Trunk Update (TU) - these events are used to update Active Frequencies table and system information displays</p>
+<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RX Update (RX) - these events update the plot images, fine tune, and error data (if present, rx.py only)</p>
+<p>Some Control Channel Event opcodes are received and displayed by the UI but cannot be logged (e.g. Adjacent Sites or Identifier Update). The last three of these are mostly useful for debugging and troubleshooting and typically should remain off.</p>
+
+<p><span class="value">Number of Rows in Log Tables</span> - The maximum number of rows allowed for each of the Call History, Events, and Error Tracking (if enabled) tables. Default is 2,500. This setting does not apply to the server-side OP25 SQL logging -- only the browser logs.</p>
+<p><span class="value">Save and Load Display Settings</span> - Changes made on the Config tab should be saved by clicking Save Display Settings. These saved settings will be applied next time OP25 Web UI is started. Load Display Settings will reload the settings on the server, overwriting the current contents of the Config tab. Changes made with keyboard shortcuts will not persist beyond the session.</p>
+
+
+<h2 class='nac'>RX Tab</h2>
+
+<p><span class="value">Main Display</span>Display showing active system, talkgroup, frequency, source ID, encryption status.</p>
+<p><span class="value">Site Information</span> - Each active system</p>
+<p><span class="value">Active Frequency Table</span> - Double click elements in these tables to access the editors.</p>
+<p><span class="value">Call History</span> - Logs channel grants as seen on the control channel. Click the Call History Magnifying Glass to pop open a searchable table. FIlter by any column. Export the table as CSV by clicking the CSV icon. The “Svc” column displays timeslot, encrypted status, and the priority when that information is pertinent. Example: “S1 Ø 4” = Slot 1, Encrypted, Pri 4. “XP” in this column means patched talkgroup, or crosspatch.</p>
+Events - Logs Control Channel events, and application events as selected in the Config tab. Click the Events Magnifying Glass to pop open a searchable table. FIlter by any column. Export the table as CSV by clicking the CSV icon.</p>
+Error Tracking (if enabled in command line option -X): Logs the error tracking data when enabled in the command line used to start OP25. The same filter and export options are available.</p>
+Click the triangles to the right of each table to expand, retract and hide that table.</p>
+
+<div align="center"><h2 class='nac'>View tab</h2></div>
+<p>Toggle Dark / Light Display</p>
+
+
+<div align="center"><h2 class='nac'>Popout</h2></div>
+<p>Pops open the app in a new window with minimal browser UI.</p>
+
+
+<div align="center"><h2 class='nac'>About</h2></div>
+<p>Well, information about the app is here.</p>
+
+<div align="center"><h2 class='nac'>Talkgroup Editor, Source ID Editor, Site Alias Editor <br> and Colors Editor</h2></div>
+
+<h3>Talkgroup and Source ID Editors</h3>
+
+<p>These editors allow changes and additions to the talkgroup tags tsv file and the source ID tags tsv files. These files are specified in the trunk.tsv configuration file in the “TGID Tags File” field. Both files are supplied in the same field, separated by a comma. For example: “talkgroups.tsv,sources.tsv”</p>
+<p>To access the Talkgroup Editor or Source ID Editor, double click on the talkgroup ID, talkgroup tag, source ID, or source ID tag in the Active Frequency Table or the Call History Table. Alternatively, click the TG or SRC link on the Home tab for the desired active system.</p>
+<p>The talkgroup and source ID editors have an import and export as CSV or TSV function. The import function accepts a 3 column comma-separated values or tab separated values file:</p>
+<p>ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TAG&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PRI/COLOR</p>
+<p>Any columns beyond the third are ignored.</p>
+<p>ID is a decimal value.</p>
+<p>TAG is an alphanumeric tag.</p>
+<p>PRI/COLOR is:</p>
+<p>For Talkgroups IDs: a 3 digit decimal value 0 through 999 where the first digit represents the priority and the last two represent the color code (see Colors Editor, below).</p>
+<p>For Source IDs: a 2 digit decimal value 0-99 matching the color map (see Color Editor).</p>
+<p>The Export function may be used to bring the file out to a text or spreadsheet editor, save, and import back into OP25.</p>
+<p>Use the Filter box to search/filter the data.</p>
+<p>To create a new entry, complete the required 3 fields and click Add New. The new entry will appear in the table. Click Save to commit or the Red X to Delete.</p>
+<p>To Delete an entry, click the red X to the right. Confirm the delete. Click Save to commit.</p>
+<p>Click on Help in the editors for information on using wildcard matching.</p>
+
+<h3>Site Alias Editor</h3>
+<p>The Site Alias editor allows a friendly name to be supplied for each site in a system. This is currently used in the System Information table on the RX Tab and in the Adjacent Sites table. The Site Alias editor is accessed by clicking on the SA link on the Home tab. The Site Alias editor allows editing of the site names for the active system, or any other system in the file. New lists can be created by clicking Change > Add New…</p>
+
+
+<h3>Color Editor</h3>
+<p>Talkgroups Tags and Source IDs can be assigned a color value 0-99 in the Talkgorup Editor and Source ID Editor. The Colors Editor allows you to change/modify those 100 colors. The Colors Editor is accessed on the Config tab, Tag Colors Editor. The “blink” function can be squarely blamed on Max.</p>
+---
+<p>Changes made in the editors take a few seconds to apply in the UI. Click Save when finished or the changes will be abandoned. Click Load to reload the saved values and overwrite all edits in the table. Additional information for the editors is available by clicking Help in the editor.</p> \ No newline at end of file
diff --git a/op25/gr-op25_repeater/www/www-static/hls.js b/op25/gr-op25_repeater/www/www-static/hls.js
new file mode 100644
index 0000000..41a465e
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/hls.js
@@ -0,0 +1,21550 @@
+typeof window !== "undefined" &&
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["Hls"] = factory();
+ else
+ root["Hls"] = factory();
+})(this, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "/dist/";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
+/******/ })
+/************************************************************************/
+/******/ ({
+
+/***/ "./node_modules/eventemitter3/index.js":
+/*!*********************************************!*\
+ !*** ./node_modules/eventemitter3/index.js ***!
+ \*********************************************/
+/*! no static exports found */
+/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var has = Object.prototype.hasOwnProperty
+ , prefix = '~';
+
+/**
+ * Constructor to create a storage for our `EE` objects.
+ * An `Events` instance is a plain object whose properties are event names.
+ *
+ * @constructor
+ * @private
+ */
+function Events() {}
+
+//
+// We try to not inherit from `Object.prototype`. In some engines creating an
+// instance in this way is faster than calling `Object.create(null)` directly.
+// If `Object.create(null)` is not supported we prefix the event names with a
+// character to make sure that the built-in object properties are not
+// overridden or used as an attack vector.
+//
+if (Object.create) {
+ Events.prototype = Object.create(null);
+
+ //
+ // This hack is needed because the `__proto__` property is still inherited in
+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
+ //
+ if (!new Events().__proto__) prefix = false;
+}
+
+/**
+ * Representation of a single event listener.
+ *
+ * @param {Function} fn The listener function.
+ * @param {*} context The context to invoke the listener with.
+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
+ * @constructor
+ * @private
+ */
+function EE(fn, context, once) {
+ this.fn = fn;
+ this.context = context;
+ this.once = once || false;
+}
+
+/**
+ * Add a listener for a given event.
+ *
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
+ * @param {(String|Symbol)} event The event name.
+ * @param {Function} fn The listener function.
+ * @param {*} context The context to invoke the listener with.
+ * @param {Boolean} once Specify if the listener is a one-time listener.
+ * @returns {EventEmitter}
+ * @private
+ */
+function addListener(emitter, event, fn, context, once) {
+ if (typeof fn !== 'function') {
+ throw new TypeError('The listener must be a function');
+ }
+
+ var listener = new EE(fn, context || emitter, once)
+ , evt = prefix ? prefix + event : event;
+
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
+ else emitter._events[evt] = [emitter._events[evt], listener];
+
+ return emitter;
+}
+
+/**
+ * Clear event by name.
+ *
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
+ * @param {(String|Symbol)} evt The Event name.
+ * @private
+ */
+function clearEvent(emitter, evt) {
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
+ else delete emitter._events[evt];
+}
+
+/**
+ * Minimal `EventEmitter` interface that is molded against the Node.js
+ * `EventEmitter` interface.
+ *
+ * @constructor
+ * @public
+ */
+function EventEmitter() {
+ this._events = new Events();
+ this._eventsCount = 0;
+}
+
+/**
+ * Return an array listing the events for which the emitter has registered
+ * listeners.
+ *
+ * @returns {Array}
+ * @public
+ */
+EventEmitter.prototype.eventNames = function eventNames() {
+ var names = []
+ , events
+ , name;
+
+ if (this._eventsCount === 0) return names;
+
+ for (name in (events = this._events)) {
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
+ }
+
+ if (Object.getOwnPropertySymbols) {
+ return names.concat(Object.getOwnPropertySymbols(events));
+ }
+
+ return names;
+};
+
+/**
+ * Return the listeners registered for a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @returns {Array} The registered listeners.
+ * @public
+ */
+EventEmitter.prototype.listeners = function listeners(event) {
+ var evt = prefix ? prefix + event : event
+ , handlers = this._events[evt];
+
+ if (!handlers) return [];
+ if (handlers.fn) return [handlers.fn];
+
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
+ ee[i] = handlers[i].fn;
+ }
+
+ return ee;
+};
+
+/**
+ * Return the number of listeners listening to a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @returns {Number} The number of listeners.
+ * @public
+ */
+EventEmitter.prototype.listenerCount = function listenerCount(event) {
+ var evt = prefix ? prefix + event : event
+ , listeners = this._events[evt];
+
+ if (!listeners) return 0;
+ if (listeners.fn) return 1;
+ return listeners.length;
+};
+
+/**
+ * Calls each of the listeners registered for a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @returns {Boolean} `true` if the event had listeners, else `false`.
+ * @public
+ */
+EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
+ var evt = prefix ? prefix + event : event;
+
+ if (!this._events[evt]) return false;
+
+ var listeners = this._events[evt]
+ , len = arguments.length
+ , args
+ , i;
+
+ if (listeners.fn) {
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
+
+ switch (len) {
+ case 1: return listeners.fn.call(listeners.context), true;
+ case 2: return listeners.fn.call(listeners.context, a1), true;
+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;
+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
+ }
+
+ for (i = 1, args = new Array(len -1); i < len; i++) {
+ args[i - 1] = arguments[i];
+ }
+
+ listeners.fn.apply(listeners.context, args);
+ } else {
+ var length = listeners.length
+ , j;
+
+ for (i = 0; i < length; i++) {
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
+
+ switch (len) {
+ case 1: listeners[i].fn.call(listeners[i].context); break;
+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;
+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
+ case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
+ default:
+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
+ args[j - 1] = arguments[j];
+ }
+
+ listeners[i].fn.apply(listeners[i].context, args);
+ }
+ }
+ }
+
+ return true;
+};
+
+/**
+ * Add a listener for a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @param {Function} fn The listener function.
+ * @param {*} [context=this] The context to invoke the listener with.
+ * @returns {EventEmitter} `this`.
+ * @public
+ */
+EventEmitter.prototype.on = function on(event, fn, context) {
+ return addListener(this, event, fn, context, false);
+};
+
+/**
+ * Add a one-time listener for a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @param {Function} fn The listener function.
+ * @param {*} [context=this] The context to invoke the listener with.
+ * @returns {EventEmitter} `this`.
+ * @public
+ */
+EventEmitter.prototype.once = function once(event, fn, context) {
+ return addListener(this, event, fn, context, true);
+};
+
+/**
+ * Remove the listeners of a given event.
+ *
+ * @param {(String|Symbol)} event The event name.
+ * @param {Function} fn Only remove the listeners that match this function.
+ * @param {*} context Only remove the listeners that have this context.
+ * @param {Boolean} once Only remove one-time listeners.
+ * @returns {EventEmitter} `this`.
+ * @public
+ */
+EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
+ var evt = prefix ? prefix + event : event;
+
+ if (!this._events[evt]) return this;
+ if (!fn) {
+ clearEvent(this, evt);
+ return this;
+ }
+
+ var listeners = this._events[evt];
+
+ if (listeners.fn) {
+ if (
+ listeners.fn === fn &&
+ (!once || listeners.once) &&
+ (!context || listeners.context === context)
+ ) {
+ clearEvent(this, evt);
+ }
+ } else {
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
+ if (
+ listeners[i].fn !== fn ||
+ (once && !listeners[i].once) ||
+ (context && listeners[i].context !== context)
+ ) {
+ events.push(listeners[i]);
+ }
+ }
+
+ //
+ // Reset the array, or remove it completely if we have no more listeners.
+ //
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
+ else clearEvent(this, evt);
+ }
+
+ return this;
+};
+
+/**
+ * Remove all listeners, or those of the specified event.
+ *
+ * @param {(String|Symbol)} [event] The event name.
+ * @returns {EventEmitter} `this`.
+ * @public
+ */
+EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
+ var evt;
+
+ if (event) {
+ evt = prefix ? prefix + event : event;
+ if (this._events[evt]) clearEvent(this, evt);
+ } else {
+ this._events = new Events();
+ this._eventsCount = 0;
+ }
+
+ return this;
+};
+
+//
+// Alias methods names because people roll like that.
+//
+EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
+EventEmitter.prototype.addListener = EventEmitter.prototype.on;
+
+//
+// Expose the prefix.
+//
+EventEmitter.prefixed = prefix;
+
+//
+// Allow `EventEmitter` to be imported as module namespace.
+//
+EventEmitter.EventEmitter = EventEmitter;
+
+//
+// Expose the module.
+//
+if (true) {
+ module.exports = EventEmitter;
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
+/*!*****************************************************!*\
+ !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
+ \*****************************************************/
+/*! no static exports found */
+/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
+/***/ (function(module, exports, __webpack_require__) {
+
+// see https://tools.ietf.org/html/rfc1808
+
+(function (root) {
+ var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
+ var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
+ var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
+ var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
+
+ var URLToolkit = {
+ // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
+ // E.g
+ // With opts.alwaysNormalize = false (default, spec compliant)
+ // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
+ // With opts.alwaysNormalize = true (not spec compliant)
+ // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
+ buildAbsoluteURL: function (baseURL, relativeURL, opts) {
+ opts = opts || {};
+ // remove any remaining space and CRLF
+ baseURL = baseURL.trim();
+ relativeURL = relativeURL.trim();
+ if (!relativeURL) {
+ // 2a) If the embedded URL is entirely empty, it inherits the
+ // entire base URL (i.e., is set equal to the base URL)
+ // and we are done.
+ if (!opts.alwaysNormalize) {
+ return baseURL;
+ }
+ var basePartsForNormalise = URLToolkit.parseURL(baseURL);
+ if (!basePartsForNormalise) {
+ throw new Error('Error trying to parse base URL.');
+ }
+ basePartsForNormalise.path = URLToolkit.normalizePath(
+ basePartsForNormalise.path
+ );
+ return URLToolkit.buildURLFromParts(basePartsForNormalise);
+ }
+ var relativeParts = URLToolkit.parseURL(relativeURL);
+ if (!relativeParts) {
+ throw new Error('Error trying to parse relative URL.');
+ }
+ if (relativeParts.scheme) {
+ // 2b) If the embedded URL starts with a scheme name, it is
+ // interpreted as an absolute URL and we are done.
+ if (!opts.alwaysNormalize) {
+ return relativeURL;
+ }
+ relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
+ return URLToolkit.buildURLFromParts(relativeParts);
+ }
+ var baseParts = URLToolkit.parseURL(baseURL);
+ if (!baseParts) {
+ throw new Error('Error trying to parse base URL.');
+ }
+ if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
+ // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
+ // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
+ var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
+ baseParts.netLoc = pathParts[1];
+ baseParts.path = pathParts[2];
+ }
+ if (baseParts.netLoc && !baseParts.path) {
+ baseParts.path = '/';
+ }
+ var builtParts = {
+ // 2c) Otherwise, the embedded URL inherits the scheme of
+ // the base URL.
+ scheme: baseParts.scheme,
+ netLoc: relativeParts.netLoc,
+ path: null,
+ params: relativeParts.params,
+ query: relativeParts.query,
+ fragment: relativeParts.fragment,
+ };
+ if (!relativeParts.netLoc) {
+ // 3) If the embedded URL's <net_loc> is non-empty, we skip to
+ // Step 7. Otherwise, the embedded URL inherits the <net_loc>
+ // (if any) of the base URL.
+ builtParts.netLoc = baseParts.netLoc;
+ // 4) If the embedded URL path is preceded by a slash "/", the
+ // path is not relative and we skip to Step 7.
+ if (relativeParts.path[0] !== '/') {
+ if (!relativeParts.path) {
+ // 5) If the embedded URL path is empty (and not preceded by a
+ // slash), then the embedded URL inherits the base URL path
+ builtParts.path = baseParts.path;
+ // 5a) if the embedded URL's <params> is non-empty, we skip to
+ // step 7; otherwise, it inherits the <params> of the base
+ // URL (if any) and
+ if (!relativeParts.params) {
+ builtParts.params = baseParts.params;
+ // 5b) if the embedded URL's <query> is non-empty, we skip to
+ // step 7; otherwise, it inherits the <query> of the base
+ // URL (if any) and we skip to step 7.
+ if (!relativeParts.query) {
+ builtParts.query = baseParts.query;
+ }
+ }
+ } else {
+ // 6) The last segment of the base URL's path (anything
+ // following the rightmost slash "/", or the entire path if no
+ // slash is present) is removed and the embedded URL's path is
+ // appended in its place.
+ var baseURLPath = baseParts.path;
+ var newPath =
+ baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
+ relativeParts.path;
+ builtParts.path = URLToolkit.normalizePath(newPath);
+ }
+ }
+ }
+ if (builtParts.path === null) {
+ builtParts.path = opts.alwaysNormalize
+ ? URLToolkit.normalizePath(relativeParts.path)
+ : relativeParts.path;
+ }
+ return URLToolkit.buildURLFromParts(builtParts);
+ },
+ parseURL: function (url) {
+ var parts = URL_REGEX.exec(url);
+ if (!parts) {
+ return null;
+ }
+ return {
+ scheme: parts[1] || '',
+ netLoc: parts[2] || '',
+ path: parts[3] || '',
+ params: parts[4] || '',
+ query: parts[5] || '',
+ fragment: parts[6] || '',
+ };
+ },
+ normalizePath: function (path) {
+ // The following operations are
+ // then applied, in order, to the new path:
+ // 6a) All occurrences of "./", where "." is a complete path
+ // segment, are removed.
+ // 6b) If the path ends with "." as a complete path segment,
+ // that "." is removed.
+ path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
+ // 6c) All occurrences of "<segment>/../", where <segment> is a
+ // complete path segment not equal to "..", are removed.
+ // Removal of these path segments is performed iteratively,
+ // removing the leftmost matching pattern on each iteration,
+ // until no matching pattern remains.
+ // 6d) If the path ends with "<segment>/..", where <segment> is a
+ // complete path segment not equal to "..", that
+ // "<segment>/.." is removed.
+ while (
+ path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
+ ) {}
+ return path.split('').reverse().join('');
+ },
+ buildURLFromParts: function (parts) {
+ return (
+ parts.scheme +
+ parts.netLoc +
+ parts.path +
+ parts.params +
+ parts.query +
+ parts.fragment
+ );
+ },
+ };
+
+ if (true)
+ module.exports = URLToolkit;
+ else {}
+})(this);
+
+
+/***/ }),
+
+/***/ "./node_modules/webworkify-webpack/index.js":
+/*!**************************************************!*\
+ !*** ./node_modules/webworkify-webpack/index.js ***!
+ \**************************************************/
+/*! no static exports found */
+/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
+/***/ (function(module, exports, __webpack_require__) {
+
+function webpackBootstrapFunc (modules) {
+/******/ // The module cache
+/******/ var installedModules = {};
+
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId])
+/******/ return installedModules[moduleId].exports;
+
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+
+/******/ // identity function for calling harmony imports with the correct context
+/******/ __webpack_require__.i = function(value) { return value; };
+
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, {
+/******/ configurable: false,
+/******/ enumerable: true,
+/******/ get: getter
+/******/ });
+/******/ }
+/******/ };
+
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "/";
+
+/******/ // on error function for async loading
+/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
+
+ var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
+ return f.default || f // try to call default if defined to also support babel esmodule exports
+}
+
+var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
+var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
+
+// http://stackoverflow.com/a/2593661/130442
+function quoteRegExp (str) {
+ return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
+}
+
+function isNumeric(n) {
+ return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
+}
+
+function getModuleDependencies (sources, module, queueName) {
+ var retval = {}
+ retval[queueName] = []
+
+ var fnString = module.toString()
+ var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
+ if (!wrapperSignature) return retval
+ var webpackRequireName = wrapperSignature[1]
+
+ // main bundle deps
+ var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
+ var match
+ while ((match = re.exec(fnString))) {
+ if (match[3] === 'dll-reference') continue
+ retval[queueName].push(match[3])
+ }
+
+ // dll deps
+ re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
+ while ((match = re.exec(fnString))) {
+ if (!sources[match[2]]) {
+ retval[queueName].push(match[1])
+ sources[match[2]] = __webpack_require__(match[1]).m
+ }
+ retval[match[2]] = retval[match[2]] || []
+ retval[match[2]].push(match[4])
+ }
+
+ // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
+ var keys = Object.keys(retval);
+ for (var i = 0; i < keys.length; i++) {
+ for (var j = 0; j < retval[keys[i]].length; j++) {
+ if (isNumeric(retval[keys[i]][j])) {
+ retval[keys[i]][j] = 1 * retval[keys[i]][j];
+ }
+ }
+ }
+
+ return retval
+}
+
+function hasValuesInQueues (queues) {
+ var keys = Object.keys(queues)
+ return keys.reduce(function (hasValues, key) {
+ return hasValues || queues[key].length > 0
+ }, false)
+}
+
+function getRequiredModules (sources, moduleId) {
+ var modulesQueue = {
+ main: [moduleId]
+ }
+ var requiredModules = {
+ main: []
+ }
+ var seenModules = {
+ main: {}
+ }
+
+ while (hasValuesInQueues(modulesQueue)) {
+ var queues = Object.keys(modulesQueue)
+ for (var i = 0; i < queues.length; i++) {
+ var queueName = queues[i]
+ var queue = modulesQueue[queueName]
+ var moduleToCheck = queue.pop()
+ seenModules[queueName] = seenModules[queueName] || {}
+ if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
+ seenModules[queueName][moduleToCheck] = true
+ requiredModules[queueName] = requiredModules[queueName] || []
+ requiredModules[queueName].push(moduleToCheck)
+ var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
+ var newModulesKeys = Object.keys(newModules)
+ for (var j = 0; j < newModulesKeys.length; j++) {
+ modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
+ modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
+ }
+ }
+ }
+
+ return requiredModules
+}
+
+module.exports = function (moduleId, options) {
+ options = options || {}
+ var sources = {
+ main: __webpack_require__.m
+ }
+
+ var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
+
+ var src = ''
+
+ Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
+ var entryModule = 0
+ while (requiredModules[module][entryModule]) {
+ entryModule++
+ }
+ requiredModules[module].push(entryModule)
+ sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
+ src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
+ })
+
+ src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
+
+ var blob = new window.Blob([src], { type: 'text/javascript' })
+ if (options.bare) { return blob }
+
+ var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
+
+ var workerUrl = URL.createObjectURL(blob)
+ var worker = new window.Worker(workerUrl)
+ worker.objectURL = workerUrl
+
+ return worker
+}
+
+
+/***/ }),
+
+/***/ "./src/crypt/decrypter.js":
+/*!********************************************!*\
+ !*** ./src/crypt/decrypter.js + 3 modules ***!
+ \********************************************/
+/*! exports provided: default */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// CONCATENATED MODULE: ./src/crypt/aes-crypto.js
+var AESCrypto = /*#__PURE__*/function () {
+ function AESCrypto(subtle, iv) {
+ this.subtle = subtle;
+ this.aesIV = iv;
+ }
+
+ var _proto = AESCrypto.prototype;
+
+ _proto.decrypt = function decrypt(data, key) {
+ return this.subtle.decrypt({
+ name: 'AES-CBC',
+ iv: this.aesIV
+ }, key, data);
+ };
+
+ return AESCrypto;
+}();
+
+
+// CONCATENATED MODULE: ./src/crypt/fast-aes-key.js
+var FastAESKey = /*#__PURE__*/function () {
+ function FastAESKey(subtle, key) {
+ this.subtle = subtle;
+ this.key = key;
+ }
+
+ var _proto = FastAESKey.prototype;
+
+ _proto.expandKey = function expandKey() {
+ return this.subtle.importKey('raw', this.key, {
+ name: 'AES-CBC'
+ }, false, ['encrypt', 'decrypt']);
+ };
+
+ return FastAESKey;
+}();
+
+/* harmony default export */ var fast_aes_key = (FastAESKey);
+// CONCATENATED MODULE: ./src/crypt/aes-decryptor.js
+// PKCS7
+function removePadding(buffer) {
+ var outputBytes = buffer.byteLength;
+ var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
+
+ if (paddingBytes) {
+ return buffer.slice(0, outputBytes - paddingBytes);
+ } else {
+ return buffer;
+ }
+}
+
+var AESDecryptor = /*#__PURE__*/function () {
+ function AESDecryptor() {
+ // Static after running initTable
+ this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
+ this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
+ this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
+ this.sBox = new Uint32Array(256);
+ this.invSBox = new Uint32Array(256); // Changes during runtime
+
+ this.key = new Uint32Array(0);
+ this.initTable();
+ } // Using view.getUint32() also swaps the byte order.
+
+
+ var _proto = AESDecryptor.prototype;
+
+ _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
+ var view = new DataView(arrayBuffer);
+ var newArray = new Uint32Array(4);
+
+ for (var i = 0; i < 4; i++) {
+ newArray[i] = view.getUint32(i * 4);
+ }
+
+ return newArray;
+ };
+
+ _proto.initTable = function initTable() {
+ var sBox = this.sBox;
+ var invSBox = this.invSBox;
+ var subMix = this.subMix;
+ var subMix0 = subMix[0];
+ var subMix1 = subMix[1];
+ var subMix2 = subMix[2];
+ var subMix3 = subMix[3];
+ var invSubMix = this.invSubMix;
+ var invSubMix0 = invSubMix[0];
+ var invSubMix1 = invSubMix[1];
+ var invSubMix2 = invSubMix[2];
+ var invSubMix3 = invSubMix[3];
+ var d = new Uint32Array(256);
+ var x = 0;
+ var xi = 0;
+ var i = 0;
+
+ for (i = 0; i < 256; i++) {
+ if (i < 128) {
+ d[i] = i << 1;
+ } else {
+ d[i] = i << 1 ^ 0x11b;
+ }
+ }
+
+ for (i = 0; i < 256; i++) {
+ var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
+ sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
+ sBox[x] = sx;
+ invSBox[sx] = x; // Compute multiplication
+
+ var x2 = d[x];
+ var x4 = d[x2];
+ var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
+
+ var t = d[sx] * 0x101 ^ sx * 0x1010100;
+ subMix0[x] = t << 24 | t >>> 8;
+ subMix1[x] = t << 16 | t >>> 16;
+ subMix2[x] = t << 8 | t >>> 24;
+ subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
+
+ t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
+ invSubMix0[sx] = t << 24 | t >>> 8;
+ invSubMix1[sx] = t << 16 | t >>> 16;
+ invSubMix2[sx] = t << 8 | t >>> 24;
+ invSubMix3[sx] = t; // Compute next counter
+
+ if (!x) {
+ x = xi = 1;
+ } else {
+ x = x2 ^ d[d[d[x8 ^ x2]]];
+ xi ^= d[d[xi]];
+ }
+ }
+ };
+
+ _proto.expandKey = function expandKey(keyBuffer) {
+ // convert keyBuffer to Uint32Array
+ var key = this.uint8ArrayToUint32Array_(keyBuffer);
+ var sameKey = true;
+ var offset = 0;
+
+ while (offset < key.length && sameKey) {
+ sameKey = key[offset] === this.key[offset];
+ offset++;
+ }
+
+ if (sameKey) {
+ return;
+ }
+
+ this.key = key;
+ var keySize = this.keySize = key.length;
+
+ if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
+ throw new Error('Invalid aes key size=' + keySize);
+ }
+
+ var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
+ var ksRow;
+ var invKsRow;
+ var keySchedule = this.keySchedule = new Uint32Array(ksRows);
+ var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
+ var sbox = this.sBox;
+ var rcon = this.rcon;
+ var invSubMix = this.invSubMix;
+ var invSubMix0 = invSubMix[0];
+ var invSubMix1 = invSubMix[1];
+ var invSubMix2 = invSubMix[2];
+ var invSubMix3 = invSubMix[3];
+ var prev;
+ var t;
+
+ for (ksRow = 0; ksRow < ksRows; ksRow++) {
+ if (ksRow < keySize) {
+ prev = keySchedule[ksRow] = key[ksRow];
+ continue;
+ }
+
+ t = prev;
+
+ if (ksRow % keySize === 0) {
+ // Rot word
+ t = t << 8 | t >>> 24; // Sub word
+
+ t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
+
+ t ^= rcon[ksRow / keySize | 0] << 24;
+ } else if (keySize > 6 && ksRow % keySize === 4) {
+ // Sub word
+ t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
+ }
+
+ keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
+ }
+
+ for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
+ ksRow = ksRows - invKsRow;
+
+ if (invKsRow & 3) {
+ t = keySchedule[ksRow];
+ } else {
+ t = keySchedule[ksRow - 4];
+ }
+
+ if (invKsRow < 4 || ksRow <= 4) {
+ invKeySchedule[invKsRow] = t;
+ } else {
+ invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
+ }
+
+ invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
+ }
+ } // Adding this as a method greatly improves performance.
+ ;
+
+ _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
+ return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
+ };
+
+ _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
+ var nRounds = this.keySize + 6;
+ var invKeySchedule = this.invKeySchedule;
+ var invSBOX = this.invSBox;
+ var invSubMix = this.invSubMix;
+ var invSubMix0 = invSubMix[0];
+ var invSubMix1 = invSubMix[1];
+ var invSubMix2 = invSubMix[2];
+ var invSubMix3 = invSubMix[3];
+ var initVector = this.uint8ArrayToUint32Array_(aesIV);
+ var initVector0 = initVector[0];
+ var initVector1 = initVector[1];
+ var initVector2 = initVector[2];
+ var initVector3 = initVector[3];
+ var inputInt32 = new Int32Array(inputArrayBuffer);
+ var outputInt32 = new Int32Array(inputInt32.length);
+ var t0, t1, t2, t3;
+ var s0, s1, s2, s3;
+ var inputWords0, inputWords1, inputWords2, inputWords3;
+ var ksRow, i;
+ var swapWord = this.networkToHostOrderSwap;
+
+ while (offset < inputInt32.length) {
+ inputWords0 = swapWord(inputInt32[offset]);
+ inputWords1 = swapWord(inputInt32[offset + 1]);
+ inputWords2 = swapWord(inputInt32[offset + 2]);
+ inputWords3 = swapWord(inputInt32[offset + 3]);
+ s0 = inputWords0 ^ invKeySchedule[0];
+ s1 = inputWords3 ^ invKeySchedule[1];
+ s2 = inputWords2 ^ invKeySchedule[2];
+ s3 = inputWords1 ^ invKeySchedule[3];
+ ksRow = 4; // Iterate through the rounds of decryption
+
+ for (i = 1; i < nRounds; i++) {
+ t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
+ t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
+ t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
+ t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
+
+ s0 = t0;
+ s1 = t1;
+ s2 = t2;
+ s3 = t3;
+ ksRow = ksRow + 4;
+ } // Shift rows, sub bytes, add round key
+
+
+ t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
+ t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
+ t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
+ t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
+ ksRow = ksRow + 3; // Write
+
+ outputInt32[offset] = swapWord(t0 ^ initVector0);
+ outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
+ outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
+ outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
+
+ initVector0 = inputWords0;
+ initVector1 = inputWords1;
+ initVector2 = inputWords2;
+ initVector3 = inputWords3;
+ offset = offset + 4;
+ }
+
+ return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
+ };
+
+ _proto.destroy = function destroy() {
+ this.key = undefined;
+ this.keySize = undefined;
+ this.ksRows = undefined;
+ this.sBox = undefined;
+ this.invSBox = undefined;
+ this.subMix = undefined;
+ this.invSubMix = undefined;
+ this.keySchedule = undefined;
+ this.invKeySchedule = undefined;
+ this.rcon = undefined;
+ };
+
+ return AESDecryptor;
+}();
+
+/* harmony default export */ var aes_decryptor = (AESDecryptor);
+// EXTERNAL MODULE: ./src/errors.ts
+var errors = __webpack_require__("./src/errors.ts");
+
+// EXTERNAL MODULE: ./src/utils/logger.js
+var logger = __webpack_require__("./src/utils/logger.js");
+
+// EXTERNAL MODULE: ./src/events.js
+var events = __webpack_require__("./src/events.js");
+
+// EXTERNAL MODULE: ./src/utils/get-self-scope.js
+var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
+
+// CONCATENATED MODULE: ./src/crypt/decrypter.js
+
+
+
+
+
+
+ // see https://stackoverflow.com/a/11237259/589493
+
+var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
+
+var decrypter_Decrypter = /*#__PURE__*/function () {
+ function Decrypter(observer, config, _temp) {
+ var _ref = _temp === void 0 ? {} : _temp,
+ _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
+ removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
+
+ this.logEnabled = true;
+ this.observer = observer;
+ this.config = config;
+ this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
+
+ if (removePKCS7Padding) {
+ try {
+ var browserCrypto = global.crypto;
+
+ if (browserCrypto) {
+ this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
+ }
+ } catch (e) {}
+ }
+
+ this.disableWebCrypto = !this.subtle;
+ }
+
+ var _proto = Decrypter.prototype;
+
+ _proto.isSync = function isSync() {
+ return this.disableWebCrypto && this.config.enableSoftwareAES;
+ };
+
+ _proto.decrypt = function decrypt(data, key, iv, callback) {
+ var _this = this;
+
+ if (this.disableWebCrypto && this.config.enableSoftwareAES) {
+ if (this.logEnabled) {
+ logger["logger"].log('JS AES decrypt');
+ this.logEnabled = false;
+ }
+
+ var decryptor = this.decryptor;
+
+ if (!decryptor) {
+ this.decryptor = decryptor = new aes_decryptor();
+ }
+
+ decryptor.expandKey(key);
+ callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
+ } else {
+ if (this.logEnabled) {
+ logger["logger"].log('WebCrypto AES decrypt');
+ this.logEnabled = false;
+ }
+
+ var subtle = this.subtle;
+
+ if (this.key !== key) {
+ this.key = key;
+ this.fastAesKey = new fast_aes_key(subtle, key);
+ }
+
+ this.fastAesKey.expandKey().then(function (aesKey) {
+ // decrypt using web crypto
+ var crypto = new AESCrypto(subtle, iv);
+ crypto.decrypt(data, aesKey).catch(function (err) {
+ _this.onWebCryptoError(err, data, key, iv, callback);
+ }).then(function (result) {
+ callback(result);
+ });
+ }).catch(function (err) {
+ _this.onWebCryptoError(err, data, key, iv, callback);
+ });
+ }
+ };
+
+ _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {
+ if (this.config.enableSoftwareAES) {
+ logger["logger"].log('WebCrypto Error, disable WebCrypto API');
+ this.disableWebCrypto = true;
+ this.logEnabled = true;
+ this.decrypt(data, key, iv, callback);
+ } else {
+ logger["logger"].error("decrypting error : " + err.message);
+ this.observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_DECRYPT_ERROR,
+ fatal: true,
+ reason: err.message
+ });
+ }
+ };
+
+ _proto.destroy = function destroy() {
+ var decryptor = this.decryptor;
+
+ if (decryptor) {
+ decryptor.destroy();
+ this.decryptor = undefined;
+ }
+ };
+
+ return Decrypter;
+}();
+
+/* harmony default export */ var decrypter = __webpack_exports__["default"] = (decrypter_Decrypter);
+
+/***/ }),
+
+/***/ "./src/demux/demuxer-inline.js":
+/*!**************************************************!*\
+ !*** ./src/demux/demuxer-inline.js + 12 modules ***!
+ \**************************************************/
+/*! exports provided: default */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/crypt/decrypter.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: ./src/events.js
+var events = __webpack_require__("./src/events.js");
+
+// EXTERNAL MODULE: ./src/errors.ts
+var errors = __webpack_require__("./src/errors.ts");
+
+// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
+var crypt_decrypter = __webpack_require__("./src/crypt/decrypter.js");
+
+// EXTERNAL MODULE: ./src/polyfills/number.js
+var number = __webpack_require__("./src/polyfills/number.js");
+
+// EXTERNAL MODULE: ./src/utils/logger.js
+var logger = __webpack_require__("./src/utils/logger.js");
+
+// EXTERNAL MODULE: ./src/utils/get-self-scope.js
+var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
+
+// CONCATENATED MODULE: ./src/demux/adts.js
+/**
+ * ADTS parser helper
+ * @link https://wiki.multimedia.cx/index.php?title=ADTS
+ */
+
+
+
+
+function getAudioConfig(observer, data, offset, audioCodec) {
+ var adtsObjectType,
+ // :int
+ adtsSampleingIndex,
+ // :int
+ adtsExtensionSampleingIndex,
+ // :int
+ adtsChanelConfig,
+ // :int
+ config,
+ userAgent = navigator.userAgent.toLowerCase(),
+ manifestCodec = audioCodec,
+ adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
+
+ adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
+ adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
+
+ if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
+ observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
+ fatal: true,
+ reason: "invalid ADTS sampling index:" + adtsSampleingIndex
+ });
+ return;
+ }
+
+ adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
+
+ adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
+ logger["logger"].log("manifest codec:" + audioCodec + ",ADTS data:type:" + adtsObjectType + ",sampleingIndex:" + adtsSampleingIndex + "[" + adtsSampleingRates[adtsSampleingIndex] + "Hz],channelConfig:" + adtsChanelConfig); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
+
+ if (/firefox/i.test(userAgent)) {
+ if (adtsSampleingIndex >= 6) {
+ adtsObjectType = 5;
+ config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
+ // there is a factor 2 between frame sample rate and output sample rate
+ // multiply frequency by 2 (see table below, equivalent to substract 3)
+
+ adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
+ } else {
+ adtsObjectType = 2;
+ config = new Array(2);
+ adtsExtensionSampleingIndex = adtsSampleingIndex;
+ } // Android : always use AAC
+
+ } else if (userAgent.indexOf('android') !== -1) {
+ adtsObjectType = 2;
+ config = new Array(2);
+ adtsExtensionSampleingIndex = adtsSampleingIndex;
+ } else {
+ /* for other browsers (Chrome/Vivaldi/Opera ...)
+ always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
+ */
+ adtsObjectType = 5;
+ config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
+
+ if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
+ // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
+ // there is a factor 2 between frame sample rate and output sample rate
+ // multiply frequency by 2 (see table below, equivalent to substract 3)
+ adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
+ } else {
+ // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
+ // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
+ if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
+ adtsObjectType = 2;
+ config = new Array(2);
+ }
+
+ adtsExtensionSampleingIndex = adtsSampleingIndex;
+ }
+ }
+ /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
+ ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
+ Audio Profile / Audio Object Type
+ 0: Null
+ 1: AAC Main
+ 2: AAC LC (Low Complexity)
+ 3: AAC SSR (Scalable Sample Rate)
+ 4: AAC LTP (Long Term Prediction)
+ 5: SBR (Spectral Band Replication)
+ 6: AAC Scalable
+ sampling freq
+ 0: 96000 Hz
+ 1: 88200 Hz
+ 2: 64000 Hz
+ 3: 48000 Hz
+ 4: 44100 Hz
+ 5: 32000 Hz
+ 6: 24000 Hz
+ 7: 22050 Hz
+ 8: 16000 Hz
+ 9: 12000 Hz
+ 10: 11025 Hz
+ 11: 8000 Hz
+ 12: 7350 Hz
+ 13: Reserved
+ 14: Reserved
+ 15: frequency is written explictly
+ Channel Configurations
+ These are the channel configurations:
+ 0: Defined in AOT Specifc Config
+ 1: 1 channel: front-center
+ 2: 2 channels: front-left, front-right
+ */
+ // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
+
+
+ config[0] = adtsObjectType << 3; // samplingFrequencyIndex
+
+ config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
+ config[1] |= (adtsSampleingIndex & 0x01) << 7; // channelConfiguration
+
+ config[1] |= adtsChanelConfig << 3;
+
+ if (adtsObjectType === 5) {
+ // adtsExtensionSampleingIndex
+ config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
+ config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
+ // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
+
+ config[2] |= 2 << 2;
+ config[3] = 0;
+ }
+
+ return {
+ config: config,
+ samplerate: adtsSampleingRates[adtsSampleingIndex],
+ channelCount: adtsChanelConfig,
+ codec: 'mp4a.40.' + adtsObjectType,
+ manifestCodec: manifestCodec
+ };
+}
+function isHeaderPattern(data, offset) {
+ return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
+}
+function getHeaderLength(data, offset) {
+ return data[offset + 1] & 0x01 ? 7 : 9;
+}
+function getFullFrameLength(data, offset) {
+ return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
+}
+function isHeader(data, offset) {
+ // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
+ // Layer bits (position 14 and 15) in header should be always 0 for ADTS
+ // More info https://wiki.multimedia.cx/index.php?title=ADTS
+ if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
+ return true;
+ }
+
+ return false;
+}
+function adts_probe(data, offset) {
+ // same as isHeader but we also check that ADTS frame follows last ADTS frame
+ // or end of data is reached
+ if (isHeader(data, offset)) {
+ // ADTS header Length
+ var headerLength = getHeaderLength(data, offset);
+
+ if (offset + headerLength >= data.length) {
+ return false;
+ } // ADTS frame Length
+
+
+ var frameLength = getFullFrameLength(data, offset);
+
+ if (frameLength <= headerLength) {
+ return false;
+ }
+
+ var newOffset = offset + frameLength;
+
+ if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+function initTrackConfig(track, observer, data, offset, audioCodec) {
+ if (!track.samplerate) {
+ var config = getAudioConfig(observer, data, offset, audioCodec);
+ track.config = config.config;
+ track.samplerate = config.samplerate;
+ track.channelCount = config.channelCount;
+ track.codec = config.codec;
+ track.manifestCodec = config.manifestCodec;
+ logger["logger"].log("parsed codec:" + track.codec + ",rate:" + config.samplerate + ",nb channel:" + config.channelCount);
+ }
+}
+function getFrameDuration(samplerate) {
+ return 1024 * 90000 / samplerate;
+}
+function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
+ var headerLength, frameLength, stamp;
+ var length = data.length; // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
+
+ headerLength = getHeaderLength(data, offset); // retrieve frame size
+
+ frameLength = getFullFrameLength(data, offset);
+ frameLength -= headerLength;
+
+ if (frameLength > 0 && offset + headerLength + frameLength <= length) {
+ stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
+
+ return {
+ headerLength: headerLength,
+ frameLength: frameLength,
+ stamp: stamp
+ };
+ }
+
+ return undefined;
+}
+function appendFrame(track, data, offset, pts, frameIndex) {
+ var frameDuration = getFrameDuration(track.samplerate);
+ var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
+
+ if (header) {
+ var stamp = header.stamp;
+ var headerLength = header.headerLength;
+ var frameLength = header.frameLength; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
+
+ var aacSample = {
+ unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
+ pts: stamp,
+ dts: stamp
+ };
+ track.samples.push(aacSample);
+ return {
+ sample: aacSample,
+ length: frameLength + headerLength
+ };
+ }
+
+ return undefined;
+}
+// EXTERNAL MODULE: ./src/demux/id3.js
+var id3 = __webpack_require__("./src/demux/id3.js");
+
+// CONCATENATED MODULE: ./src/demux/aacdemuxer.js
+
+
+/**
+ * AAC demuxer
+ */
+
+
+
+
+var aacdemuxer_AACDemuxer = /*#__PURE__*/function () {
+ function AACDemuxer(observer, remuxer, config) {
+ this.observer = observer;
+ this.config = config;
+ this.remuxer = remuxer;
+ }
+
+ var _proto = AACDemuxer.prototype;
+
+ _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
+ this._audioTrack = {
+ container: 'audio/adts',
+ type: 'audio',
+ id: 0,
+ sequenceNumber: 0,
+ isAAC: true,
+ samples: [],
+ len: 0,
+ manifestCodec: audioCodec,
+ duration: duration,
+ inputTimeScale: 90000
+ };
+ };
+
+ _proto.resetTimeStamp = function resetTimeStamp() {};
+
+ AACDemuxer.probe = function probe(data) {
+ if (!data) {
+ return false;
+ } // Check for the ADTS sync word
+ // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
+ // Layer bits (position 14 and 15) in header should be always 0 for ADTS
+ // More info https://wiki.multimedia.cx/index.php?title=ADTS
+
+
+ var id3Data = id3["default"].getID3Data(data, 0) || [];
+ var offset = id3Data.length;
+
+ for (var length = data.length; offset < length; offset++) {
+ if (adts_probe(data, offset)) {
+ logger["logger"].log('ADTS sync word found !');
+ return true;
+ }
+ }
+
+ return false;
+ } // feed incoming data to the front of the parsing pipeline
+ ;
+
+ _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
+ var track = this._audioTrack;
+ var id3Data = id3["default"].getID3Data(data, 0) || [];
+ var timestamp = id3["default"].getTimeStamp(id3Data);
+ var pts = Object(number["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
+ var frameIndex = 0;
+ var stamp = pts;
+ var length = data.length;
+ var offset = id3Data.length;
+ var id3Samples = [{
+ pts: stamp,
+ dts: stamp,
+ data: id3Data
+ }];
+
+ while (offset < length - 1) {
+ if (isHeader(data, offset) && offset + 5 < length) {
+ initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
+ var frame = appendFrame(track, data, offset, pts, frameIndex);
+
+ if (frame) {
+ offset += frame.length;
+ stamp = frame.sample.pts;
+ frameIndex++;
+ } else {
+ logger["logger"].log('Unable to parse AAC frame');
+ break;
+ }
+ } else if (id3["default"].isHeader(data, offset)) {
+ id3Data = id3["default"].getID3Data(data, offset);
+ id3Samples.push({
+ pts: stamp,
+ dts: stamp,
+ data: id3Data
+ });
+ offset += id3Data.length;
+ } else {
+ // nothing found, keep looking
+ offset++;
+ }
+ }
+
+ this.remuxer.remux(track, {
+ samples: []
+ }, {
+ samples: id3Samples,
+ inputTimeScale: 90000
+ }, {
+ samples: []
+ }, timeOffset, contiguous, accurateTimeOffset);
+ };
+
+ _proto.destroy = function destroy() {};
+
+ return AACDemuxer;
+}();
+
+/* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer);
+// EXTERNAL MODULE: ./src/demux/mp4demuxer.js
+var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
+
+// CONCATENATED MODULE: ./src/demux/mpegaudio.js
+/**
+ * MPEG parser helper
+ */
+var MpegAudio = {
+ BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
+ SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
+ SamplesCoefficients: [// MPEG 2.5
+ [0, // Reserved
+ 72, // Layer3
+ 144, // Layer2
+ 12 // Layer1
+ ], // Reserved
+ [0, // Reserved
+ 0, // Layer3
+ 0, // Layer2
+ 0 // Layer1
+ ], // MPEG 2
+ [0, // Reserved
+ 72, // Layer3
+ 144, // Layer2
+ 12 // Layer1
+ ], // MPEG 1
+ [0, // Reserved
+ 144, // Layer3
+ 144, // Layer2
+ 12 // Layer1
+ ]],
+ BytesInSlot: [0, // Reserved
+ 1, // Layer3
+ 1, // Layer2
+ 4 // Layer1
+ ],
+ appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
+ // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
+ if (offset + 24 > data.length) {
+ return undefined;
+ }
+
+ var header = this.parseHeader(data, offset);
+
+ if (header && offset + header.frameLength <= data.length) {
+ var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
+ var stamp = pts + frameIndex * frameDuration;
+ var sample = {
+ unit: data.subarray(offset, offset + header.frameLength),
+ pts: stamp,
+ dts: stamp
+ };
+ track.config = [];
+ track.channelCount = header.channelCount;
+ track.samplerate = header.sampleRate;
+ track.samples.push(sample);
+ return {
+ sample: sample,
+ length: header.frameLength
+ };
+ }
+
+ return undefined;
+ },
+ parseHeader: function parseHeader(data, offset) {
+ var headerB = data[offset + 1] >> 3 & 3;
+ var headerC = data[offset + 1] >> 1 & 3;
+ var headerE = data[offset + 2] >> 4 & 15;
+ var headerF = data[offset + 2] >> 2 & 3;
+ var headerG = data[offset + 2] >> 1 & 1;
+
+ if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
+ var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
+ var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
+ var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
+ var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
+ var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
+
+ var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
+ var bytesInSlot = MpegAudio.BytesInSlot[headerC];
+ var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
+ var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
+ return {
+ sampleRate: sampleRate,
+ channelCount: channelCount,
+ frameLength: frameLength,
+ samplesPerFrame: samplesPerFrame
+ };
+ }
+
+ return undefined;
+ },
+ isHeaderPattern: function isHeaderPattern(data, offset) {
+ return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
+ },
+ isHeader: function isHeader(data, offset) {
+ // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
+ // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
+ // More info http://www.mp3-tech.org/programmer/frame_header.html
+ if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
+ return true;
+ }
+
+ return false;
+ },
+ probe: function probe(data, offset) {
+ // same as isHeader but we also check that MPEG frame follows last MPEG frame
+ // or end of data is reached
+ if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
+ // MPEG header Length
+ var headerLength = 4; // MPEG frame Length
+
+ var header = this.parseHeader(data, offset);
+ var frameLength = headerLength;
+
+ if (header && header.frameLength) {
+ frameLength = header.frameLength;
+ }
+
+ var newOffset = offset + frameLength;
+
+ if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+};
+/* harmony default export */ var mpegaudio = (MpegAudio);
+// CONCATENATED MODULE: ./src/demux/exp-golomb.js
+/**
+ * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
+*/
+
+
+var exp_golomb_ExpGolomb = /*#__PURE__*/function () {
+ function ExpGolomb(data) {
+ this.data = data; // the number of bytes left to examine in this.data
+
+ this.bytesAvailable = data.byteLength; // the current word being examined
+
+ this.word = 0; // :uint
+ // the number of bits left to examine in the current word
+
+ this.bitsAvailable = 0; // :uint
+ } // ():void
+
+
+ var _proto = ExpGolomb.prototype;
+
+ _proto.loadWord = function loadWord() {
+ var data = this.data,
+ bytesAvailable = this.bytesAvailable,
+ position = data.byteLength - bytesAvailable,
+ workingBytes = new Uint8Array(4),
+ availableBytes = Math.min(4, bytesAvailable);
+
+ if (availableBytes === 0) {
+ throw new Error('no bytes available');
+ }
+
+ workingBytes.set(data.subarray(position, position + availableBytes));
+ this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
+
+ this.bitsAvailable = availableBytes * 8;
+ this.bytesAvailable -= availableBytes;
+ } // (count:int):void
+ ;
+
+ _proto.skipBits = function skipBits(count) {
+ var skipBytes; // :int
+
+ if (this.bitsAvailable > count) {
+ this.word <<= count;
+ this.bitsAvailable -= count;
+ } else {
+ count -= this.bitsAvailable;
+ skipBytes = count >> 3;
+ count -= skipBytes >> 3;
+ this.bytesAvailable -= skipBytes;
+ this.loadWord();
+ this.word <<= count;
+ this.bitsAvailable -= count;
+ }
+ } // (size:int):uint
+ ;
+
+ _proto.readBits = function readBits(size) {
+ var bits = Math.min(this.bitsAvailable, size),
+ // :uint
+ valu = this.word >>> 32 - bits; // :uint
+
+ if (size > 32) {
+ logger["logger"].error('Cannot read more than 32 bits at a time');
+ }
+
+ this.bitsAvailable -= bits;
+
+ if (this.bitsAvailable > 0) {
+ this.word <<= bits;
+ } else if (this.bytesAvailable > 0) {
+ this.loadWord();
+ }
+
+ bits = size - bits;
+
+ if (bits > 0 && this.bitsAvailable) {
+ return valu << bits | this.readBits(bits);
+ } else {
+ return valu;
+ }
+ } // ():uint
+ ;
+
+ _proto.skipLZ = function skipLZ() {
+ var leadingZeroCount; // :uint
+
+ for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
+ if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
+ // the first bit of working word is 1
+ this.word <<= leadingZeroCount;
+ this.bitsAvailable -= leadingZeroCount;
+ return leadingZeroCount;
+ }
+ } // we exhausted word and still have not found a 1
+
+
+ this.loadWord();
+ return leadingZeroCount + this.skipLZ();
+ } // ():void
+ ;
+
+ _proto.skipUEG = function skipUEG() {
+ this.skipBits(1 + this.skipLZ());
+ } // ():void
+ ;
+
+ _proto.skipEG = function skipEG() {
+ this.skipBits(1 + this.skipLZ());
+ } // ():uint
+ ;
+
+ _proto.readUEG = function readUEG() {
+ var clz = this.skipLZ(); // :uint
+
+ return this.readBits(clz + 1) - 1;
+ } // ():int
+ ;
+
+ _proto.readEG = function readEG() {
+ var valu = this.readUEG(); // :int
+
+ if (0x01 & valu) {
+ // the number is odd if the low order bit is set
+ return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
+ } else {
+ return -1 * (valu >>> 1); // divide by two then make it negative
+ }
+ } // Some convenience functions
+ // :Boolean
+ ;
+
+ _proto.readBoolean = function readBoolean() {
+ return this.readBits(1) === 1;
+ } // ():int
+ ;
+
+ _proto.readUByte = function readUByte() {
+ return this.readBits(8);
+ } // ():int
+ ;
+
+ _proto.readUShort = function readUShort() {
+ return this.readBits(16);
+ } // ():int
+ ;
+
+ _proto.readUInt = function readUInt() {
+ return this.readBits(32);
+ }
+ /**
+ * Advance the ExpGolomb decoder past a scaling list. The scaling
+ * list is optionally transmitted as part of a sequence parameter
+ * set and is not relevant to transmuxing.
+ * @param count {number} the number of entries in this scaling list
+ * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
+ */
+ ;
+
+ _proto.skipScalingList = function skipScalingList(count) {
+ var lastScale = 8,
+ nextScale = 8,
+ j,
+ deltaScale;
+
+ for (j = 0; j < count; j++) {
+ if (nextScale !== 0) {
+ deltaScale = this.readEG();
+ nextScale = (lastScale + deltaScale + 256) % 256;
+ }
+
+ lastScale = nextScale === 0 ? lastScale : nextScale;
+ }
+ }
+ /**
+ * Read a sequence parameter set and return some interesting video
+ * properties. A sequence parameter set is the H264 metadata that
+ * describes the properties of upcoming video frames.
+ * @param data {Uint8Array} the bytes of a sequence parameter set
+ * @return {object} an object with configuration parsed from the
+ * sequence parameter set, including the dimensions of the
+ * associated video frames.
+ */
+ ;
+
+ _proto.readSPS = function readSPS() {
+ var frameCropLeftOffset = 0,
+ frameCropRightOffset = 0,
+ frameCropTopOffset = 0,
+ frameCropBottomOffset = 0,
+ profileIdc,
+ profileCompat,
+ levelIdc,
+ numRefFramesInPicOrderCntCycle,
+ picWidthInMbsMinus1,
+ picHeightInMapUnitsMinus1,
+ frameMbsOnlyFlag,
+ scalingListCount,
+ i,
+ readUByte = this.readUByte.bind(this),
+ readBits = this.readBits.bind(this),
+ readUEG = this.readUEG.bind(this),
+ readBoolean = this.readBoolean.bind(this),
+ skipBits = this.skipBits.bind(this),
+ skipEG = this.skipEG.bind(this),
+ skipUEG = this.skipUEG.bind(this),
+ skipScalingList = this.skipScalingList.bind(this);
+ readUByte();
+ profileIdc = readUByte(); // profile_idc
+
+ profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
+
+ skipBits(3); // reserved_zero_3bits u(3),
+
+ levelIdc = readUByte(); // level_idc u(8)
+
+ skipUEG(); // seq_parameter_set_id
+ // some profiles have more optional data we don't need
+
+ if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
+ var chromaFormatIdc = readUEG();
+
+ if (chromaFormatIdc === 3) {
+ skipBits(1);
+ } // separate_colour_plane_flag
+
+
+ skipUEG(); // bit_depth_luma_minus8
+
+ skipUEG(); // bit_depth_chroma_minus8
+
+ skipBits(1); // qpprime_y_zero_transform_bypass_flag
+
+ if (readBoolean()) {
+ // seq_scaling_matrix_present_flag
+ scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
+
+ for (i = 0; i < scalingListCount; i++) {
+ if (readBoolean()) {
+ // seq_scaling_list_present_flag[ i ]
+ if (i < 6) {
+ skipScalingList(16);
+ } else {
+ skipScalingList(64);
+ }
+ }
+ }
+ }
+ }
+
+ skipUEG(); // log2_max_frame_num_minus4
+
+ var picOrderCntType = readUEG();
+
+ if (picOrderCntType === 0) {
+ readUEG(); // log2_max_pic_order_cnt_lsb_minus4
+ } else if (picOrderCntType === 1) {
+ skipBits(1); // delta_pic_order_always_zero_flag
+
+ skipEG(); // offset_for_non_ref_pic
+
+ skipEG(); // offset_for_top_to_bottom_field
+
+ numRefFramesInPicOrderCntCycle = readUEG();
+
+ for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
+ skipEG();
+ } // offset_for_ref_frame[ i ]
+
+ }
+
+ skipUEG(); // max_num_ref_frames
+
+ skipBits(1); // gaps_in_frame_num_value_allowed_flag
+
+ picWidthInMbsMinus1 = readUEG();
+ picHeightInMapUnitsMinus1 = readUEG();
+ frameMbsOnlyFlag = readBits(1);
+
+ if (frameMbsOnlyFlag === 0) {
+ skipBits(1);
+ } // mb_adaptive_frame_field_flag
+
+
+ skipBits(1); // direct_8x8_inference_flag
+
+ if (readBoolean()) {
+ // frame_cropping_flag
+ frameCropLeftOffset = readUEG();
+ frameCropRightOffset = readUEG();
+ frameCropTopOffset = readUEG();
+ frameCropBottomOffset = readUEG();
+ }
+
+ var pixelRatio = [1, 1];
+
+ if (readBoolean()) {
+ // vui_parameters_present_flag
+ if (readBoolean()) {
+ // aspect_ratio_info_present_flag
+ var aspectRatioIdc = readUByte();
+
+ switch (aspectRatioIdc) {
+ case 1:
+ pixelRatio = [1, 1];
+ break;
+
+ case 2:
+ pixelRatio = [12, 11];
+ break;
+
+ case 3:
+ pixelRatio = [10, 11];
+ break;
+
+ case 4:
+ pixelRatio = [16, 11];
+ break;
+
+ case 5:
+ pixelRatio = [40, 33];
+ break;
+
+ case 6:
+ pixelRatio = [24, 11];
+ break;
+
+ case 7:
+ pixelRatio = [20, 11];
+ break;
+
+ case 8:
+ pixelRatio = [32, 11];
+ break;
+
+ case 9:
+ pixelRatio = [80, 33];
+ break;
+
+ case 10:
+ pixelRatio = [18, 11];
+ break;
+
+ case 11:
+ pixelRatio = [15, 11];
+ break;
+
+ case 12:
+ pixelRatio = [64, 33];
+ break;
+
+ case 13:
+ pixelRatio = [160, 99];
+ break;
+
+ case 14:
+ pixelRatio = [4, 3];
+ break;
+
+ case 15:
+ pixelRatio = [3, 2];
+ break;
+
+ case 16:
+ pixelRatio = [2, 1];
+ break;
+
+ case 255:
+ {
+ pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
+ break;
+ }
+ }
+ }
+ }
+
+ return {
+ width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
+ height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
+ pixelRatio: pixelRatio
+ };
+ };
+
+ _proto.readSliceType = function readSliceType() {
+ // skip NALu type
+ this.readUByte(); // discard first_mb_in_slice
+
+ this.readUEG(); // return slice_type
+
+ return this.readUEG();
+ };
+
+ return ExpGolomb;
+}();
+
+/* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb);
+// CONCATENATED MODULE: ./src/demux/sample-aes.js
+/**
+ * SAMPLE-AES decrypter
+*/
+
+
+var sample_aes_SampleAesDecrypter = /*#__PURE__*/function () {
+ function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
+ this.decryptdata = decryptdata;
+ this.discardEPB = discardEPB;
+ this.decrypter = new crypt_decrypter["default"](observer, config, {
+ removePKCS7Padding: false
+ });
+ }
+
+ var _proto = SampleAesDecrypter.prototype;
+
+ _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
+ this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
+ } // AAC - encrypt all full 16 bytes blocks starting from offset 16
+ ;
+
+ _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
+ var curUnit = samples[sampleIndex].unit;
+ var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
+ var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
+ var localthis = this;
+ this.decryptBuffer(encryptedBuffer, function (decryptedData) {
+ decryptedData = new Uint8Array(decryptedData);
+ curUnit.set(decryptedData, 16);
+
+ if (!sync) {
+ localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
+ }
+ });
+ };
+
+ _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
+ for (;; sampleIndex++) {
+ if (sampleIndex >= samples.length) {
+ callback();
+ return;
+ }
+
+ if (samples[sampleIndex].unit.length < 32) {
+ continue;
+ }
+
+ var sync = this.decrypter.isSync();
+ this.decryptAacSample(samples, sampleIndex, callback, sync);
+
+ if (!sync) {
+ return;
+ }
+ }
+ } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
+ ;
+
+ _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
+ var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
+ var encryptedData = new Int8Array(encryptedDataLen);
+ var outputPos = 0;
+
+ for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
+ encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
+ }
+
+ return encryptedData;
+ };
+
+ _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
+ decryptedData = new Uint8Array(decryptedData);
+ var inputPos = 0;
+
+ for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
+ decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
+ }
+
+ return decodedData;
+ };
+
+ _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
+ var decodedData = this.discardEPB(curUnit.data);
+ var encryptedData = this.getAvcEncryptedData(decodedData);
+ var localthis = this;
+ this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
+ curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
+
+ if (!sync) {
+ localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
+ }
+ });
+ };
+
+ _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
+ for (;; sampleIndex++, unitIndex = 0) {
+ if (sampleIndex >= samples.length) {
+ callback();
+ return;
+ }
+
+ var curUnits = samples[sampleIndex].units;
+
+ for (;; unitIndex++) {
+ if (unitIndex >= curUnits.length) {
+ break;
+ }
+
+ var curUnit = curUnits[unitIndex];
+
+ if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
+ continue;
+ }
+
+ var sync = this.decrypter.isSync();
+ this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
+
+ if (!sync) {
+ return;
+ }
+ }
+ }
+ };
+
+ return SampleAesDecrypter;
+}();
+
+/* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter);
+// CONCATENATED MODULE: ./src/demux/tsdemuxer.js
+/**
+ * highly optimized TS demuxer:
+ * parse PAT, PMT
+ * extract PES packet from audio and video PIDs
+ * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
+ * trigger the remuxer upon parsing completion
+ * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
+ * it also controls the remuxing process :
+ * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
+*/
+
+
+
+
+ // import Hex from '../utils/hex';
+
+
+
+ // We are using fixed track IDs for driving the MP4 remuxer
+// instead of following the TS PIDs.
+// There is no reason not to do this and some browsers/SourceBuffer-demuxers
+// may not like if there are TrackID "switches"
+// See https://github.com/video-dev/hls.js/issues/1331
+// Here we are mapping our internal track types to constant MP4 track IDs
+// With MSE currently one can only have one track of each, and we are muxing
+// whatever video/audio rendition in them.
+
+var RemuxerTrackIdConfig = {
+ video: 1,
+ audio: 2,
+ id3: 3,
+ text: 4
+};
+
+var tsdemuxer_TSDemuxer = /*#__PURE__*/function () {
+ function TSDemuxer(observer, remuxer, config, typeSupported) {
+ this.observer = observer;
+ this.config = config;
+ this.typeSupported = typeSupported;
+ this.remuxer = remuxer;
+ this.sampleAes = null;
+ this.pmtUnknownTypes = {};
+ }
+
+ var _proto = TSDemuxer.prototype;
+
+ _proto.setDecryptData = function setDecryptData(decryptdata) {
+ if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
+ this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB);
+ } else {
+ this.sampleAes = null;
+ }
+ };
+
+ TSDemuxer.probe = function probe(data) {
+ var syncOffset = TSDemuxer._syncOffset(data);
+
+ if (syncOffset < 0) {
+ return false;
+ } else {
+ if (syncOffset) {
+ logger["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
+ }
+
+ return true;
+ }
+ };
+
+ TSDemuxer._syncOffset = function _syncOffset(data) {
+ // scan 1000 first bytes
+ var scanwindow = Math.min(1000, data.length - 3 * 188);
+ var i = 0;
+
+ while (i < scanwindow) {
+ // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
+ if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
+ return i;
+ } else {
+ i++;
+ }
+ }
+
+ return -1;
+ }
+ /**
+ * Creates a track model internal to demuxer used to drive remuxing input
+ *
+ * @param {string} type 'audio' | 'video' | 'id3' | 'text'
+ * @param {number} duration
+ * @return {object} TSDemuxer's internal track model
+ */
+ ;
+
+ TSDemuxer.createTrack = function createTrack(type, duration) {
+ return {
+ container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
+ type: type,
+ id: RemuxerTrackIdConfig[type],
+ pid: -1,
+ inputTimeScale: 90000,
+ sequenceNumber: 0,
+ samples: [],
+ dropped: type === 'video' ? 0 : undefined,
+ isAAC: type === 'audio' ? true : undefined,
+ duration: type === 'audio' ? duration : undefined
+ };
+ }
+ /**
+ * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
+ * Resets all internal track instances of the demuxer.
+ *
+ * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
+ * @param {object} initSegment
+ * @param {string} audioCodec
+ * @param {string} videoCodec
+ * @param {number} duration (in TS timescale = 90kHz)
+ */
+ ;
+
+ _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
+ this.pmtParsed = false;
+ this._pmtId = -1;
+ this.pmtUnknownTypes = {};
+ this._avcTrack = TSDemuxer.createTrack('video', duration);
+ this._audioTrack = TSDemuxer.createTrack('audio', duration);
+ this._id3Track = TSDemuxer.createTrack('id3', duration);
+ this._txtTrack = TSDemuxer.createTrack('text', duration); // flush any partial content
+
+ this.aacOverFlow = null;
+ this.aacLastPTS = null;
+ this.avcSample = null;
+ this.audioCodec = audioCodec;
+ this.videoCodec = videoCodec;
+ this._duration = duration;
+ }
+ /**
+ *
+ * @override
+ */
+ ;
+
+ _proto.resetTimeStamp = function resetTimeStamp() {} // feed incoming data to the front of the parsing pipeline
+ ;
+
+ _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
+ var start,
+ len = data.length,
+ stt,
+ pid,
+ atf,
+ offset,
+ pes,
+ unknownPIDs = false;
+ this.pmtUnknownTypes = {};
+ this.contiguous = contiguous;
+
+ var pmtParsed = this.pmtParsed,
+ avcTrack = this._avcTrack,
+ audioTrack = this._audioTrack,
+ id3Track = this._id3Track,
+ avcId = avcTrack.pid,
+ audioId = audioTrack.pid,
+ id3Id = id3Track.pid,
+ pmtId = this._pmtId,
+ avcData = avcTrack.pesData,
+ audioData = audioTrack.pesData,
+ id3Data = id3Track.pesData,
+ parsePAT = this._parsePAT,
+ parsePMT = this._parsePMT.bind(this),
+ parsePES = this._parsePES,
+ parseAVCPES = this._parseAVCPES.bind(this),
+ parseAACPES = this._parseAACPES.bind(this),
+ parseMPEGPES = this._parseMPEGPES.bind(this),
+ parseID3PES = this._parseID3PES.bind(this);
+
+ var syncOffset = TSDemuxer._syncOffset(data); // don't parse last TS packet if incomplete
+
+
+ len -= (len + syncOffset) % 188; // loop through TS packets
+
+ for (start = syncOffset; start < len; start += 188) {
+ if (data[start] === 0x47) {
+ stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
+
+ pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
+ atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
+
+ if (atf > 1) {
+ offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
+
+ if (offset === start + 188) {
+ continue;
+ }
+ } else {
+ offset = start + 4;
+ }
+
+ switch (pid) {
+ case avcId:
+ if (stt) {
+ if (avcData && (pes = parsePES(avcData))) {
+ parseAVCPES(pes, false);
+ }
+
+ avcData = {
+ data: [],
+ size: 0
+ };
+ }
+
+ if (avcData) {
+ avcData.data.push(data.subarray(offset, start + 188));
+ avcData.size += start + 188 - offset;
+ }
+
+ break;
+
+ case audioId:
+ if (stt) {
+ if (audioData && (pes = parsePES(audioData))) {
+ if (audioTrack.isAAC) {
+ parseAACPES(pes);
+ } else {
+ parseMPEGPES(pes);
+ }
+ }
+
+ audioData = {
+ data: [],
+ size: 0
+ };
+ }
+
+ if (audioData) {
+ audioData.data.push(data.subarray(offset, start + 188));
+ audioData.size += start + 188 - offset;
+ }
+
+ break;
+
+ case id3Id:
+ if (stt) {
+ if (id3Data && (pes = parsePES(id3Data))) {
+ parseID3PES(pes);
+ }
+
+ id3Data = {
+ data: [],
+ size: 0
+ };
+ }
+
+ if (id3Data) {
+ id3Data.data.push(data.subarray(offset, start + 188));
+ id3Data.size += start + 188 - offset;
+ }
+
+ break;
+
+ case 0:
+ if (stt) {
+ offset += data[offset] + 1;
+ }
+
+ pmtId = this._pmtId = parsePAT(data, offset);
+ break;
+
+ case pmtId:
+ if (stt) {
+ offset += data[offset] + 1;
+ }
+
+ var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null); // only update track id if track PID found while parsing PMT
+ // this is to avoid resetting the PID to -1 in case
+ // track PID transiently disappears from the stream
+ // this could happen in case of transient missing audio samples for example
+ // NOTE this is only the PID of the track as found in TS,
+ // but we are not using this for MP4 track IDs.
+
+ avcId = parsedPIDs.avc;
+
+ if (avcId > 0) {
+ avcTrack.pid = avcId;
+ }
+
+ audioId = parsedPIDs.audio;
+
+ if (audioId > 0) {
+ audioTrack.pid = audioId;
+ audioTrack.isAAC = parsedPIDs.isAAC;
+ }
+
+ id3Id = parsedPIDs.id3;
+
+ if (id3Id > 0) {
+ id3Track.pid = id3Id;
+ }
+
+ if (unknownPIDs && !pmtParsed) {
+ logger["logger"].log('reparse from beginning');
+ unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
+
+ start = syncOffset - 188;
+ }
+
+ pmtParsed = this.pmtParsed = true;
+ break;
+
+ case 17:
+ case 0x1fff:
+ break;
+
+ default:
+ unknownPIDs = true;
+ break;
+ }
+ } else {
+ this.observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
+ fatal: false,
+ reason: 'TS packet did not start with 0x47'
+ });
+ }
+ } // try to parse last PES packets
+
+
+ if (avcData && (pes = parsePES(avcData))) {
+ parseAVCPES(pes, true);
+ avcTrack.pesData = null;
+ } else {
+ // either avcData null or PES truncated, keep it for next frag parsing
+ avcTrack.pesData = avcData;
+ }
+
+ if (audioData && (pes = parsePES(audioData))) {
+ if (audioTrack.isAAC) {
+ parseAACPES(pes);
+ } else {
+ parseMPEGPES(pes);
+ }
+
+ audioTrack.pesData = null;
+ } else {
+ if (audioData && audioData.size) {
+ logger["logger"].log('last AAC PES packet truncated,might overlap between fragments');
+ } // either audioData null or PES truncated, keep it for next frag parsing
+
+
+ audioTrack.pesData = audioData;
+ }
+
+ if (id3Data && (pes = parsePES(id3Data))) {
+ parseID3PES(pes);
+ id3Track.pesData = null;
+ } else {
+ // either id3Data null or PES truncated, keep it for next frag parsing
+ id3Track.pesData = id3Data;
+ }
+
+ if (this.sampleAes == null) {
+ this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
+ } else {
+ this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
+ }
+ };
+
+ _proto.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
+ if (audioTrack.samples && audioTrack.isAAC) {
+ var localthis = this;
+ this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
+ localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
+ });
+ } else {
+ this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
+ }
+ };
+
+ _proto.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
+ if (videoTrack.samples) {
+ var localthis = this;
+ this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
+ localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
+ });
+ } else {
+ this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
+ }
+ };
+
+ _proto.destroy = function destroy() {
+ this._initPTS = this._initDTS = undefined;
+ this._duration = 0;
+ };
+
+ _proto._parsePAT = function _parsePAT(data, offset) {
+ // skip the PSI header and parse the first PMT entry
+ return (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
+ };
+
+ _proto._trackUnknownPmt = function _trackUnknownPmt(type, logLevel, message) {
+ // Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)
+ // For more information on elementary stream types see:
+ // https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types
+ var result = this.pmtUnknownTypes[type] || 0;
+
+ if (result === 0) {
+ this.pmtUnknownTypes[type] = 0;
+ logLevel.call(logger["logger"], message);
+ }
+
+ this.pmtUnknownTypes[type]++;
+ return result;
+ };
+
+ _proto._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {
+ var sectionLength,
+ tableEnd,
+ programInfoLength,
+ pid,
+ result = {
+ audio: -1,
+ avc: -1,
+ id3: -1,
+ isAAC: true
+ };
+ sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
+ tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
+ // long the program info descriptors are
+
+ programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
+
+ offset += 12 + programInfoLength;
+
+ while (offset < tableEnd) {
+ pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
+
+ switch (data[offset]) {
+ case 0xcf:
+ // SAMPLE-AES AAC
+ if (!isSampleAes) {
+ this._trackUnknownPmt(data[offset], logger["logger"].warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
+
+ break;
+ }
+
+ /* falls through */
+ // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
+
+ case 0x0f:
+ // logger.log('AAC PID:' + pid);
+ if (result.audio === -1) {
+ result.audio = pid;
+ }
+
+ break;
+ // Packetized metadata (ID3)
+
+ case 0x15:
+ // logger.log('ID3 PID:' + pid);
+ if (result.id3 === -1) {
+ result.id3 = pid;
+ }
+
+ break;
+
+ case 0xdb:
+ // SAMPLE-AES AVC
+ if (!isSampleAes) {
+ this._trackUnknownPmt(data[offset], logger["logger"].warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');
+
+ break;
+ }
+
+ /* falls through */
+ // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
+
+ case 0x1b:
+ // logger.log('AVC PID:' + pid);
+ if (result.avc === -1) {
+ result.avc = pid;
+ }
+
+ break;
+ // ISO/IEC 11172-3 (MPEG-1 audio)
+ // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
+
+ case 0x03:
+ case 0x04:
+ // logger.log('MPEG PID:' + pid);
+ if (!mpegSupported) {
+ this._trackUnknownPmt(data[offset], logger["logger"].warn, 'MPEG audio found, not supported in this browser');
+ } else if (result.audio === -1) {
+ result.audio = pid;
+ result.isAAC = false;
+ }
+
+ break;
+
+ case 0x24:
+ this._trackUnknownPmt(data[offset], logger["logger"].warn, 'Unsupported HEVC stream type found');
+
+ break;
+
+ default:
+ this._trackUnknownPmt(data[offset], logger["logger"].log, 'Unknown stream type:' + data[offset]);
+
+ break;
+ } // move to the next table entry
+ // skip past the elementary stream descriptors, if present
+
+
+ offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
+ }
+
+ return result;
+ };
+
+ _proto._parsePES = function _parsePES(stream) {
+ var i = 0,
+ frag,
+ pesFlags,
+ pesPrefix,
+ pesLen,
+ pesHdrLen,
+ pesData,
+ pesPts,
+ pesDts,
+ payloadStartOffset,
+ data = stream.data; // safety check
+
+ if (!stream || stream.size === 0) {
+ return null;
+ } // we might need up to 19 bytes to read PES header
+ // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
+ // usually only one merge is needed (and this is rare ...)
+
+
+ while (data[0].length < 19 && data.length > 1) {
+ var newData = new Uint8Array(data[0].length + data[1].length);
+ newData.set(data[0]);
+ newData.set(data[1], data[0].length);
+ data[0] = newData;
+ data.splice(1, 1);
+ } // retrieve PTS/DTS from first fragment
+
+
+ frag = data[0];
+ pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
+
+ if (pesPrefix === 1) {
+ pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
+ // minus 6 : PES header size
+
+ if (pesLen && pesLen > stream.size - 6) {
+ return null;
+ }
+
+ pesFlags = frag[7];
+
+ if (pesFlags & 0xC0) {
+ /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
+ as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
+ as Bitwise operators treat their operands as a sequence of 32 bits */
+ pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
+ (frag[10] & 0xFF) * 4194304 + // 1 << 22
+ (frag[11] & 0xFE) * 16384 + // 1 << 14
+ (frag[12] & 0xFF) * 128 + // 1 << 7
+ (frag[13] & 0xFE) / 2;
+
+ if (pesFlags & 0x40) {
+ pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
+ (frag[15] & 0xFF) * 4194304 + // 1 << 22
+ (frag[16] & 0xFE) * 16384 + // 1 << 14
+ (frag[17] & 0xFF) * 128 + // 1 << 7
+ (frag[18] & 0xFE) / 2;
+
+ if (pesPts - pesDts > 60 * 90000) {
+ logger["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
+ pesPts = pesDts;
+ }
+ } else {
+ pesDts = pesPts;
+ }
+ }
+
+ pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
+
+ payloadStartOffset = pesHdrLen + 9;
+
+ if (stream.size <= payloadStartOffset) {
+ return null;
+ }
+
+ stream.size -= payloadStartOffset; // reassemble PES packet
+
+ pesData = new Uint8Array(stream.size);
+
+ for (var j = 0, dataLen = data.length; j < dataLen; j++) {
+ frag = data[j];
+ var len = frag.byteLength;
+
+ if (payloadStartOffset) {
+ if (payloadStartOffset > len) {
+ // trim full frag if PES header bigger than frag
+ payloadStartOffset -= len;
+ continue;
+ } else {
+ // trim partial frag if PES header smaller than frag
+ frag = frag.subarray(payloadStartOffset);
+ len -= payloadStartOffset;
+ payloadStartOffset = 0;
+ }
+ }
+
+ pesData.set(frag, i);
+ i += len;
+ }
+
+ if (pesLen) {
+ // payload size : remove PES header + PES extension
+ pesLen -= pesHdrLen + 3;
+ }
+
+ return {
+ data: pesData,
+ pts: pesPts,
+ dts: pesDts,
+ len: pesLen
+ };
+ } else {
+ return null;
+ }
+ };
+
+ _proto.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
+ if (avcSample.units.length && avcSample.frame) {
+ var samples = avcTrack.samples;
+ var nbSamples = samples.length; // if sample does not have PTS/DTS, patch with last sample PTS/DTS
+
+ if (isNaN(avcSample.pts)) {
+ if (nbSamples) {
+ var lastSample = samples[nbSamples - 1];
+ avcSample.pts = lastSample.pts;
+ avcSample.dts = lastSample.dts;
+ } else {
+ // dropping samples, no timestamp found
+ avcTrack.dropped++;
+ return;
+ }
+ } // only push AVC sample if starting with a keyframe is not mandatory OR
+ // if keyframe already found in this fragment OR
+ // keyframe found in last fragment (track.sps) AND
+ // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
+
+
+ if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
+ avcSample.id = nbSamples;
+ samples.push(avcSample);
+ } else {
+ // dropped samples, track it
+ avcTrack.dropped++;
+ }
+ }
+
+ if (avcSample.debug.length) {
+ logger["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
+ }
+ };
+
+ _proto._parseAVCPES = function _parseAVCPES(pes, last) {
+ var _this = this;
+
+ // logger.log('parse new PES');
+ var track = this._avcTrack,
+ units = this._parseAVCNALu(pes.data),
+ debug = false,
+ expGolombDecoder,
+ avcSample = this.avcSample,
+ push,
+ spsfound = false,
+ i,
+ pushAccesUnit = this.pushAccesUnit.bind(this),
+ createAVCSample = function createAVCSample(key, pts, dts, debug) {
+ return {
+ key: key,
+ pts: pts,
+ dts: dts,
+ units: [],
+ debug: debug
+ };
+ }; // free pes.data to save up some memory
+
+
+ pes.data = null; // if new NAL units found and last sample still there, let's push ...
+ // this helps parsing streams with missing AUD (only do this if AUD never found)
+
+ if (avcSample && units.length && !track.audFound) {
+ pushAccesUnit(avcSample, track);
+ avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
+ }
+
+ units.forEach(function (unit) {
+ switch (unit.type) {
+ // NDR
+ case 1:
+ push = true;
+
+ if (!avcSample) {
+ avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
+ }
+
+ if (debug) {
+ avcSample.debug += 'NDR ';
+ }
+
+ avcSample.frame = true;
+ var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
+
+ if (spsfound && data.length > 4) {
+ // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
+ var sliceType = new exp_golomb(data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
+ // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
+ // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
+ // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
+ // if (sliceType === 2 || sliceType === 7) {
+
+ if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
+ avcSample.key = true;
+ }
+ }
+
+ break;
+ // IDR
+
+ case 5:
+ push = true; // handle PES not starting with AUD
+
+ if (!avcSample) {
+ avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
+ }
+
+ if (debug) {
+ avcSample.debug += 'IDR ';
+ }
+
+ avcSample.key = true;
+ avcSample.frame = true;
+ break;
+ // SEI
+
+ case 6:
+ push = true;
+
+ if (debug && avcSample) {
+ avcSample.debug += 'SEI ';
+ }
+
+ expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data)); // skip frameType
+
+ expGolombDecoder.readUByte();
+ var payloadType = 0;
+ var payloadSize = 0;
+ var endOfCaptions = false;
+ var b = 0;
+
+ while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
+ payloadType = 0;
+
+ do {
+ b = expGolombDecoder.readUByte();
+ payloadType += b;
+ } while (b === 0xFF); // Parse payload size.
+
+
+ payloadSize = 0;
+
+ do {
+ b = expGolombDecoder.readUByte();
+ payloadSize += b;
+ } while (b === 0xFF); // TODO: there can be more than one payload in an SEI packet...
+ // TODO: need to read type and size in a while loop to get them all
+
+
+ if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
+ endOfCaptions = true;
+ var countryCode = expGolombDecoder.readUByte();
+
+ if (countryCode === 181) {
+ var providerCode = expGolombDecoder.readUShort();
+
+ if (providerCode === 49) {
+ var userStructure = expGolombDecoder.readUInt();
+
+ if (userStructure === 0x47413934) {
+ var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
+
+ if (userDataType === 3) {
+ var firstByte = expGolombDecoder.readUByte();
+ var secondByte = expGolombDecoder.readUByte();
+ var totalCCs = 31 & firstByte;
+ var byteArray = [firstByte, secondByte];
+
+ for (i = 0; i < totalCCs; i++) {
+ // 3 bytes per CC
+ byteArray.push(expGolombDecoder.readUByte());
+ byteArray.push(expGolombDecoder.readUByte());
+ byteArray.push(expGolombDecoder.readUByte());
+ }
+
+ _this._insertSampleInOrder(_this._txtTrack.samples, {
+ type: 3,
+ pts: pes.pts,
+ bytes: byteArray
+ });
+ }
+ }
+ }
+ }
+ } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
+ endOfCaptions = true;
+
+ if (payloadSize > 16) {
+ var uuidStrArray = [];
+
+ for (i = 0; i < 16; i++) {
+ uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
+
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
+ uuidStrArray.push('-');
+ }
+ }
+
+ var length = payloadSize - 16;
+ var userDataPayloadBytes = new Uint8Array(length);
+
+ for (i = 0; i < length; i++) {
+ userDataPayloadBytes[i] = expGolombDecoder.readUByte();
+ }
+
+ _this._insertSampleInOrder(_this._txtTrack.samples, {
+ pts: pes.pts,
+ payloadType: payloadType,
+ uuid: uuidStrArray.join(''),
+ userDataBytes: userDataPayloadBytes,
+ userData: Object(id3["utf8ArrayToStr"])(userDataPayloadBytes.buffer)
+ });
+ }
+ } else if (payloadSize < expGolombDecoder.bytesAvailable) {
+ for (i = 0; i < payloadSize; i++) {
+ expGolombDecoder.readUByte();
+ }
+ }
+ }
+
+ break;
+ // SPS
+
+ case 7:
+ push = true;
+ spsfound = true;
+
+ if (debug && avcSample) {
+ avcSample.debug += 'SPS ';
+ }
+
+ if (!track.sps) {
+ expGolombDecoder = new exp_golomb(unit.data);
+ var config = expGolombDecoder.readSPS();
+ track.width = config.width;
+ track.height = config.height;
+ track.pixelRatio = config.pixelRatio;
+ track.sps = [unit.data];
+ track.duration = _this._duration;
+ var codecarray = unit.data.subarray(1, 4);
+ var codecstring = 'avc1.';
+
+ for (i = 0; i < 3; i++) {
+ var h = codecarray[i].toString(16);
+
+ if (h.length < 2) {
+ h = '0' + h;
+ }
+
+ codecstring += h;
+ }
+
+ track.codec = codecstring;
+ }
+
+ break;
+ // PPS
+
+ case 8:
+ push = true;
+
+ if (debug && avcSample) {
+ avcSample.debug += 'PPS ';
+ }
+
+ if (!track.pps) {
+ track.pps = [unit.data];
+ }
+
+ break;
+ // AUD
+
+ case 9:
+ push = false;
+ track.audFound = true;
+
+ if (avcSample) {
+ pushAccesUnit(avcSample, track);
+ }
+
+ avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
+ break;
+ // Filler Data
+
+ case 12:
+ push = false;
+ break;
+
+ default:
+ push = false;
+
+ if (avcSample) {
+ avcSample.debug += 'unknown NAL ' + unit.type + ' ';
+ }
+
+ break;
+ }
+
+ if (avcSample && push) {
+ var _units = avcSample.units;
+
+ _units.push(unit);
+ }
+ }); // if last PES packet, push samples
+
+ if (last && avcSample) {
+ pushAccesUnit(avcSample, track);
+ this.avcSample = null;
+ }
+ };
+
+ _proto._insertSampleInOrder = function _insertSampleInOrder(arr, data) {
+ var len = arr.length;
+
+ if (len > 0) {
+ if (data.pts >= arr[len - 1].pts) {
+ arr.push(data);
+ } else {
+ for (var pos = len - 1; pos >= 0; pos--) {
+ if (data.pts < arr[pos].pts) {
+ arr.splice(pos, 0, data);
+ break;
+ }
+ }
+ }
+ } else {
+ arr.push(data);
+ }
+ };
+
+ _proto._getLastNalUnit = function _getLastNalUnit() {
+ var avcSample = this.avcSample,
+ lastUnit; // try to fallback to previous sample if current one is empty
+
+ if (!avcSample || avcSample.units.length === 0) {
+ var track = this._avcTrack,
+ samples = track.samples;
+ avcSample = samples[samples.length - 1];
+ }
+
+ if (avcSample) {
+ var units = avcSample.units;
+ lastUnit = units[units.length - 1];
+ }
+
+ return lastUnit;
+ };
+
+ _proto._parseAVCNALu = function _parseAVCNALu(array) {
+ var i = 0,
+ len = array.byteLength,
+ value,
+ overflow,
+ track = this._avcTrack,
+ state = track.naluState || 0,
+ lastState = state;
+ var units = [],
+ unit,
+ unitType,
+ lastUnitStart = -1,
+ lastUnitType; // logger.log('PES:' + Hex.hexDump(array));
+
+ if (state === -1) {
+ // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
+ lastUnitStart = 0; // NALu type is value read from offset 0
+
+ lastUnitType = array[0] & 0x1f;
+ state = 0;
+ i = 1;
+ }
+
+ while (i < len) {
+ value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
+
+ if (!state) {
+ state = value ? 0 : 1;
+ continue;
+ }
+
+ if (state === 1) {
+ state = value ? 0 : 2;
+ continue;
+ } // here we have state either equal to 2 or 3
+
+
+ if (!value) {
+ state = 3;
+ } else if (value === 1) {
+ if (lastUnitStart >= 0) {
+ unit = {
+ data: array.subarray(lastUnitStart, i - state - 1),
+ type: lastUnitType
+ }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
+
+ units.push(unit);
+ } else {
+ // lastUnitStart is undefined => this is the first start code found in this PES packet
+ // first check if start code delimiter is overlapping between 2 PES packets,
+ // ie it started in last packet (lastState not zero)
+ // and ended at the beginning of this PES packet (i <= 4 - lastState)
+ var lastUnit = this._getLastNalUnit();
+
+ if (lastUnit) {
+ if (lastState && i <= 4 - lastState) {
+ // start delimiter overlapping between PES packets
+ // strip start delimiter bytes from the end of last NAL unit
+ // check if lastUnit had a state different from zero
+ if (lastUnit.state) {
+ // strip last bytes
+ lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
+ }
+ } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
+
+
+ overflow = i - state - 1;
+
+ if (overflow > 0) {
+ // logger.log('first NALU found with overflow:' + overflow);
+ var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
+ tmp.set(lastUnit.data, 0);
+ tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
+ lastUnit.data = tmp;
+ }
+ }
+ } // check if we can read unit type
+
+
+ if (i < len) {
+ unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
+
+ lastUnitStart = i;
+ lastUnitType = unitType;
+ state = 0;
+ } else {
+ // not enough byte to read unit type. let's read it on next PES parsing
+ state = -1;
+ }
+ } else {
+ state = 0;
+ }
+ }
+
+ if (lastUnitStart >= 0 && state >= 0) {
+ unit = {
+ data: array.subarray(lastUnitStart, len),
+ type: lastUnitType,
+ state: state
+ };
+ units.push(unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
+ } // no NALu found
+
+
+ if (units.length === 0) {
+ // append pes.data to previous NAL unit
+ var _lastUnit = this._getLastNalUnit();
+
+ if (_lastUnit) {
+ var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
+
+ _tmp.set(_lastUnit.data, 0);
+
+ _tmp.set(array, _lastUnit.data.byteLength);
+
+ _lastUnit.data = _tmp;
+ }
+ }
+
+ track.naluState = state;
+ return units;
+ }
+ /**
+ * remove Emulation Prevention bytes from a RBSP
+ */
+ ;
+
+ _proto.discardEPB = function discardEPB(data) {
+ var length = data.byteLength,
+ EPBPositions = [],
+ i = 1,
+ newLength,
+ newData; // Find all `Emulation Prevention Bytes`
+
+ while (i < length - 2) {
+ if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
+ EPBPositions.push(i + 2);
+ i += 2;
+ } else {
+ i++;
+ }
+ } // If no Emulation Prevention Bytes were found just return the original
+ // array
+
+
+ if (EPBPositions.length === 0) {
+ return data;
+ } // Create a new array to hold the NAL unit data
+
+
+ newLength = length - EPBPositions.length;
+ newData = new Uint8Array(newLength);
+ var sourceIndex = 0;
+
+ for (i = 0; i < newLength; sourceIndex++, i++) {
+ if (sourceIndex === EPBPositions[0]) {
+ // Skip this byte
+ sourceIndex++; // Remove this position index
+
+ EPBPositions.shift();
+ }
+
+ newData[i] = data[sourceIndex];
+ }
+
+ return newData;
+ };
+
+ _proto._parseAACPES = function _parseAACPES(pes) {
+ var track = this._audioTrack,
+ data = pes.data,
+ pts = pes.pts,
+ startOffset = 0,
+ aacOverFlow = this.aacOverFlow,
+ aacLastPTS = this.aacLastPTS,
+ frameDuration,
+ frameIndex,
+ offset,
+ stamp,
+ len;
+
+ if (aacOverFlow) {
+ var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
+ tmp.set(aacOverFlow, 0);
+ tmp.set(data, aacOverFlow.byteLength); // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
+
+ data = tmp;
+ } // look for ADTS header (0xFFFx)
+
+
+ for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
+ if (isHeader(data, offset)) {
+ break;
+ }
+ } // if ADTS header does not start straight from the beginning of the PES payload, raise an error
+
+
+ if (offset) {
+ var reason, fatal;
+
+ if (offset < len - 1) {
+ reason = "AAC PES did not start with ADTS header,offset:" + offset;
+ fatal = false;
+ } else {
+ reason = 'no ADTS header found in AAC PES';
+ fatal = true;
+ }
+
+ logger["logger"].warn("parsing error:" + reason);
+ this.observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
+ fatal: fatal,
+ reason: reason
+ });
+
+ if (fatal) {
+ return;
+ }
+ }
+
+ initTrackConfig(track, this.observer, data, offset, this.audioCodec);
+ frameIndex = 0;
+ frameDuration = getFrameDuration(track.samplerate); // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
+ // first sample PTS should be equal to last sample PTS + frameDuration
+
+ if (aacOverFlow && aacLastPTS) {
+ var newPTS = aacLastPTS + frameDuration;
+
+ if (Math.abs(newPTS - pts) > 1) {
+ logger["logger"].log("AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
+ pts = newPTS;
+ }
+ } // scan for aac samples
+
+
+ while (offset < len) {
+ if (isHeader(data, offset)) {
+ if (offset + 5 < len) {
+ var frame = appendFrame(track, data, offset, pts, frameIndex);
+
+ if (frame) {
+ offset += frame.length;
+ stamp = frame.sample.pts;
+ frameIndex++;
+ continue;
+ }
+ } // We are at an ADTS header, but do not have enough data for a frame
+ // Remaining data will be added to aacOverFlow
+
+
+ break;
+ } else {
+ // nothing found, keep looking
+ offset++;
+ }
+ }
+
+ if (offset < len) {
+ aacOverFlow = data.subarray(offset, len); // logger.log(`AAC: overflow detected:${len-offset}`);
+ } else {
+ aacOverFlow = null;
+ }
+
+ this.aacOverFlow = aacOverFlow;
+ this.aacLastPTS = stamp;
+ };
+
+ _proto._parseMPEGPES = function _parseMPEGPES(pes) {
+ var data = pes.data;
+ var length = data.length;
+ var frameIndex = 0;
+ var offset = 0;
+ var pts = pes.pts;
+
+ while (offset < length) {
+ if (mpegaudio.isHeader(data, offset)) {
+ var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
+
+ if (frame) {
+ offset += frame.length;
+ frameIndex++;
+ } else {
+ // logger.log('Unable to parse Mpeg audio frame');
+ break;
+ }
+ } else {
+ // nothing found, keep looking
+ offset++;
+ }
+ }
+ };
+
+ _proto._parseID3PES = function _parseID3PES(pes) {
+ this._id3Track.samples.push(pes);
+ };
+
+ return TSDemuxer;
+}();
+
+/* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer);
+// CONCATENATED MODULE: ./src/demux/mp3demuxer.js
+/**
+ * MP3 demuxer
+ */
+
+
+
+
+var mp3demuxer_MP3Demuxer = /*#__PURE__*/function () {
+ function MP3Demuxer(observer, remuxer, config) {
+ this.observer = observer;
+ this.config = config;
+ this.remuxer = remuxer;
+ }
+
+ var _proto = MP3Demuxer.prototype;
+
+ _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
+ this._audioTrack = {
+ container: 'audio/mpeg',
+ type: 'audio',
+ id: -1,
+ sequenceNumber: 0,
+ isAAC: false,
+ samples: [],
+ len: 0,
+ manifestCodec: audioCodec,
+ duration: duration,
+ inputTimeScale: 90000
+ };
+ };
+
+ _proto.resetTimeStamp = function resetTimeStamp() {};
+
+ MP3Demuxer.probe = function probe(data) {
+ // check if data contains ID3 timestamp and MPEG sync word
+ var offset, length;
+ var id3Data = id3["default"].getID3Data(data, 0);
+
+ if (id3Data && id3["default"].getTimeStamp(id3Data) !== undefined) {
+ // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
+ // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
+ // More info http://www.mp3-tech.org/programmer/frame_header.html
+ for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
+ if (mpegaudio.probe(data, offset)) {
+ logger["logger"].log('MPEG Audio sync word found !');
+ return true;
+ }
+ }
+ }
+
+ return false;
+ } // feed incoming data to the front of the parsing pipeline
+ ;
+
+ _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
+ var id3Data = id3["default"].getID3Data(data, 0) || [];
+ var timestamp = id3["default"].getTimeStamp(id3Data);
+ var pts = timestamp !== undefined ? 90 * timestamp : timeOffset * 90000;
+ var offset = id3Data.length;
+ var length = data.length;
+ var frameIndex = 0,
+ stamp = 0;
+ var track = this._audioTrack;
+ var id3Samples = [{
+ pts: pts,
+ dts: pts,
+ data: id3Data
+ }];
+
+ while (offset < length) {
+ if (mpegaudio.isHeader(data, offset)) {
+ var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex);
+
+ if (frame) {
+ offset += frame.length;
+ stamp = frame.sample.pts;
+ frameIndex++;
+ } else {
+ // logger.log('Unable to parse Mpeg audio frame');
+ break;
+ }
+ } else if (id3["default"].isHeader(data, offset)) {
+ id3Data = id3["default"].getID3Data(data, offset);
+ id3Samples.push({
+ pts: stamp,
+ dts: stamp,
+ data: id3Data
+ });
+ offset += id3Data.length;
+ } else {
+ // nothing found, keep looking
+ offset++;
+ }
+ }
+
+ this.remuxer.remux(track, {
+ samples: []
+ }, {
+ samples: id3Samples,
+ inputTimeScale: 90000
+ }, {
+ samples: []
+ }, timeOffset, contiguous, accurateTimeOffset);
+ };
+
+ _proto.destroy = function destroy() {};
+
+ return MP3Demuxer;
+}();
+
+/* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer);
+// CONCATENATED MODULE: ./src/remux/aac-helper.js
+/**
+ * AAC helper
+ */
+var AAC = /*#__PURE__*/function () {
+ function AAC() {}
+
+ AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
+ switch (codec) {
+ case 'mp4a.40.2':
+ if (channelCount === 1) {
+ return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
+ } else if (channelCount === 2) {
+ return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
+ } else if (channelCount === 3) {
+ return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
+ } else if (channelCount === 4) {
+ return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
+ } else if (channelCount === 5) {
+ return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
+ } else if (channelCount === 6) {
+ return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
+ }
+
+ break;
+ // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
+
+ default:
+ if (channelCount === 1) {
+ // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
+ return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
+ } else if (channelCount === 2) {
+ // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
+ return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
+ } else if (channelCount === 3) {
+ // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
+ return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
+ }
+
+ break;
+ }
+
+ return null;
+ };
+
+ return AAC;
+}();
+
+/* harmony default export */ var aac_helper = (AAC);
+// CONCATENATED MODULE: ./src/remux/mp4-generator.js
+/**
+ * Generate MP4 Box
+*/
+var UINT32_MAX = Math.pow(2, 32) - 1;
+
+var MP4 = /*#__PURE__*/function () {
+ function MP4() {}
+
+ MP4.init = function init() {
+ MP4.types = {
+ avc1: [],
+ // codingname
+ avcC: [],
+ btrt: [],
+ dinf: [],
+ dref: [],
+ esds: [],
+ ftyp: [],
+ hdlr: [],
+ mdat: [],
+ mdhd: [],
+ mdia: [],
+ mfhd: [],
+ minf: [],
+ moof: [],
+ moov: [],
+ mp4a: [],
+ '.mp3': [],
+ mvex: [],
+ mvhd: [],
+ pasp: [],
+ sdtp: [],
+ stbl: [],
+ stco: [],
+ stsc: [],
+ stsd: [],
+ stsz: [],
+ stts: [],
+ tfdt: [],
+ tfhd: [],
+ traf: [],
+ trak: [],
+ trun: [],
+ trex: [],
+ tkhd: [],
+ vmhd: [],
+ smhd: []
+ };
+ var i;
+
+ for (i in MP4.types) {
+ if (MP4.types.hasOwnProperty(i)) {
+ MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
+ }
+ }
+
+ var videoHdlr = new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00, // pre_defined
+ 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
+ ]);
+ var audioHdlr = new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00, // pre_defined
+ 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
+ ]);
+ MP4.HDLR_TYPES = {
+ 'video': videoHdlr,
+ 'audio': audioHdlr
+ };
+ var dref = new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x01, // entry_count
+ 0x00, 0x00, 0x00, 0x0c, // entry_size
+ 0x75, 0x72, 0x6c, 0x20, // 'url' type
+ 0x00, // version 0
+ 0x00, 0x00, 0x01 // entry_flags
+ ]);
+ var stco = new Uint8Array([0x00, // version
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00 // entry_count
+ ]);
+ MP4.STTS = MP4.STSC = MP4.STCO = stco;
+ MP4.STSZ = new Uint8Array([0x00, // version
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00, // sample_size
+ 0x00, 0x00, 0x00, 0x00 // sample_count
+ ]);
+ MP4.VMHD = new Uint8Array([0x00, // version
+ 0x00, 0x00, 0x01, // flags
+ 0x00, 0x00, // graphicsmode
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
+ ]);
+ MP4.SMHD = new Uint8Array([0x00, // version
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, // balance
+ 0x00, 0x00 // reserved
+ ]);
+ MP4.STSD = new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x01]); // entry_count
+
+ var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
+
+ var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
+
+ var minorVersion = new Uint8Array([0, 0, 0, 1]);
+ MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
+ MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
+ };
+
+ MP4.box = function box(type) {
+ var payload = Array.prototype.slice.call(arguments, 1),
+ size = 8,
+ i = payload.length,
+ len = i,
+ result; // calculate the total size we need to allocate
+
+ while (i--) {
+ size += payload[i].byteLength;
+ }
+
+ result = new Uint8Array(size);
+ result[0] = size >> 24 & 0xff;
+ result[1] = size >> 16 & 0xff;
+ result[2] = size >> 8 & 0xff;
+ result[3] = size & 0xff;
+ result.set(type, 4); // copy the payload into the result
+
+ for (i = 0, size = 8; i < len; i++) {
+ // copy payload[i] array @ offset size
+ result.set(payload[i], size);
+ size += payload[i].byteLength;
+ }
+
+ return result;
+ };
+
+ MP4.hdlr = function hdlr(type) {
+ return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
+ };
+
+ MP4.mdat = function mdat(data) {
+ return MP4.box(MP4.types.mdat, data);
+ };
+
+ MP4.mdhd = function mdhd(timescale, duration) {
+ duration *= timescale;
+ var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
+ var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
+ return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
+ timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
+ upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined)
+ 0x00, 0x00]));
+ };
+
+ MP4.mdia = function mdia(track) {
+ return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
+ };
+
+ MP4.mfhd = function mfhd(sequenceNumber) {
+ return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
+ sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
+ ]));
+ };
+
+ MP4.minf = function minf(track) {
+ if (track.type === 'audio') {
+ return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
+ } else {
+ return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
+ }
+ };
+
+ MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
+ return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
+ }
+ /**
+ * @param tracks... (optional) {array} the tracks associated with this movie
+ */
+ ;
+
+ MP4.moov = function moov(tracks) {
+ var i = tracks.length,
+ boxes = [];
+
+ while (i--) {
+ boxes[i] = MP4.trak(tracks[i]);
+ }
+
+ return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
+ };
+
+ MP4.mvex = function mvex(tracks) {
+ var i = tracks.length,
+ boxes = [];
+
+ while (i--) {
+ boxes[i] = MP4.trex(tracks[i]);
+ }
+
+ return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
+ };
+
+ MP4.mvhd = function mvhd(timescale, duration) {
+ duration *= timescale;
+ var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
+ var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
+ var bytes = new Uint8Array([0x01, // version 1
+ 0x00, 0x00, 0x00, // flags
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
+ timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
+ upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
+ 0x01, 0x00, // 1.0 volume
+ 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
+ 0xff, 0xff, 0xff, 0xff // next_track_ID
+ ]);
+ return MP4.box(MP4.types.mvhd, bytes);
+ };
+
+ MP4.sdtp = function sdtp(track) {
+ var samples = track.samples || [],
+ bytes = new Uint8Array(4 + samples.length),
+ flags,
+ i; // leave the full box header (4 bytes) all zero
+ // write the sample table
+
+ for (i = 0; i < samples.length; i++) {
+ flags = samples[i].flags;
+ bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
+ }
+
+ return MP4.box(MP4.types.sdtp, bytes);
+ };
+
+ MP4.stbl = function stbl(track) {
+ return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
+ };
+
+ MP4.avc1 = function avc1(track) {
+ var sps = [],
+ pps = [],
+ i,
+ data,
+ len; // assemble the SPSs
+
+ for (i = 0; i < track.sps.length; i++) {
+ data = track.sps[i];
+ len = data.byteLength;
+ sps.push(len >>> 8 & 0xFF);
+ sps.push(len & 0xFF); // SPS
+
+ sps = sps.concat(Array.prototype.slice.call(data));
+ } // assemble the PPSs
+
+
+ for (i = 0; i < track.pps.length; i++) {
+ data = track.pps[i];
+ len = data.byteLength;
+ pps.push(len >>> 8 & 0xFF);
+ pps.push(len & 0xFF);
+ pps = pps.concat(Array.prototype.slice.call(data));
+ }
+
+ var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
+ sps[3], // profile
+ sps[4], // profile compat
+ sps[5], // level
+ 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
+ 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
+ ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
+ ]).concat(pps))),
+ // "PPS"
+ width = track.width,
+ height = track.height,
+ hSpacing = track.pixelRatio[0],
+ vSpacing = track.pixelRatio[1];
+ return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x01, // data_reference_index
+ 0x00, 0x00, // pre_defined
+ 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
+ width >> 8 & 0xFF, width & 0xff, // width
+ height >> 8 & 0xFF, height & 0xff, // height
+ 0x00, 0x48, 0x00, 0x00, // horizresolution
+ 0x00, 0x48, 0x00, 0x00, // vertresolution
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x01, // frame_count
+ 0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
+ 0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
+ 0x00, 0x18, // depth = 24
+ 0x11, 0x11]), // pre_defined = -1
+ avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
+ 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
+ 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
+ MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
+ hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
+ vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
+ };
+
+ MP4.esds = function esds(track) {
+ var configlen = track.config.length;
+ return new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ 0x03, // descriptor_type
+ 0x17 + configlen, // length
+ 0x00, 0x01, // es_id
+ 0x00, // stream_priority
+ 0x04, // descriptor_type
+ 0x0f + configlen, // length
+ 0x40, // codec : mpeg4_audio
+ 0x15, // stream_type
+ 0x00, 0x00, 0x00, // buffer_size
+ 0x00, 0x00, 0x00, 0x00, // maxBitrate
+ 0x00, 0x00, 0x00, 0x00, // avgBitrate
+ 0x05 // descriptor_type
+ ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
+ };
+
+ MP4.mp4a = function mp4a(track) {
+ var samplerate = track.samplerate;
+ return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x01, // data_reference_index
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, track.channelCount, // channelcount
+ 0x00, 0x10, // sampleSize:16bits
+ 0x00, 0x00, 0x00, 0x00, // reserved2
+ samplerate >> 8 & 0xFF, samplerate & 0xff, //
+ 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
+ };
+
+ MP4.mp3 = function mp3(track) {
+ var samplerate = track.samplerate;
+ return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x01, // data_reference_index
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, track.channelCount, // channelcount
+ 0x00, 0x10, // sampleSize:16bits
+ 0x00, 0x00, 0x00, 0x00, // reserved2
+ samplerate >> 8 & 0xFF, samplerate & 0xff, //
+ 0x00, 0x00]));
+ };
+
+ MP4.stsd = function stsd(track) {
+ if (track.type === 'audio') {
+ if (!track.isAAC && track.codec === 'mp3') {
+ return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
+ }
+
+ return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
+ } else {
+ return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
+ }
+ };
+
+ MP4.tkhd = function tkhd(track) {
+ var id = track.id,
+ duration = track.duration * track.timescale,
+ width = track.width,
+ height = track.height,
+ upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
+ lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
+ return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
+ 0x00, 0x00, 0x07, // flags
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
+ id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
+ 0x00, 0x00, 0x00, 0x00, // reserved
+ upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
+ 0x00, 0x00, // layer
+ 0x00, 0x00, // alternate_group
+ 0x00, 0x00, // non-audio track volume
+ 0x00, 0x00, // reserved
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
+ width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
+ height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
+ ]));
+ };
+
+ MP4.traf = function traf(track, baseMediaDecodeTime) {
+ var sampleDependencyTable = MP4.sdtp(track),
+ id = track.id,
+ upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
+ lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
+ return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF // track_ID
+ ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
+ 0x00, 0x00, 0x00, // flags
+ upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
+ 20 + // tfdt
+ 8 + // traf header
+ 16 + // mfhd
+ 8 + // moof header
+ 8), // mdat header
+ sampleDependencyTable);
+ }
+ /**
+ * Generate a track box.
+ * @param track {object} a track definition
+ * @return {Uint8Array} the track box
+ */
+ ;
+
+ MP4.trak = function trak(track) {
+ track.duration = track.duration || 0xffffffff;
+ return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
+ };
+
+ MP4.trex = function trex(track) {
+ var id = track.id;
+ return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
+ 0x00, 0x00, 0x00, // flags
+ id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
+ 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
+ 0x00, 0x00, 0x00, 0x00, // default_sample_duration
+ 0x00, 0x00, 0x00, 0x00, // default_sample_size
+ 0x00, 0x01, 0x00, 0x01 // default_sample_flags
+ ]));
+ };
+
+ MP4.trun = function trun(track, offset) {
+ var samples = track.samples || [],
+ len = samples.length,
+ arraylen = 12 + 16 * len,
+ array = new Uint8Array(arraylen),
+ i,
+ sample,
+ duration,
+ size,
+ flags,
+ cts;
+ offset += 8 + arraylen;
+ array.set([0x00, // version 0
+ 0x00, 0x0f, 0x01, // flags
+ len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
+ offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
+ ], 0);
+
+ for (i = 0; i < len; i++) {
+ sample = samples[i];
+ duration = sample.duration;
+ size = sample.size;
+ flags = sample.flags;
+ cts = sample.cts;
+ array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
+ size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
+ flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
+ cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
+ ], 12 + 16 * i);
+ }
+
+ return MP4.box(MP4.types.trun, array);
+ };
+
+ MP4.initSegment = function initSegment(tracks) {
+ if (!MP4.types) {
+ MP4.init();
+ }
+
+ var movie = MP4.moov(tracks),
+ result;
+ result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
+ result.set(MP4.FTYP);
+ result.set(movie, MP4.FTYP.byteLength);
+ return result;
+ };
+
+ return MP4;
+}();
+
+/* harmony default export */ var mp4_generator = (MP4);
+// CONCATENATED MODULE: ./src/utils/timescale-conversion.ts
+var MPEG_TS_CLOCK_FREQ_HZ = 90000;
+function toTimescaleFromScale(value, destScale, srcScale, round) {
+ if (srcScale === void 0) {
+ srcScale = 1;
+ }
+
+ if (round === void 0) {
+ round = false;
+ }
+
+ return toTimescaleFromBase(value, destScale, 1 / srcScale);
+}
+function toTimescaleFromBase(value, destScale, srcBase, round) {
+ if (srcBase === void 0) {
+ srcBase = 1;
+ }
+
+ if (round === void 0) {
+ round = false;
+ }
+
+ var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
+
+ return round ? Math.round(result) : result;
+}
+function toMsFromMpegTsClock(value, round) {
+ if (round === void 0) {
+ round = false;
+ }
+
+ return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
+}
+function toMpegTsClockFromTimescale(value, srcScale) {
+ if (srcScale === void 0) {
+ srcScale = 1;
+ }
+
+ return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
+}
+// CONCATENATED MODULE: ./src/remux/mp4-remuxer.js
+/**
+ * fMP4 remuxer
+*/
+
+
+
+
+
+
+var MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);
+var PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);
+var chromeVersion = null;
+
+var mp4_remuxer_MP4Remuxer = /*#__PURE__*/function () {
+ function MP4Remuxer(observer, config, typeSupported, vendor) {
+ this.observer = observer;
+ this.config = config;
+ this.typeSupported = typeSupported;
+ this.ISGenerated = false;
+
+ if (chromeVersion === null) {
+ var result = navigator.userAgent.match(/Chrome\/(\d+)/i);
+ chromeVersion = result ? parseInt(result[1]) : 0;
+ }
+ }
+
+ var _proto = MP4Remuxer.prototype;
+
+ _proto.destroy = function destroy() {};
+
+ _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
+ this._initPTS = this._initDTS = defaultTimeStamp;
+ };
+
+ _proto.resetInitSegment = function resetInitSegment() {
+ this.ISGenerated = false;
+ };
+
+ _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
+ var rolloverDetected = false;
+ var startPTS = videoSamples.reduce(function (minPTS, sample) {
+ var delta = sample.pts - minPTS;
+
+ if (delta < -4294967296) {
+ // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
+ rolloverDetected = true;
+ return PTSNormalize(minPTS, sample.pts);
+ } else if (delta > 0) {
+ return minPTS;
+ } else {
+ return sample.pts;
+ }
+ }, videoSamples[0].pts);
+
+ if (rolloverDetected) {
+ logger["logger"].debug('PTS rollover detected');
+ }
+
+ return startPTS;
+ };
+
+ _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
+ // generate Init Segment if needed
+ if (!this.ISGenerated) {
+ this.generateIS(audioTrack, videoTrack, timeOffset);
+ }
+
+ if (this.ISGenerated) {
+ var nbAudioSamples = audioTrack.samples.length;
+ var nbVideoSamples = videoTrack.samples.length;
+ var audioTimeOffset = timeOffset;
+ var videoTimeOffset = timeOffset;
+
+ if (nbAudioSamples && nbVideoSamples) {
+ // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
+ // if first audio DTS is not aligned with first video DTS then we need to take that into account
+ // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
+ // drift between audio and video streams
+ var startPTS = this.getVideoStartPts(videoTrack.samples);
+ var tsDelta = PTSNormalize(audioTrack.samples[0].pts, startPTS) - startPTS;
+ var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
+ audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
+ videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
+ } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
+ // calculated in remuxAudio.
+ // logger.log('nb AAC samples:' + audioTrack.samples.length);
+
+
+ if (nbAudioSamples) {
+ // if initSegment was generated without video samples, regenerate it again
+ if (!audioTrack.timescale) {
+ logger["logger"].warn('regenerate InitSegment as audio detected');
+ this.generateIS(audioTrack, videoTrack, timeOffset);
+ }
+
+ var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset); // logger.log('nb AVC samples:' + videoTrack.samples.length);
+
+ if (nbVideoSamples) {
+ var audioTrackLength;
+
+ if (audioData) {
+ audioTrackLength = audioData.endPTS - audioData.startPTS;
+ } // if initSegment was generated without video samples, regenerate it again
+
+
+ if (!videoTrack.timescale) {
+ logger["logger"].warn('regenerate InitSegment as video detected');
+ this.generateIS(audioTrack, videoTrack, timeOffset);
+ }
+
+ this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength);
+ }
+ } else {
+ // logger.log('nb AVC samples:' + videoTrack.samples.length);
+ if (nbVideoSamples) {
+ var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
+
+ if (videoData && audioTrack.codec) {
+ this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
+ }
+ }
+ }
+ } // logger.log('nb ID3 samples:' + audioTrack.samples.length);
+
+
+ if (id3Track.samples.length) {
+ this.remuxID3(id3Track, timeOffset);
+ } // logger.log('nb ID3 samples:' + audioTrack.samples.length);
+
+
+ if (textTrack.samples.length) {
+ this.remuxText(textTrack, timeOffset);
+ } // notify end of parsing
+
+
+ this.observer.trigger(events["default"].FRAG_PARSED);
+ };
+
+ _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
+ var observer = this.observer,
+ audioSamples = audioTrack.samples,
+ videoSamples = videoTrack.samples,
+ typeSupported = this.typeSupported,
+ container = 'audio/mp4',
+ tracks = {},
+ data = {
+ tracks: tracks
+ },
+ computePTSDTS = this._initPTS === undefined,
+ initPTS,
+ initDTS;
+
+ if (computePTSDTS) {
+ initPTS = initDTS = Infinity;
+ }
+
+ if (audioTrack.config && audioSamples.length) {
+ // let's use audio sampling rate as MP4 time scale.
+ // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
+ // using audio sampling rate here helps having an integer MP4 frame duration
+ // this avoids potential rounding issue and AV sync issue
+ audioTrack.timescale = audioTrack.samplerate;
+ logger["logger"].log("audio sampling rate : " + audioTrack.samplerate);
+
+ if (!audioTrack.isAAC) {
+ if (typeSupported.mpeg) {
+ // Chrome and Safari
+ container = 'audio/mpeg';
+ audioTrack.codec = '';
+ } else if (typeSupported.mp3) {
+ // Firefox
+ audioTrack.codec = 'mp3';
+ }
+ }
+
+ tracks.audio = {
+ container: container,
+ codec: audioTrack.codec,
+ initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]),
+ metadata: {
+ channelCount: audioTrack.channelCount
+ }
+ };
+
+ if (computePTSDTS) {
+ // remember first PTS of this demuxing context. for audio, PTS = DTS
+ initPTS = initDTS = audioSamples[0].pts - Math.round(audioTrack.inputTimeScale * timeOffset);
+ }
+ }
+
+ if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
+ // let's use input time scale as MP4 video timescale
+ // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
+ var inputTimeScale = videoTrack.inputTimeScale;
+ videoTrack.timescale = inputTimeScale;
+ tracks.video = {
+ container: 'video/mp4',
+ codec: videoTrack.codec,
+ initSegment: mp4_generator.initSegment([videoTrack]),
+ metadata: {
+ width: videoTrack.width,
+ height: videoTrack.height
+ }
+ };
+
+ if (computePTSDTS) {
+ var startPTS = this.getVideoStartPts(videoSamples);
+ var startOffset = Math.round(inputTimeScale * timeOffset);
+ initDTS = Math.min(initDTS, PTSNormalize(videoSamples[0].dts, startPTS) - startOffset);
+ initPTS = Math.min(initPTS, startPTS - startOffset);
+ this.observer.trigger(events["default"].INIT_PTS_FOUND, {
+ initPTS: initPTS
+ });
+ }
+ } else if (computePTSDTS && tracks.audio) {
+ // initPTS found for audio-only stream with main and alt audio
+ this.observer.trigger(events["default"].INIT_PTS_FOUND, {
+ initPTS: initPTS
+ });
+ }
+
+ if (Object.keys(tracks).length) {
+ observer.trigger(events["default"].FRAG_PARSING_INIT_SEGMENT, data);
+ this.ISGenerated = true;
+
+ if (computePTSDTS) {
+ this._initPTS = initPTS;
+ this._initDTS = initDTS;
+ }
+ } else {
+ observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
+ fatal: false,
+ reason: 'no audio/video samples found'
+ });
+ }
+ };
+
+ _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
+ var timeScale = track.timescale;
+ var inputSamples = track.samples;
+ var outputSamples = [];
+ var nbSamples = inputSamples.length;
+ var initPTS = this._initPTS;
+ var offset = 8;
+ var mp4SampleDuration;
+ var mdat;
+ var moof;
+ var firstDTS;
+ var lastDTS;
+ var minPTS = Number.POSITIVE_INFINITY;
+ var maxPTS = Number.NEGATIVE_INFINITY;
+ var ptsDtsShift = 0;
+ var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
+
+ var nextAvcDts = this.nextAvcDts;
+
+ if (nbSamples === 0) {
+ return;
+ }
+
+ if (!contiguous) {
+ var pts = timeOffset * timeScale;
+ var cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
+
+ nextAvcDts = pts - cts;
+ } // PTS is coded on 33bits, and can loop from -2^32 to 2^32
+ // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
+
+
+ for (var i = 0; i < nbSamples; i++) {
+ var sample = inputSamples[i];
+ sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);
+ sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);
+
+ if (sample.dts > sample.pts) {
+ ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
+ }
+
+ if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
+ sortSamples = true;
+ }
+ } // sort video samples by DTS then PTS then demux id order
+
+
+ if (sortSamples) {
+ inputSamples.sort(function (a, b) {
+ var deltadts = a.dts - b.dts;
+ var deltapts = a.pts - b.pts;
+ return deltadts || deltapts || a.id - b.id;
+ });
+ } // Get first/last DTS
+
+
+ firstDTS = inputSamples[0].dts;
+ lastDTS = inputSamples[nbSamples - 1].dts; // on Safari let's signal the same sample duration for all samples
+ // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
+ // set this constant duration as being the avg delta between consecutive DTS.
+
+ var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
+
+ if (ptsDtsShift < 0) {
+ if (ptsDtsShift < averageSampleDuration * -2) {
+ // Fix for "CNN special report, with CC" in test-streams (including Safari browser)
+ // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
+ logger["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + toMsFromMpegTsClock(-averageSampleDuration, true) + " ms");
+ var lastDts = ptsDtsShift;
+
+ for (var _i = 0; _i < nbSamples; _i++) {
+ inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
+ inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
+ }
+ } else {
+ // Fix for "Custom IV with bad PTS DTS" in test-streams
+ // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
+ logger["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + toMsFromMpegTsClock(ptsDtsShift, true) + " ms to overcome this issue");
+
+ for (var _i2 = 0; _i2 < nbSamples; _i2++) {
+ inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
+ }
+ }
+
+ firstDTS = inputSamples[0].dts;
+ lastDTS = inputSamples[nbSamples - 1].dts;
+ } // if fragment are contiguous, detect hole/overlapping between fragments
+
+
+ if (contiguous) {
+ // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
+ var delta = firstDTS - nextAvcDts;
+ var foundHole = delta > averageSampleDuration;
+ var foundOverlap = delta < -1;
+
+ if (foundHole || foundOverlap) {
+ if (foundHole) {
+ logger["logger"].warn("AVC: " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
+ } else {
+ logger["logger"].warn("AVC: " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
+ }
+
+ firstDTS = nextAvcDts;
+ var firstPTS = inputSamples[0].pts - delta;
+ inputSamples[0].dts = firstDTS;
+ inputSamples[0].pts = firstPTS;
+ logger["logger"].log("Video: First PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
+ }
+ }
+
+ if (chromeVersion && chromeVersion < 75) {
+ firstDTS = Math.max(0, firstDTS);
+ }
+
+ var nbNalu = 0;
+ var naluLen = 0;
+
+ for (var _i3 = 0; _i3 < nbSamples; _i3++) {
+ // compute total/avc sample length and nb of NAL units
+ var _sample = inputSamples[_i3];
+ var units = _sample.units;
+ var nbUnits = units.length;
+ var sampleLen = 0;
+
+ for (var j = 0; j < nbUnits; j++) {
+ sampleLen += units[j].data.length;
+ }
+
+ naluLen += sampleLen;
+ nbNalu += nbUnits;
+ _sample.length = sampleLen; // normalize PTS/DTS
+ // ensure sample monotonic DTS
+
+ _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
+
+ _sample.pts = Math.max(_sample.pts, _sample.dts, 0);
+ minPTS = Math.min(_sample.pts, minPTS);
+ maxPTS = Math.max(_sample.pts, maxPTS);
+ }
+
+ lastDTS = inputSamples[nbSamples - 1].dts;
+ /* concatenate the video data and construct the mdat in place
+ (need 8 more bytes to fill length and mpdat type) */
+
+ var mdatSize = naluLen + 4 * nbNalu + 8;
+
+ try {
+ mdat = new Uint8Array(mdatSize);
+ } catch (err) {
+ this.observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MUX_ERROR,
+ details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
+ fatal: false,
+ bytes: mdatSize,
+ reason: "fail allocating video mdat " + mdatSize
+ });
+ return;
+ }
+
+ var view = new DataView(mdat.buffer);
+ view.setUint32(0, mdatSize);
+ mdat.set(mp4_generator.types.mdat, 4);
+
+ for (var _i4 = 0; _i4 < nbSamples; _i4++) {
+ var avcSample = inputSamples[_i4];
+ var avcSampleUnits = avcSample.units;
+ var mp4SampleLength = 0;
+ var compositionTimeOffset = void 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
+
+ for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
+ var unit = avcSampleUnits[_j];
+ var unitData = unit.data;
+ var unitDataLen = unit.data.byteLength;
+ view.setUint32(offset, unitDataLen);
+ offset += 4;
+ mdat.set(unitData, offset);
+ offset += unitDataLen;
+ mp4SampleLength += 4 + unitDataLen;
+ } // expected sample duration is the Decoding Timestamp diff of consecutive samples
+
+
+ if (_i4 < nbSamples - 1) {
+ mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
+ } else {
+ var config = this.config;
+ var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
+
+ if (config.stretchShortVideoTrack) {
+ // In some cases, a segment's audio track duration may exceed the video track duration.
+ // Since we've already remuxed audio, and we know how long the audio track is, we look to
+ // see if the delta to the next segment is longer than maxBufferHole.
+ // If so, playback would potentially get stuck, so we artificially inflate
+ // the duration of the last frame to minimize any potential gap between segments.
+ var maxBufferHole = config.maxBufferHole;
+ var gapTolerance = Math.floor(maxBufferHole * timeScale);
+ var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
+
+ if (deltaToFrameEnd > gapTolerance) {
+ // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
+ // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
+ mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
+
+ if (mp4SampleDuration < 0) {
+ mp4SampleDuration = lastFrameDuration;
+ }
+
+ logger["logger"].log("It is approximately " + toMsFromMpegTsClock(deltaToFrameEnd, false) + " ms to the next segment; using duration " + toMsFromMpegTsClock(mp4SampleDuration, false) + " ms for the last video frame.");
+ } else {
+ mp4SampleDuration = lastFrameDuration;
+ }
+ } else {
+ mp4SampleDuration = lastFrameDuration;
+ }
+ }
+
+ compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
+
+ outputSamples.push({
+ size: mp4SampleLength,
+ // constant duration
+ duration: mp4SampleDuration,
+ cts: compositionTimeOffset,
+ flags: {
+ isLeading: 0,
+ isDependedOn: 0,
+ hasRedundancy: 0,
+ degradPrio: 0,
+ dependsOn: avcSample.key ? 2 : 1,
+ isNonSync: avcSample.key ? 0 : 1
+ }
+ });
+ } // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
+
+
+ this.nextAvcDts = lastDTS + mp4SampleDuration;
+ var dropped = track.dropped;
+ track.nbNalu = 0;
+ track.dropped = 0;
+
+ if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
+ var flags = outputSamples[0].flags; // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
+ // https://code.google.com/p/chromium/issues/detail?id=229412
+
+ flags.dependsOn = 2;
+ flags.isNonSync = 0;
+ }
+
+ track.samples = outputSamples;
+ moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track);
+ track.samples = [];
+ var data = {
+ data1: moof,
+ data2: mdat,
+ startPTS: minPTS / timeScale,
+ endPTS: (maxPTS + mp4SampleDuration) / timeScale,
+ startDTS: firstDTS / timeScale,
+ endDTS: this.nextAvcDts / timeScale,
+ type: 'video',
+ hasAudio: false,
+ hasVideo: true,
+ nb: outputSamples.length,
+ dropped: dropped
+ };
+ this.observer.trigger(events["default"].FRAG_PARSING_DATA, data);
+ return data;
+ };
+
+ _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
+ var inputTimeScale = track.inputTimeScale;
+ var mp4timeScale = track.timescale;
+ var scaleFactor = inputTimeScale / mp4timeScale;
+ var mp4SampleDuration = track.isAAC ? 1024 : 1152;
+ var inputSampleDuration = mp4SampleDuration * scaleFactor;
+ var initPTS = this._initPTS;
+ var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
+ var mp4Sample;
+ var fillFrame;
+ var mdat;
+ var moof;
+ var firstPTS;
+ var lastPTS;
+ var offset = rawMPEG ? 0 : 8;
+ var inputSamples = track.samples;
+ var outputSamples = [];
+ var nextAudioPts = this.nextAudioPts; // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
+ // for sake of clarity:
+ // consecutive fragments are frags with
+ // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
+ // - less than 20 audio frames distance
+ // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
+ // this helps ensuring audio continuity
+ // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
+
+ contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration); // compute normalized PTS
+
+ inputSamples.forEach(function (sample) {
+ sample.pts = sample.dts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
+ }); // filter out sample with negative PTS that are not playable anyway
+ // if we don't remove these negative samples, they will shift all audio samples forward.
+ // leading to audio overlap between current / next fragment
+
+ inputSamples = inputSamples.filter(function (sample) {
+ return sample.pts >= 0;
+ }); // in case all samples have negative PTS, and have been filtered out, return now
+
+ if (inputSamples.length === 0) {
+ return;
+ }
+
+ if (!contiguous) {
+ if (!accurateTimeOffset) {
+ // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
+ nextAudioPts = inputSamples[0].pts;
+ } else {
+ // if timeOffset is accurate, let's use it as predicted next audio PTS
+ nextAudioPts = Math.max(0, timeOffset * inputTimeScale);
+ }
+ } // If the audio track is missing samples, the frames seem to get "left-shifted" within the
+ // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
+ // In an effort to prevent this from happening, we inject frames here where there are gaps.
+ // When possible, we inject a silent frame; when that's not possible, we duplicate the last
+ // frame.
+
+
+ if (track.isAAC) {
+ var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
+
+ for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
+ // First, let's see how far off this frame is from where we expect it to be
+ var sample = inputSamples[i];
+ var pts = sample.pts;
+ var delta = pts - nextPts; // If we're overlapping by more than a duration, drop this sample
+
+ if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
+ if (contiguous || i > 0) {
+ logger["logger"].warn("Dropping 1 audio frame @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms overlap.");
+ inputSamples.splice(i, 1); // Don't touch nextPtsNorm or i
+ } else {
+ // When changing qualities we can't trust that audio has been appended up to nextAudioPts
+ // Warn about the overlap but do not drop samples as that can introduce buffer gaps
+ logger["logger"].warn("Audio frame @ " + toMsFromMpegTsClock(pts, true) / 1000 + "s overlaps nextAudioPts by " + toMsFromMpegTsClock(delta, true) + " ms.");
+ nextPts = pts + inputSampleDuration;
+ i++;
+ }
+ } // eslint-disable-line brace-style
+ // Insert missing frames if:
+ // 1: We're more than maxAudioFramesDrift frame away
+ // 2: Not more than MAX_SILENT_FRAME_DURATION away
+ // 3: currentTime (aka nextPtsNorm) is not 0
+ else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ && nextPts) {
+ var missing = Math.round(delta / inputSampleDuration);
+ logger["logger"].warn("Injecting " + missing + " audio frames @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms gap.");
+
+ for (var j = 0; j < missing; j++) {
+ var newStamp = Math.max(nextPts, 0);
+ fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
+
+ if (!fillFrame) {
+ logger["logger"].log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
+ fillFrame = sample.unit.subarray();
+ }
+
+ inputSamples.splice(i, 0, {
+ unit: fillFrame,
+ pts: newStamp,
+ dts: newStamp
+ });
+ nextPts += inputSampleDuration;
+ i++;
+ } // Adjust sample to next expected pts
+
+
+ sample.pts = sample.dts = nextPts;
+ nextPts += inputSampleDuration;
+ i++;
+ } else {
+ // Otherwise, just adjust pts
+ if (Math.abs(delta) > 0.1 * inputSampleDuration) {// logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
+ }
+
+ sample.pts = sample.dts = nextPts;
+ nextPts += inputSampleDuration;
+ i++;
+ }
+ }
+ } // compute mdat size, as we eventually filtered/added some samples
+
+
+ var nbSamples = inputSamples.length;
+ var mdatSize = 0;
+
+ while (nbSamples--) {
+ mdatSize += inputSamples[nbSamples].unit.byteLength;
+ }
+
+ for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
+ var audioSample = inputSamples[_j2];
+ var unit = audioSample.unit;
+ var _pts = audioSample.pts; // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);
+ // if not first sample
+
+ if (lastPTS !== undefined && mp4Sample) {
+ mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
+ } else {
+ var _delta = _pts - nextAudioPts;
+
+ var numMissingFrames = 0; // if fragment are contiguous, detect hole/overlapping between fragments
+ // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
+
+ if (contiguous && track.isAAC) {
+ // log delta
+ if (_delta) {
+ if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION_90KHZ) {
+ // Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,
+ // and if not, shouldn't we actually Math.ceil() instead?
+ numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
+ logger["logger"].log(toMsFromMpegTsClock(_delta, true) + " ms hole between AAC samples detected,filling it");
+
+ if (numMissingFrames > 0) {
+ fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
+
+ if (!fillFrame) {
+ fillFrame = unit.subarray();
+ }
+
+ mdatSize += numMissingFrames * fillFrame.length;
+ } // if we have frame overlap, overlapping for more than half a frame duraion
+
+ } else if (_delta < -12) {
+ // drop overlapping audio frames... browser will deal with it
+ logger["logger"].log("drop overlapping AAC sample, expected/parsed/delta: " + toMsFromMpegTsClock(nextAudioPts, true) + " ms / " + toMsFromMpegTsClock(_pts, true) + " ms / " + toMsFromMpegTsClock(-_delta, true) + " ms");
+ mdatSize -= unit.byteLength;
+ continue;
+ } // set PTS/DTS to expected PTS/DTS
+
+
+ _pts = nextAudioPts;
+ }
+ } // remember first PTS of our audioSamples
+
+
+ firstPTS = _pts;
+
+ if (mdatSize > 0) {
+ mdatSize += offset;
+
+ try {
+ mdat = new Uint8Array(mdatSize);
+ } catch (err) {
+ this.observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MUX_ERROR,
+ details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
+ fatal: false,
+ bytes: mdatSize,
+ reason: "fail allocating audio mdat " + mdatSize
+ });
+ return;
+ }
+
+ if (!rawMPEG) {
+ var view = new DataView(mdat.buffer);
+ view.setUint32(0, mdatSize);
+ mdat.set(mp4_generator.types.mdat, 4);
+ }
+ } else {
+ // no audio samples
+ return;
+ }
+
+ for (var _i5 = 0; _i5 < numMissingFrames; _i5++) {
+ fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
+
+ if (!fillFrame) {
+ logger["logger"].log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
+ fillFrame = unit.subarray();
+ }
+
+ mdat.set(fillFrame, offset);
+ offset += fillFrame.byteLength;
+ mp4Sample = {
+ size: fillFrame.byteLength,
+ cts: 0,
+ duration: 1024,
+ flags: {
+ isLeading: 0,
+ isDependedOn: 0,
+ hasRedundancy: 0,
+ degradPrio: 0,
+ dependsOn: 1
+ }
+ };
+ outputSamples.push(mp4Sample);
+ }
+ }
+
+ mdat.set(unit, offset);
+ var unitLen = unit.byteLength;
+ offset += unitLen; // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
+
+ mp4Sample = {
+ size: unitLen,
+ cts: 0,
+ duration: 0,
+ flags: {
+ isLeading: 0,
+ isDependedOn: 0,
+ hasRedundancy: 0,
+ degradPrio: 0,
+ dependsOn: 1
+ }
+ };
+ outputSamples.push(mp4Sample);
+ lastPTS = _pts;
+ }
+
+ var lastSampleDuration = 0;
+ nbSamples = outputSamples.length; // set last sample duration as being identical to previous sample
+
+ if (nbSamples >= 2) {
+ lastSampleDuration = outputSamples[nbSamples - 2].duration;
+ mp4Sample.duration = lastSampleDuration;
+ }
+
+ if (nbSamples) {
+ // next audio sample PTS should be equal to last sample PTS + duration
+ this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration; // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
+
+ track.samples = outputSamples;
+
+ if (rawMPEG) {
+ moof = new Uint8Array();
+ } else {
+ moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
+ }
+
+ track.samples = [];
+ var start = firstPTS / inputTimeScale;
+ var end = nextAudioPts / inputTimeScale;
+ var audioData = {
+ data1: moof,
+ data2: mdat,
+ startPTS: start,
+ endPTS: end,
+ startDTS: start,
+ endDTS: end,
+ type: 'audio',
+ hasAudio: true,
+ hasVideo: false,
+ nb: nbSamples
+ };
+ this.observer.trigger(events["default"].FRAG_PARSING_DATA, audioData);
+ return audioData;
+ }
+
+ return null;
+ };
+
+ _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
+ var inputTimeScale = track.inputTimeScale;
+ var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
+ var scaleFactor = inputTimeScale / mp4timeScale;
+ var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
+
+ var startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
+ var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
+
+ var sampleDuration = 1024;
+ var frameDuration = scaleFactor * sampleDuration; // samples count of this segment's duration
+
+ var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
+
+ var silentFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
+ logger["logger"].warn('remux empty Audio'); // Can't remux if we can't generate a silent frame...
+
+ if (!silentFrame) {
+ logger["logger"].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
+ return;
+ }
+
+ var samples = [];
+
+ for (var i = 0; i < nbSamples; i++) {
+ var stamp = startDTS + i * frameDuration;
+ samples.push({
+ unit: silentFrame,
+ pts: stamp,
+ dts: stamp
+ });
+ }
+
+ track.samples = samples;
+ this.remuxAudio(track, timeOffset, contiguous);
+ };
+
+ _proto.remuxID3 = function remuxID3(track, timeOffset) {
+ var length = track.samples.length;
+
+ if (!length) {
+ return;
+ }
+
+ var inputTimeScale = track.inputTimeScale;
+ var initPTS = this._initPTS;
+ var initDTS = this._initDTS; // consume samples
+
+ for (var index = 0; index < length; index++) {
+ var sample = track.samples[index]; // setting id3 pts, dts to relative time
+ // using this._initPTS and this._initDTS to calculate relative time
+
+ sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
+ sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
+ }
+
+ this.observer.trigger(events["default"].FRAG_PARSING_METADATA, {
+ samples: track.samples
+ });
+ track.samples = [];
+ };
+
+ _proto.remuxText = function remuxText(track, timeOffset) {
+ var length = track.samples.length;
+ var inputTimeScale = track.inputTimeScale;
+ var initPTS = this._initPTS; // consume samples
+
+ if (length) {
+ for (var index = 0; index < length; index++) {
+ var sample = track.samples[index]; // setting text pts, dts to relative time
+ // using this._initPTS and this._initDTS to calculate relative time
+
+ sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
+ }
+
+ track.samples.sort(function (a, b) {
+ return a.pts - b.pts;
+ });
+ this.observer.trigger(events["default"].FRAG_PARSING_USERDATA, {
+ samples: track.samples
+ });
+ }
+
+ track.samples = [];
+ };
+
+ return MP4Remuxer;
+}();
+
+function PTSNormalize(value, reference) {
+ var offset;
+
+ if (reference === undefined) {
+ return value;
+ }
+
+ if (reference < value) {
+ // - 2^33
+ offset = -8589934592;
+ } else {
+ // + 2^33
+ offset = 8589934592;
+ }
+ /* PTS is 33bit (from 0 to 2^33 -1)
+ if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
+ PTS looping occured. fill the gap */
+
+
+ while (Math.abs(value - reference) > 4294967296) {
+ value += offset;
+ }
+
+ return value;
+}
+
+/* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer);
+// CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js
+/**
+ * passthrough remuxer
+*/
+
+
+var passthrough_remuxer_PassThroughRemuxer = /*#__PURE__*/function () {
+ function PassThroughRemuxer(observer) {
+ this.observer = observer;
+ }
+
+ var _proto = PassThroughRemuxer.prototype;
+
+ _proto.destroy = function destroy() {};
+
+ _proto.resetTimeStamp = function resetTimeStamp() {};
+
+ _proto.resetInitSegment = function resetInitSegment() {};
+
+ _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
+ var observer = this.observer;
+ var streamType = '';
+
+ if (audioTrack) {
+ streamType += 'audio';
+ }
+
+ if (videoTrack) {
+ streamType += 'video';
+ }
+
+ observer.trigger(events["default"].FRAG_PARSING_DATA, {
+ data1: rawData,
+ startPTS: timeOffset,
+ startDTS: timeOffset,
+ type: streamType,
+ hasAudio: !!audioTrack,
+ hasVideo: !!videoTrack,
+ nb: 1,
+ dropped: 0
+ }); // notify end of parsing
+
+ observer.trigger(events["default"].FRAG_PARSED);
+ };
+
+ return PassThroughRemuxer;
+}();
+
+/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
+// CONCATENATED MODULE: ./src/demux/demuxer-inline.js
+/**
+ *
+ * inline demuxer: probe fragments and instantiate
+ * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
+ *
+ */
+
+
+
+
+
+
+
+
+
+
+ // see https://stackoverflow.com/a/11237259/589493
+
+var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
+
+var now; // performance.now() not available on WebWorker, at least on Safari Desktop
+
+try {
+ now = global.performance.now.bind(global.performance);
+} catch (err) {
+ logger["logger"].debug('Unable to use Performance API on this environment');
+ now = global.Date.now;
+}
+
+var demuxer_inline_DemuxerInline = /*#__PURE__*/function () {
+ function DemuxerInline(observer, typeSupported, config, vendor) {
+ this.observer = observer;
+ this.typeSupported = typeSupported;
+ this.config = config;
+ this.vendor = vendor;
+ }
+
+ var _proto = DemuxerInline.prototype;
+
+ _proto.destroy = function destroy() {
+ var demuxer = this.demuxer;
+
+ if (demuxer) {
+ demuxer.destroy();
+ }
+ };
+
+ _proto.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
+ var _this = this;
+
+ if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
+ var decrypter = this.decrypter;
+
+ if (decrypter == null) {
+ decrypter = this.decrypter = new crypt_decrypter["default"](this.observer, this.config);
+ }
+
+ var startTime = now();
+ decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
+ var endTime = now();
+
+ _this.observer.trigger(events["default"].FRAG_DECRYPTED, {
+ stats: {
+ tstart: startTime,
+ tdecrypt: endTime
+ }
+ });
+
+ _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
+ });
+ } else {
+ this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
+ }
+ };
+
+ _proto.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
+ var demuxer = this.demuxer;
+ var remuxer = this.remuxer;
+
+ if (!demuxer || // in case of continuity change, or track switch
+ // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
+ discontinuity || trackSwitch) {
+ var observer = this.observer;
+ var typeSupported = this.typeSupported;
+ var config = this.config; // probing order is TS/MP4/AAC/MP3
+
+ var muxConfig = [{
+ demux: tsdemuxer,
+ remux: mp4_remuxer
+ }, {
+ demux: mp4demuxer["default"],
+ remux: passthrough_remuxer
+ }, {
+ demux: aacdemuxer,
+ remux: mp4_remuxer
+ }, {
+ demux: mp3demuxer,
+ remux: mp4_remuxer
+ }]; // probe for content type
+
+ var mux;
+
+ for (var i = 0, len = muxConfig.length; i < len; i++) {
+ mux = muxConfig[i];
+
+ if (mux.demux.probe(data)) {
+ break;
+ }
+ }
+
+ if (!mux) {
+ observer.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
+ fatal: true,
+ reason: 'no demux matching with content found'
+ });
+ return;
+ } // so let's check that current remuxer and demuxer are still valid
+
+
+ if (!remuxer || !(remuxer instanceof mux.remux)) {
+ remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
+ }
+
+ if (!demuxer || !(demuxer instanceof mux.demux)) {
+ demuxer = new mux.demux(observer, remuxer, config, typeSupported);
+ this.probe = mux.demux.probe;
+ }
+
+ this.demuxer = demuxer;
+ this.remuxer = remuxer;
+ }
+
+ if (discontinuity || trackSwitch) {
+ demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
+ remuxer.resetInitSegment();
+ }
+
+ if (discontinuity) {
+ demuxer.resetTimeStamp(defaultInitPTS);
+ remuxer.resetTimeStamp(defaultInitPTS);
+ }
+
+ if (typeof demuxer.setDecryptData === 'function') {
+ demuxer.setDecryptData(decryptdata);
+ }
+
+ demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
+ };
+
+ return DemuxerInline;
+}();
+
+/* harmony default export */ var demuxer_inline = __webpack_exports__["default"] = (demuxer_inline_DemuxerInline);
+
+/***/ }),
+
+/***/ "./src/demux/demuxer-worker.js":
+/*!*************************************!*\
+ !*** ./src/demux/demuxer-worker.js ***!
+ \*************************************/
+/*! exports provided: default */
+/*! ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./src/demux/demuxer.js (referenced with require.resolve) */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/demuxer-inline */ "./src/demux/demuxer-inline.js");
+/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
+/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
+/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
+/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
+/* demuxer web worker.
+ * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
+ * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
+ */
+
+
+
+
+
+var DemuxerWorker = function DemuxerWorker(self) {
+ // observer setup
+ var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
+
+ observer.trigger = function trigger(event) {
+ for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ data[_key - 1] = arguments[_key];
+ }
+
+ observer.emit.apply(observer, [event, event].concat(data));
+ };
+
+ observer.off = function off(event) {
+ for (var _len2 = arguments.length, data = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ data[_key2 - 1] = arguments[_key2];
+ }
+
+ observer.removeListener.apply(observer, [event].concat(data));
+ };
+
+ var forwardMessage = function forwardMessage(ev, data) {
+ self.postMessage({
+ event: ev,
+ data: data
+ });
+ };
+
+ self.addEventListener('message', function (ev) {
+ var data = ev.data; // console.log('demuxer cmd:' + data.cmd);
+
+ switch (data.cmd) {
+ case 'init':
+ var config = JSON.parse(data.config);
+ self.demuxer = new _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor);
+ Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug); // signal end of worker init
+
+ forwardMessage('init', null);
+ break;
+
+ case 'demux':
+ self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);
+ break;
+
+ default:
+ break;
+ }
+ }); // forward events to main thread
+
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_DECRYPTED, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSED, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].ERROR, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_METADATA, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_USERDATA, forwardMessage);
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, forwardMessage); // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
+
+ observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_DATA, function (ev, data) {
+ var transferable = [];
+ var message = {
+ event: ev,
+ data: data
+ };
+
+ if (data.data1) {
+ message.data1 = data.data1.buffer;
+ transferable.push(data.data1.buffer);
+ delete data.data1;
+ }
+
+ if (data.data2) {
+ message.data2 = data.data2.buffer;
+ transferable.push(data.data2.buffer);
+ delete data.data2;
+ }
+
+ self.postMessage(message, transferable);
+ });
+};
+
+/* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker);
+
+/***/ }),
+
+/***/ "./src/demux/id3.js":
+/*!**************************!*\
+ !*** ./src/demux/id3.js ***!
+ \**************************/
+/*! exports provided: default, utf8ArrayToStr */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
+/* harmony import */ var _utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
+
+/**
+ * ID3 parser
+ */
+
+var ID3 = /*#__PURE__*/function () {
+ function ID3() {}
+
+ /**
+ * Returns true if an ID3 header can be found at offset in data
+ * @param {Uint8Array} data - The data to search in
+ * @param {number} offset - The offset at which to start searching
+ * @return {boolean} - True if an ID3 header is found
+ */
+ ID3.isHeader = function isHeader(data, offset) {
+ /*
+ * http://id3.org/id3v2.3.0
+ * [0] = 'I'
+ * [1] = 'D'
+ * [2] = '3'
+ * [3,4] = {Version}
+ * [5] = {Flags}
+ * [6-9] = {ID3 Size}
+ *
+ * An ID3v2 tag can be detected with the following pattern:
+ * $49 44 33 yy yy xx zz zz zz zz
+ * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
+ */
+ if (offset + 10 <= data.length) {
+ // look for 'ID3' identifier
+ if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
+ // check version is within range
+ if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
+ // check size is within range
+ if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+ /**
+ * Returns true if an ID3 footer can be found at offset in data
+ * @param {Uint8Array} data - The data to search in
+ * @param {number} offset - The offset at which to start searching
+ * @return {boolean} - True if an ID3 footer is found
+ */
+ ;
+
+ ID3.isFooter = function isFooter(data, offset) {
+ /*
+ * The footer is a copy of the header, but with a different identifier
+ */
+ if (offset + 10 <= data.length) {
+ // look for '3DI' identifier
+ if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
+ // check version is within range
+ if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
+ // check size is within range
+ if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+ /**
+ * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
+ * @param {Uint8Array} data - The data to search in
+ * @param {number} offset - The offset at which to start searching
+ * @return {Uint8Array} - The block of data containing any ID3 tags found
+ */
+ ;
+
+ ID3.getID3Data = function getID3Data(data, offset) {
+ var front = offset;
+ var length = 0;
+
+ while (ID3.isHeader(data, offset)) {
+ // ID3 header is 10 bytes
+ length += 10;
+
+ var size = ID3._readSize(data, offset + 6);
+
+ length += size;
+
+ if (ID3.isFooter(data, offset + 10)) {
+ // ID3 footer is 10 bytes
+ length += 10;
+ }
+
+ offset += length;
+ }
+
+ if (length > 0) {
+ return data.subarray(front, front + length);
+ }
+
+ return undefined;
+ };
+
+ ID3._readSize = function _readSize(data, offset) {
+ var size = 0;
+ size = (data[offset] & 0x7f) << 21;
+ size |= (data[offset + 1] & 0x7f) << 14;
+ size |= (data[offset + 2] & 0x7f) << 7;
+ size |= data[offset + 3] & 0x7f;
+ return size;
+ }
+ /**
+ * Searches for the Elementary Stream timestamp found in the ID3 data chunk
+ * @param {Uint8Array} data - Block of data containing one or more ID3 tags
+ * @return {number} - The timestamp
+ */
+ ;
+
+ ID3.getTimeStamp = function getTimeStamp(data) {
+ var frames = ID3.getID3Frames(data);
+
+ for (var i = 0; i < frames.length; i++) {
+ var frame = frames[i];
+
+ if (ID3.isTimeStampFrame(frame)) {
+ return ID3._readTimeStamp(frame);
+ }
+ }
+
+ return undefined;
+ }
+ /**
+ * Returns true if the ID3 frame is an Elementary Stream timestamp frame
+ * @param {ID3 frame} frame
+ */
+ ;
+
+ ID3.isTimeStampFrame = function isTimeStampFrame(frame) {
+ return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
+ };
+
+ ID3._getFrameData = function _getFrameData(data) {
+ /*
+ Frame ID $xx xx xx xx (four characters)
+ Size $xx xx xx xx
+ Flags $xx xx
+ */
+ var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
+
+ var size = ID3._readSize(data, 4); // skip frame id, size, and flags
+
+
+ var offset = 10;
+ return {
+ type: type,
+ size: size,
+ data: data.subarray(offset, offset + size)
+ };
+ }
+ /**
+ * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
+ * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
+ * @return {ID3 frame[]} - Array of ID3 frame objects
+ */
+ ;
+
+ ID3.getID3Frames = function getID3Frames(id3Data) {
+ var offset = 0;
+ var frames = [];
+
+ while (ID3.isHeader(id3Data, offset)) {
+ var size = ID3._readSize(id3Data, offset + 6); // skip past ID3 header
+
+
+ offset += 10;
+ var end = offset + size; // loop through frames in the ID3 tag
+
+ while (offset + 8 < end) {
+ var frameData = ID3._getFrameData(id3Data.subarray(offset));
+
+ var frame = ID3._decodeFrame(frameData);
+
+ if (frame) {
+ frames.push(frame);
+ } // skip frame header and frame data
+
+
+ offset += frameData.size + 10;
+ }
+
+ if (ID3.isFooter(id3Data, offset)) {
+ offset += 10;
+ }
+ }
+
+ return frames;
+ };
+
+ ID3._decodeFrame = function _decodeFrame(frame) {
+ if (frame.type === 'PRIV') {
+ return ID3._decodePrivFrame(frame);
+ } else if (frame.type[0] === 'W') {
+ return ID3._decodeURLFrame(frame);
+ }
+
+ return ID3._decodeTextFrame(frame);
+ };
+
+ ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {
+ if (timeStampFrame.data.byteLength === 8) {
+ var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
+ // with the upper 31 bits set to zero.
+
+ var pts33Bit = data[3] & 0x1;
+ var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
+ timestamp /= 45;
+
+ if (pts33Bit) {
+ timestamp += 47721858.84;
+ } // 2^32 / 90
+
+
+ return Math.round(timestamp);
+ }
+
+ return undefined;
+ };
+
+ ID3._decodePrivFrame = function _decodePrivFrame(frame) {
+ /*
+ Format: <text string>\0<binary data>
+ */
+ if (frame.size < 2) {
+ return undefined;
+ }
+
+ var owner = ID3._utf8ArrayToStr(frame.data, true);
+
+ var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
+ return {
+ key: frame.type,
+ info: owner,
+ data: privateData.buffer
+ };
+ };
+
+ ID3._decodeTextFrame = function _decodeTextFrame(frame) {
+ if (frame.size < 2) {
+ return undefined;
+ }
+
+ if (frame.type === 'TXXX') {
+ /*
+ Format:
+ [0] = {Text Encoding}
+ [1-?] = {Description}\0{Value}
+ */
+ var index = 1;
+
+ var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
+
+ index += description.length + 1;
+
+ var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
+
+ return {
+ key: frame.type,
+ info: description,
+ data: value
+ };
+ } else {
+ /*
+ Format:
+ [0] = {Text Encoding}
+ [1-?] = {Value}
+ */
+ var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
+
+ return {
+ key: frame.type,
+ data: text
+ };
+ }
+ };
+
+ ID3._decodeURLFrame = function _decodeURLFrame(frame) {
+ if (frame.type === 'WXXX') {
+ /*
+ Format:
+ [0] = {Text Encoding}
+ [1-?] = {Description}\0{URL}
+ */
+ if (frame.size < 2) {
+ return undefined;
+ }
+
+ var index = 1;
+
+ var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
+
+ index += description.length + 1;
+
+ var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
+
+ return {
+ key: frame.type,
+ info: description,
+ data: value
+ };
+ } else {
+ /*
+ Format:
+ [0-?] = {URL}
+ */
+ var url = ID3._utf8ArrayToStr(frame.data);
+
+ return {
+ key: frame.type,
+ data: url
+ };
+ }
+ } // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
+ // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
+
+ /* utf.js - UTF-8 <=> UTF-16 convertion
+ *
+ * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
+ * Version: 1.0
+ * LastModified: Dec 25 1999
+ * This library is free. You can redistribute it and/or modify it.
+ */
+ ;
+
+ ID3._utf8ArrayToStr = function _utf8ArrayToStr(array, exitOnNull) {
+ if (exitOnNull === void 0) {
+ exitOnNull = false;
+ }
+
+ var decoder = getTextDecoder();
+
+ if (decoder) {
+ var decoded = decoder.decode(array);
+
+ if (exitOnNull) {
+ // grab up to the first null
+ var idx = decoded.indexOf('\0');
+ return idx !== -1 ? decoded.substring(0, idx) : decoded;
+ } // remove any null characters
+
+
+ return decoded.replace(/\0/g, '');
+ }
+
+ var len = array.length;
+ var c;
+ var char2;
+ var char3;
+ var out = '';
+ var i = 0;
+
+ while (i < len) {
+ c = array[i++];
+
+ if (c === 0x00 && exitOnNull) {
+ return out;
+ } else if (c === 0x00 || c === 0x03) {
+ // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
+ continue;
+ }
+
+ switch (c >> 4) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ // 0xxxxxxx
+ out += String.fromCharCode(c);
+ break;
+
+ case 12:
+ case 13:
+ // 110x xxxx 10xx xxxx
+ char2 = array[i++];
+ out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
+ break;
+
+ case 14:
+ // 1110 xxxx 10xx xxxx 10xx xxxx
+ char2 = array[i++];
+ char3 = array[i++];
+ out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
+ break;
+
+ default:
+ }
+ }
+
+ return out;
+ };
+
+ return ID3;
+}();
+
+var decoder;
+
+function getTextDecoder() {
+ var global = Object(_utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
+
+ if (!decoder && typeof global.TextDecoder !== 'undefined') {
+ decoder = new global.TextDecoder('utf-8');
+ }
+
+ return decoder;
+}
+
+var utf8ArrayToStr = ID3._utf8ArrayToStr;
+/* harmony default export */ __webpack_exports__["default"] = (ID3);
+
+
+/***/ }),
+
+/***/ "./src/demux/mp4demuxer.js":
+/*!*********************************!*\
+ !*** ./src/demux/mp4demuxer.js ***!
+ \*********************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
+/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
+/**
+ * MP4 demuxer
+ */
+
+
+var UINT32_MAX = Math.pow(2, 32) - 1;
+
+var MP4Demuxer = /*#__PURE__*/function () {
+ function MP4Demuxer(observer, remuxer) {
+ this.observer = observer;
+ this.remuxer = remuxer;
+ }
+
+ var _proto = MP4Demuxer.prototype;
+
+ _proto.resetTimeStamp = function resetTimeStamp(initPTS) {
+ this.initPTS = initPTS;
+ };
+
+ _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
+ // jshint unused:false
+ if (initSegment && initSegment.byteLength) {
+ var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); // default audio codec if nothing specified
+ // TODO : extract that from initsegment
+
+ if (audioCodec == null) {
+ audioCodec = 'mp4a.40.5';
+ }
+
+ if (videoCodec == null) {
+ videoCodec = 'avc1.42e01e';
+ }
+
+ var tracks = {};
+
+ if (initData.audio && initData.video) {
+ tracks.audiovideo = {
+ container: 'video/mp4',
+ codec: audioCodec + ',' + videoCodec,
+ initSegment: duration ? initSegment : null
+ };
+ } else {
+ if (initData.audio) {
+ tracks.audio = {
+ container: 'audio/mp4',
+ codec: audioCodec,
+ initSegment: duration ? initSegment : null
+ };
+ }
+
+ if (initData.video) {
+ tracks.video = {
+ container: 'video/mp4',
+ codec: videoCodec,
+ initSegment: duration ? initSegment : null
+ };
+ }
+ }
+
+ this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, {
+ tracks: tracks
+ });
+ } else {
+ if (audioCodec) {
+ this.audioCodec = audioCodec;
+ }
+
+ if (videoCodec) {
+ this.videoCodec = videoCodec;
+ }
+ }
+ };
+
+ MP4Demuxer.probe = function probe(data) {
+ // ensure we find a moof box in the first 16 kB
+ return MP4Demuxer.findBox({
+ data: data,
+ start: 0,
+ end: Math.min(data.length, 16384)
+ }, ['moof']).length > 0;
+ };
+
+ MP4Demuxer.bin2str = function bin2str(buffer) {
+ return String.fromCharCode.apply(null, buffer);
+ };
+
+ MP4Demuxer.readUint16 = function readUint16(buffer, offset) {
+ if (buffer.data) {
+ offset += buffer.start;
+ buffer = buffer.data;
+ }
+
+ var val = buffer[offset] << 8 | buffer[offset + 1];
+ return val < 0 ? 65536 + val : val;
+ };
+
+ MP4Demuxer.readUint32 = function readUint32(buffer, offset) {
+ if (buffer.data) {
+ offset += buffer.start;
+ buffer = buffer.data;
+ }
+
+ var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
+ return val < 0 ? 4294967296 + val : val;
+ };
+
+ MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) {
+ if (buffer.data) {
+ offset += buffer.start;
+ buffer = buffer.data;
+ }
+
+ buffer[offset] = value >> 24;
+ buffer[offset + 1] = value >> 16 & 0xff;
+ buffer[offset + 2] = value >> 8 & 0xff;
+ buffer[offset + 3] = value & 0xff;
+ } // Find the data for a box specified by its path
+ ;
+
+ MP4Demuxer.findBox = function findBox(data, path) {
+ var results = [],
+ i,
+ size,
+ type,
+ end,
+ subresults,
+ start,
+ endbox;
+
+ if (data.data) {
+ start = data.start;
+ end = data.end;
+ data = data.data;
+ } else {
+ start = 0;
+ end = data.byteLength;
+ }
+
+ if (!path.length) {
+ // short-circuit the search for empty paths
+ return null;
+ }
+
+ for (i = start; i < end;) {
+ size = MP4Demuxer.readUint32(data, i);
+ type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
+ endbox = size > 1 ? i + size : end;
+
+ if (type === path[0]) {
+ if (path.length === 1) {
+ // this is the end of the path and we've found the box we were
+ // looking for
+ results.push({
+ data: data,
+ start: i + 8,
+ end: endbox
+ });
+ } else {
+ // recursively search for the next box along the path
+ subresults = MP4Demuxer.findBox({
+ data: data,
+ start: i + 8,
+ end: endbox
+ }, path.slice(1));
+
+ if (subresults.length) {
+ results = results.concat(subresults);
+ }
+ }
+ }
+
+ i = endbox;
+ } // we've finished searching all of data
+
+
+ return results;
+ };
+
+ MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {
+ var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
+ var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
+
+ var index = 0;
+ var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
+ var references;
+
+ if (!sidx || !sidx[0]) {
+ return null;
+ }
+
+ references = [];
+ sidx = sidx[0];
+ var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
+
+ index = version === 0 ? 8 : 16;
+ var timescale = MP4Demuxer.readUint32(sidx, index);
+ index += 4; // TODO: parse earliestPresentationTime and firstOffset
+ // usually zero in our case
+
+ var earliestPresentationTime = 0;
+ var firstOffset = 0;
+
+ if (version === 0) {
+ index += 8;
+ } else {
+ index += 16;
+ } // skip reserved
+
+
+ index += 2;
+ var startByte = sidx.end + firstOffset;
+ var referencesCount = MP4Demuxer.readUint16(sidx, index);
+ index += 2;
+
+ for (var i = 0; i < referencesCount; i++) {
+ var referenceIndex = index;
+ var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
+ referenceIndex += 4;
+ var referenceSize = referenceInfo & 0x7FFFFFFF;
+ var referenceType = (referenceInfo & 0x80000000) >>> 31;
+
+ if (referenceType === 1) {
+ console.warn('SIDX has hierarchical references (not supported)');
+ return;
+ }
+
+ var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
+ referenceIndex += 4;
+ references.push({
+ referenceSize: referenceSize,
+ subsegmentDuration: subsegmentDuration,
+ // unscaled
+ info: {
+ duration: subsegmentDuration / timescale,
+ start: startByte,
+ end: startByte + referenceSize - 1
+ }
+ });
+ startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
+ // for |sapDelta|.
+
+ referenceIndex += 4; // skip to next ref
+
+ index = referenceIndex;
+ }
+
+ return {
+ earliestPresentationTime: earliestPresentationTime,
+ timescale: timescale,
+ version: version,
+ referencesCount: referencesCount,
+ references: references,
+ moovEndOffset: moovEndOffset
+ };
+ }
+ /**
+ * Parses an MP4 initialization segment and extracts stream type and
+ * timescale values for any declared tracks. Timescale values indicate the
+ * number of clock ticks per second to assume for time-based values
+ * elsewhere in the MP4.
+ *
+ * To determine the start time of an MP4, you need two pieces of
+ * information: the timescale unit and the earliest base media decode
+ * time. Multiple timescales can be specified within an MP4 but the
+ * base media decode time is always expressed in the timescale from
+ * the media header box for the track:
+ * ```
+ * moov > trak > mdia > mdhd.timescale
+ * moov > trak > mdia > hdlr
+ * ```
+ * @param init {Uint8Array} the bytes of the init segment
+ * @return {object} a hash of track type to timescale values or null if
+ * the init segment is malformed.
+ */
+ ;
+
+ MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {
+ var result = [];
+ var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
+ traks.forEach(function (trak) {
+ var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
+
+ if (tkhd) {
+ var version = tkhd.data[tkhd.start];
+ var index = version === 0 ? 12 : 20;
+ var trackId = MP4Demuxer.readUint32(tkhd, index);
+ var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
+
+ if (mdhd) {
+ version = mdhd.data[mdhd.start];
+ index = version === 0 ? 12 : 20;
+ var timescale = MP4Demuxer.readUint32(mdhd, index);
+ var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
+
+ if (hdlr) {
+ var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
+ var type = {
+ 'soun': 'audio',
+ 'vide': 'video'
+ }[hdlrType];
+
+ if (type) {
+ // extract codec info. TODO : parse codec details to be able to build MIME type
+ var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
+
+ if (codecBox.length) {
+ codecBox = codecBox[0];
+ var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
+ _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("MP4Demuxer:" + type + ":" + codecType + " found");
+ }
+
+ result[trackId] = {
+ timescale: timescale,
+ type: type
+ };
+ result[type] = {
+ timescale: timescale,
+ id: trackId
+ };
+ }
+ }
+ }
+ }
+ });
+ return result;
+ }
+ /**
+ * Determine the base media decode start time, in seconds, for an MP4
+ * fragment. If multiple fragments are specified, the earliest time is
+ * returned.
+ *
+ * The base media decode time can be parsed from track fragment
+ * metadata:
+ * ```
+ * moof > traf > tfdt.baseMediaDecodeTime
+ * ```
+ * It requires the timescale value from the mdhd to interpret.
+ *
+ * @param timescale {object} a hash of track ids to timescale values.
+ * @return {number} the earliest base media decode start time for the
+ * fragment, in seconds
+ */
+ ;
+
+ MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
+ var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
+
+ trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']); // determine the start times for each track
+
+ baseTimes = [].concat.apply([], trafs.map(function (traf) {
+ return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
+ var id, scale, baseTime; // get the track id from the tfhd
+
+ id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
+
+ scale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
+
+ baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
+ var version, result;
+ version = tfdt.data[tfdt.start];
+ result = MP4Demuxer.readUint32(tfdt, 4);
+
+ if (version === 1) {
+ result *= Math.pow(2, 32);
+ result += MP4Demuxer.readUint32(tfdt, 8);
+ }
+
+ return result;
+ })[0]; // convert base time to seconds
+
+ return baseTime / scale;
+ });
+ })); // return the minimum
+
+ result = Math.min.apply(null, baseTimes);
+ return isFinite(result) ? result : 0;
+ };
+
+ MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
+ MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
+ return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
+ // get the track id from the tfhd
+ var id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
+
+ var timescale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
+
+ MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
+ var version = tfdt.data[tfdt.start];
+ var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
+
+ if (version === 0) {
+ MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
+ } else {
+ baseMediaDecodeTime *= Math.pow(2, 32);
+ baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
+ baseMediaDecodeTime -= timeOffset * timescale;
+ baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
+ var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
+ var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
+ MP4Demuxer.writeUint32(tfdt, 4, upper);
+ MP4Demuxer.writeUint32(tfdt, 8, lower);
+ }
+ });
+ });
+ });
+ } // feed incoming data to the front of the parsing pipeline
+ ;
+
+ _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
+ var initData = this.initData;
+
+ if (!initData) {
+ this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
+ initData = this.initData;
+ }
+
+ var startDTS,
+ initPTS = this.initPTS;
+
+ if (initPTS === undefined) {
+ var _startDTS = MP4Demuxer.getStartDTS(initData, data);
+
+ this.initPTS = initPTS = _startDTS - timeOffset;
+ this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, {
+ initPTS: initPTS
+ });
+ }
+
+ MP4Demuxer.offsetStartDTS(initData, data, initPTS);
+ startDTS = MP4Demuxer.getStartDTS(initData, data);
+ this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
+ };
+
+ _proto.destroy = function destroy() {};
+
+ return MP4Demuxer;
+}();
+
+/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
+
+/***/ }),
+
+/***/ "./src/errors.ts":
+/*!***********************!*\
+ !*** ./src/errors.ts ***!
+ \***********************/
+/*! exports provided: ErrorTypes, ErrorDetails */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
+var ErrorTypes;
+/**
+ * @enum {ErrorDetails}
+ * @typedef {string} ErrorDetail
+ */
+
+(function (ErrorTypes) {
+ ErrorTypes["NETWORK_ERROR"] = "networkError";
+ ErrorTypes["MEDIA_ERROR"] = "mediaError";
+ ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
+ ErrorTypes["MUX_ERROR"] = "muxError";
+ ErrorTypes["OTHER_ERROR"] = "otherError";
+})(ErrorTypes || (ErrorTypes = {}));
+
+var ErrorDetails;
+
+(function (ErrorDetails) {
+ ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
+ ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
+ ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
+ ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
+ ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
+ ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
+ ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
+ ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
+ ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
+ ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
+ ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
+ ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
+ ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
+ ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
+ ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
+ ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
+ ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
+ ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
+ ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
+ ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
+ ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
+ ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
+ ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
+ ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
+ ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
+ ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
+ ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
+ ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
+ ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
+ ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
+})(ErrorDetails || (ErrorDetails = {}));
+
+/***/ }),
+
+/***/ "./src/events.js":
+/*!***********************!*\
+ !*** ./src/events.js ***!
+ \***********************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/**
+ * @readonly
+ * @enum {string}
+ */
+var HlsEvents = {
+ // fired before MediaSource is attaching to media element - data: { media }
+ MEDIA_ATTACHING: 'hlsMediaAttaching',
+ // fired when MediaSource has been succesfully attached to media element - data: { }
+ MEDIA_ATTACHED: 'hlsMediaAttached',
+ // fired before detaching MediaSource from media element - data: { }
+ MEDIA_DETACHING: 'hlsMediaDetaching',
+ // fired when MediaSource has been detached from media element - data: { }
+ MEDIA_DETACHED: 'hlsMediaDetached',
+ // fired when we buffer is going to be reset - data: { }
+ BUFFER_RESET: 'hlsBufferReset',
+ // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
+ BUFFER_CODECS: 'hlsBufferCodecs',
+ // fired when sourcebuffers have been created - data: { tracks : tracks }
+ BUFFER_CREATED: 'hlsBufferCreated',
+ // fired when we append a segment to the buffer - data: { segment: segment object }
+ BUFFER_APPENDING: 'hlsBufferAppending',
+ // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
+ BUFFER_APPENDED: 'hlsBufferAppended',
+ // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
+ BUFFER_EOS: 'hlsBufferEos',
+ // fired when the media buffer should be flushed - data { startOffset, endOffset }
+ BUFFER_FLUSHING: 'hlsBufferFlushing',
+ // fired when the media buffer has been flushed - data: { }
+ BUFFER_FLUSHED: 'hlsBufferFlushed',
+ // fired to signal that a manifest loading starts - data: { url : manifestURL}
+ MANIFEST_LOADING: 'hlsManifestLoading',
+ // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
+ MANIFEST_LOADED: 'hlsManifestLoaded',
+ // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
+ MANIFEST_PARSED: 'hlsManifestParsed',
+ // fired when a level switch is requested - data: { level : id of new level }
+ LEVEL_SWITCHING: 'hlsLevelSwitching',
+ // fired when a level switch is effective - data: { level : id of new level }
+ LEVEL_SWITCHED: 'hlsLevelSwitched',
+ // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
+ LEVEL_LOADING: 'hlsLevelLoading',
+ // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
+ LEVEL_LOADED: 'hlsLevelLoaded',
+ // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
+ LEVEL_UPDATED: 'hlsLevelUpdated',
+ // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
+ LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
+ // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
+ LEVELS_UPDATED: 'hlsLevelsUpdated',
+ // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
+ AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
+ // fired when an audio track switching is requested - data: { id : audio track id }
+ AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
+ // fired when an audio track switch actually occurs - data: { id : audio track id }
+ AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
+ // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
+ AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
+ // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
+ AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
+ // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
+ SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
+ // fired when an subtitle track switch occurs - data: { id : subtitle track id }
+ SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
+ // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
+ SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
+ // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
+ SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
+ // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
+ SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
+ // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
+ CUES_PARSED: 'hlsCuesParsed',
+ // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
+ NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',
+ // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
+ INIT_PTS_FOUND: 'hlsInitPtsFound',
+ // fired when a fragment loading starts - data: { frag : fragment object }
+ FRAG_LOADING: 'hlsFragLoading',
+ // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
+ FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
+ // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
+ FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
+ // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
+ FRAG_LOADED: 'hlsFragLoaded',
+ // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
+ FRAG_DECRYPTED: 'hlsFragDecrypted',
+ // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
+ FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
+ // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
+ FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
+ // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
+ FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
+ // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
+ FRAG_PARSING_DATA: 'hlsFragParsingData',
+ // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
+ FRAG_PARSED: 'hlsFragParsed',
+ // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
+ FRAG_BUFFERED: 'hlsFragBuffered',
+ // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
+ FRAG_CHANGED: 'hlsFragChanged',
+ // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
+ FPS_DROP: 'hlsFpsDrop',
+ // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
+ FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
+ // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
+ ERROR: 'hlsError',
+ // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
+ DESTROYING: 'hlsDestroying',
+ // fired when a decrypt key loading starts - data: { frag : fragment object }
+ KEY_LOADING: 'hlsKeyLoading',
+ // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
+ KEY_LOADED: 'hlsKeyLoaded',
+ // fired upon stream controller state transitions - data: { previousState, nextState }
+ STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',
+ // fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }
+ LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'
+};
+/* harmony default export */ __webpack_exports__["default"] = (HlsEvents);
+
+/***/ }),
+
+/***/ "./src/hls.ts":
+/*!*********************************!*\
+ !*** ./src/hls.ts + 50 modules ***!
+ \*********************************/
+/*! exports provided: default */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/crypt/decrypter.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/demuxer-inline.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/demux/demuxer-worker.js */
+/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/eventemitter3/index.js (<- Module is not an ECMAScript module) */
+/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/url-toolkit/src/url-toolkit.js (<- Module is not an ECMAScript module) */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// EXPORTS
+__webpack_require__.d(__webpack_exports__, "default", function() { return /* binding */ hls_Hls; });
+
+// NAMESPACE OBJECT: ./src/utils/cues.ts
+var cues_namespaceObject = {};
+__webpack_require__.r(cues_namespaceObject);
+__webpack_require__.d(cues_namespaceObject, "newCue", function() { return newCue; });
+
+// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js
+var url_toolkit = __webpack_require__("./node_modules/url-toolkit/src/url-toolkit.js");
+
+// EXTERNAL MODULE: ./src/errors.ts
+var errors = __webpack_require__("./src/errors.ts");
+
+// EXTERNAL MODULE: ./src/polyfills/number.js
+var number = __webpack_require__("./src/polyfills/number.js");
+
+// EXTERNAL MODULE: ./src/events.js
+var events = __webpack_require__("./src/events.js");
+
+// EXTERNAL MODULE: ./src/utils/logger.js
+var logger = __webpack_require__("./src/utils/logger.js");
+
+// CONCATENATED MODULE: ./src/event-handler.ts
+/*
+*
+* All objects in the event handling chain should inherit from this class
+*
+*/
+
+
+
+var FORBIDDEN_EVENT_NAMES = {
+ 'hlsEventGeneric': true,
+ 'hlsHandlerDestroying': true,
+ 'hlsHandlerDestroyed': true
+};
+
+var event_handler_EventHandler = /*#__PURE__*/function () {
+ function EventHandler(hls) {
+ this.hls = void 0;
+ this.handledEvents = void 0;
+ this.useGenericHandler = void 0;
+ this.hls = hls;
+ this.onEvent = this.onEvent.bind(this);
+
+ for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ events[_key - 1] = arguments[_key];
+ }
+
+ this.handledEvents = events;
+ this.useGenericHandler = true;
+ this.registerListeners();
+ }
+
+ var _proto = EventHandler.prototype;
+
+ _proto.destroy = function destroy() {
+ this.onHandlerDestroying();
+ this.unregisterListeners();
+ this.onHandlerDestroyed();
+ };
+
+ _proto.onHandlerDestroying = function onHandlerDestroying() {};
+
+ _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
+
+ _proto.isEventHandler = function isEventHandler() {
+ return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
+ };
+
+ _proto.registerListeners = function registerListeners() {
+ if (this.isEventHandler()) {
+ this.handledEvents.forEach(function (event) {
+ if (FORBIDDEN_EVENT_NAMES[event]) {
+ throw new Error('Forbidden event-name: ' + event);
+ }
+
+ this.hls.on(event, this.onEvent);
+ }, this);
+ }
+ };
+
+ _proto.unregisterListeners = function unregisterListeners() {
+ if (this.isEventHandler()) {
+ this.handledEvents.forEach(function (event) {
+ this.hls.off(event, this.onEvent);
+ }, this);
+ }
+ }
+ /**
+ * arguments: event (string), data (any)
+ */
+ ;
+
+ _proto.onEvent = function onEvent(event, data) {
+ this.onEventGeneric(event, data);
+ };
+
+ _proto.onEventGeneric = function onEventGeneric(event, data) {
+ var eventToFunction = function eventToFunction(event, data) {
+ var funcName = 'on' + event.replace('hls', '');
+
+ if (typeof this[funcName] !== 'function') {
+ throw new Error("Event " + event + " has no generic handler in this " + this.constructor.name + " class (tried " + funcName + ")");
+ }
+
+ return this[funcName].bind(this, data);
+ };
+
+ try {
+ eventToFunction.call(this, event, data).call();
+ } catch (err) {
+ logger["logger"].error("An internal error happened while handling event " + event + ". Error message: \"" + err.message + "\". Here is a stacktrace:", err);
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].OTHER_ERROR,
+ details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
+ fatal: false,
+ event: event,
+ err: err
+ });
+ }
+ };
+
+ return EventHandler;
+}();
+
+/* harmony default export */ var event_handler = (event_handler_EventHandler);
+// CONCATENATED MODULE: ./src/types/loader.ts
+/**
+ * `type` property values for this loaders' context object
+ * @enum
+ *
+ */
+var PlaylistContextType;
+/**
+ * @enum {string}
+ */
+
+(function (PlaylistContextType) {
+ PlaylistContextType["MANIFEST"] = "manifest";
+ PlaylistContextType["LEVEL"] = "level";
+ PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
+ PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
+})(PlaylistContextType || (PlaylistContextType = {}));
+
+var PlaylistLevelType;
+
+(function (PlaylistLevelType) {
+ PlaylistLevelType["MAIN"] = "main";
+ PlaylistLevelType["AUDIO"] = "audio";
+ PlaylistLevelType["SUBTITLE"] = "subtitle";
+})(PlaylistLevelType || (PlaylistLevelType = {}));
+// EXTERNAL MODULE: ./src/demux/mp4demuxer.js
+var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
+
+// CONCATENATED MODULE: ./src/loader/level-key.ts
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+
+
+var level_key_LevelKey = /*#__PURE__*/function () {
+ function LevelKey(baseURI, relativeURI) {
+ this._uri = null;
+ this.baseuri = void 0;
+ this.reluri = void 0;
+ this.method = null;
+ this.key = null;
+ this.iv = null;
+ this.baseuri = baseURI;
+ this.reluri = relativeURI;
+ }
+
+ _createClass(LevelKey, [{
+ key: "uri",
+ get: function get() {
+ if (!this._uri && this.reluri) {
+ this._uri = Object(url_toolkit["buildAbsoluteURL"])(this.baseuri, this.reluri, {
+ alwaysNormalize: true
+ });
+ }
+
+ return this._uri;
+ }
+ }]);
+
+ return LevelKey;
+}();
+
+
+// CONCATENATED MODULE: ./src/loader/fragment.ts
+
+
+
+function fragment_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function fragment_createClass(Constructor, protoProps, staticProps) { if (protoProps) fragment_defineProperties(Constructor.prototype, protoProps); if (staticProps) fragment_defineProperties(Constructor, staticProps); return Constructor; }
+
+
+
+
+var ElementaryStreamTypes;
+
+(function (ElementaryStreamTypes) {
+ ElementaryStreamTypes["AUDIO"] = "audio";
+ ElementaryStreamTypes["VIDEO"] = "video";
+})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
+
+var fragment_Fragment = /*#__PURE__*/function () {
+ function Fragment() {
+ var _this$_elementaryStre;
+
+ this._url = null;
+ this._byteRange = null;
+ this._decryptdata = null;
+ this._elementaryStreams = (_this$_elementaryStre = {}, _this$_elementaryStre[ElementaryStreamTypes.AUDIO] = false, _this$_elementaryStre[ElementaryStreamTypes.VIDEO] = false, _this$_elementaryStre);
+ this.deltaPTS = 0;
+ this.rawProgramDateTime = null;
+ this.programDateTime = null;
+ this.title = null;
+ this.tagList = [];
+ this.cc = void 0;
+ this.type = void 0;
+ this.relurl = void 0;
+ this.baseurl = void 0;
+ this.duration = void 0;
+ this.start = void 0;
+ this.sn = 0;
+ this.urlId = 0;
+ this.level = 0;
+ this.levelkey = void 0;
+ this.loader = void 0;
+ }
+
+ var _proto = Fragment.prototype;
+
+ // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
+ _proto.setByteRange = function setByteRange(value, previousFrag) {
+ var params = value.split('@', 2);
+ var byteRange = [];
+
+ if (params.length === 1) {
+ byteRange[0] = previousFrag ? previousFrag.byteRangeEndOffset : 0;
+ } else {
+ byteRange[0] = parseInt(params[1]);
+ }
+
+ byteRange[1] = parseInt(params[0]) + byteRange[0];
+ this._byteRange = byteRange;
+ };
+
+ /**
+ * @param {ElementaryStreamTypes} type
+ */
+ _proto.addElementaryStream = function addElementaryStream(type) {
+ this._elementaryStreams[type] = true;
+ }
+ /**
+ * @param {ElementaryStreamTypes} type
+ */
+ ;
+
+ _proto.hasElementaryStream = function hasElementaryStream(type) {
+ return this._elementaryStreams[type] === true;
+ }
+ /**
+ * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
+ * @param {number} segmentNumber - segment number to generate IV with
+ * @returns {Uint8Array}
+ */
+ ;
+
+ _proto.createInitializationVector = function createInitializationVector(segmentNumber) {
+ var uint8View = new Uint8Array(16);
+
+ for (var i = 12; i < 16; i++) {
+ uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
+ }
+
+ return uint8View;
+ }
+ /**
+ * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
+ * @param levelkey - a playlist's encryption info
+ * @param segmentNumber - the fragment's segment number
+ * @returns {LevelKey} - an object to be applied as a fragment's decryptdata
+ */
+ ;
+
+ _proto.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
+ var decryptdata = levelkey;
+
+ if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) && levelkey.uri && !levelkey.iv) {
+ decryptdata = new level_key_LevelKey(levelkey.baseuri, levelkey.reluri);
+ decryptdata.method = levelkey.method;
+ decryptdata.iv = this.createInitializationVector(segmentNumber);
+ }
+
+ return decryptdata;
+ };
+
+ fragment_createClass(Fragment, [{
+ key: "url",
+ get: function get() {
+ if (!this._url && this.relurl) {
+ this._url = Object(url_toolkit["buildAbsoluteURL"])(this.baseurl, this.relurl, {
+ alwaysNormalize: true
+ });
+ }
+
+ return this._url;
+ },
+ set: function set(value) {
+ this._url = value;
+ }
+ }, {
+ key: "byteRange",
+ get: function get() {
+ if (!this._byteRange) {
+ return [];
+ }
+
+ return this._byteRange;
+ }
+ /**
+ * @type {number}
+ */
+
+ }, {
+ key: "byteRangeStartOffset",
+ get: function get() {
+ return this.byteRange[0];
+ }
+ }, {
+ key: "byteRangeEndOffset",
+ get: function get() {
+ return this.byteRange[1];
+ }
+ }, {
+ key: "decryptdata",
+ get: function get() {
+ if (!this.levelkey && !this._decryptdata) {
+ return null;
+ }
+
+ if (!this._decryptdata && this.levelkey) {
+ var sn = this.sn;
+
+ if (typeof sn !== 'number') {
+ // We are fetching decryption data for a initialization segment
+ // If the segment was encrypted with AES-128
+ // It must have an IV defined. We cannot substitute the Segment Number in.
+ if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
+ logger["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
+ }
+ /*
+ Be converted to a Number.
+ 'initSegment' will become NaN.
+ NaN, which when converted through ToInt32() -> +0.
+ ---
+ Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
+ */
+
+
+ sn = 0;
+ }
+
+ this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
+ }
+
+ return this._decryptdata;
+ }
+ }, {
+ key: "endProgramDateTime",
+ get: function get() {
+ if (this.programDateTime === null) {
+ return null;
+ }
+
+ if (!Object(number["isFiniteNumber"])(this.programDateTime)) {
+ return null;
+ }
+
+ var duration = !Object(number["isFiniteNumber"])(this.duration) ? 0 : this.duration;
+ return this.programDateTime + duration * 1000;
+ }
+ }, {
+ key: "encrypted",
+ get: function get() {
+ return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
+ }
+ }]);
+
+ return Fragment;
+}();
+
+
+// CONCATENATED MODULE: ./src/loader/level.js
+
+
+function level_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function level_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_defineProperties(Constructor, staticProps); return Constructor; }
+
+var level_Level = /*#__PURE__*/function () {
+ function Level(baseUrl) {
+ // Please keep properties in alphabetical order
+ this.endCC = 0;
+ this.endSN = 0;
+ this.fragments = [];
+ this.initSegment = null;
+ this.live = true;
+ this.needSidxRanges = false;
+ this.startCC = 0;
+ this.startSN = 0;
+ this.startTimeOffset = null;
+ this.targetduration = 0;
+ this.totalduration = 0;
+ this.type = null;
+ this.url = baseUrl;
+ this.version = null;
+ }
+
+ level_createClass(Level, [{
+ key: "hasProgramDateTime",
+ get: function get() {
+ return !!(this.fragments[0] && Object(number["isFiniteNumber"])(this.fragments[0].programDateTime));
+ }
+ }]);
+
+ return Level;
+}();
+
+
+// CONCATENATED MODULE: ./src/utils/attr-list.js
+var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
+
+var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
+// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
+
+var AttrList = /*#__PURE__*/function () {
+ function AttrList(attrs) {
+ if (typeof attrs === 'string') {
+ attrs = AttrList.parseAttrList(attrs);
+ }
+
+ for (var attr in attrs) {
+ if (attrs.hasOwnProperty(attr)) {
+ this[attr] = attrs[attr];
+ }
+ }
+ }
+
+ var _proto = AttrList.prototype;
+
+ _proto.decimalInteger = function decimalInteger(attrName) {
+ var intValue = parseInt(this[attrName], 10);
+
+ if (intValue > Number.MAX_SAFE_INTEGER) {
+ return Infinity;
+ }
+
+ return intValue;
+ };
+
+ _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
+ if (this[attrName]) {
+ var stringValue = (this[attrName] || '0x').slice(2);
+ stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
+ var value = new Uint8Array(stringValue.length / 2);
+
+ for (var i = 0; i < stringValue.length / 2; i++) {
+ value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
+ }
+
+ return value;
+ } else {
+ return null;
+ }
+ };
+
+ _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
+ var intValue = parseInt(this[attrName], 16);
+
+ if (intValue > Number.MAX_SAFE_INTEGER) {
+ return Infinity;
+ }
+
+ return intValue;
+ };
+
+ _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
+ return parseFloat(this[attrName]);
+ };
+
+ _proto.enumeratedString = function enumeratedString(attrName) {
+ return this[attrName];
+ };
+
+ _proto.decimalResolution = function decimalResolution(attrName) {
+ var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
+
+ if (res === null) {
+ return undefined;
+ }
+
+ return {
+ width: parseInt(res[1], 10),
+ height: parseInt(res[2], 10)
+ };
+ };
+
+ AttrList.parseAttrList = function parseAttrList(input) {
+ var match,
+ attrs = {};
+ ATTR_LIST_REGEX.lastIndex = 0;
+
+ while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
+ var value = match[2],
+ quote = '"';
+
+ if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
+ value = value.slice(1, -1);
+ }
+
+ attrs[match[1]] = value;
+ }
+
+ return attrs;
+ };
+
+ return AttrList;
+}();
+
+/* harmony default export */ var attr_list = (AttrList);
+// CONCATENATED MODULE: ./src/utils/codecs.ts
+// from http://mp4ra.org/codecs.html
+var sampleEntryCodesISO = {
+ audio: {
+ 'a3ds': true,
+ 'ac-3': true,
+ 'ac-4': true,
+ 'alac': true,
+ 'alaw': true,
+ 'dra1': true,
+ 'dts+': true,
+ 'dts-': true,
+ 'dtsc': true,
+ 'dtse': true,
+ 'dtsh': true,
+ 'ec-3': true,
+ 'enca': true,
+ 'g719': true,
+ 'g726': true,
+ 'm4ae': true,
+ 'mha1': true,
+ 'mha2': true,
+ 'mhm1': true,
+ 'mhm2': true,
+ 'mlpa': true,
+ 'mp4a': true,
+ 'raw ': true,
+ 'Opus': true,
+ 'samr': true,
+ 'sawb': true,
+ 'sawp': true,
+ 'sevc': true,
+ 'sqcp': true,
+ 'ssmv': true,
+ 'twos': true,
+ 'ulaw': true
+ },
+ video: {
+ 'avc1': true,
+ 'avc2': true,
+ 'avc3': true,
+ 'avc4': true,
+ 'avcp': true,
+ 'drac': true,
+ 'dvav': true,
+ 'dvhe': true,
+ 'encv': true,
+ 'hev1': true,
+ 'hvc1': true,
+ 'mjp2': true,
+ 'mp4v': true,
+ 'mvc1': true,
+ 'mvc2': true,
+ 'mvc3': true,
+ 'mvc4': true,
+ 'resv': true,
+ 'rv60': true,
+ 's263': true,
+ 'svc1': true,
+ 'svc2': true,
+ 'vc-1': true,
+ 'vp08': true,
+ 'vp09': true
+ }
+};
+
+function isCodecType(codec, type) {
+ var typeCodes = sampleEntryCodesISO[type];
+ return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
+}
+
+function isCodecSupportedInMp4(codec, type) {
+ return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
+}
+
+
+// CONCATENATED MODULE: ./src/loader/m3u8-parser.ts
+
+
+
+
+
+
+
+
+
+
+
+/**
+ * M3U8 parser
+ * @module
+ */
+// https://regex101.com is your friend
+var MASTER_PLAYLIST_REGEX = /(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g;
+var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
+var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
+/|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
+/|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
+/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
+/|#.*/.source // All other non-segment oriented tags will match with all groups empty
+].join(''), 'g');
+var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;
+var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
+
+var m3u8_parser_M3U8Parser = /*#__PURE__*/function () {
+ function M3U8Parser() {}
+
+ M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
+ for (var i = 0; i < groups.length; i++) {
+ var group = groups[i];
+
+ if (group.id === mediaGroupId) {
+ return group;
+ }
+ }
+ };
+
+ M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
+ var avcdata = codec.split('.');
+ var result;
+
+ if (avcdata.length > 2) {
+ result = avcdata.shift() + '.';
+ result += parseInt(avcdata.shift()).toString(16);
+ result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
+ } else {
+ result = codec;
+ }
+
+ return result;
+ };
+
+ M3U8Parser.resolve = function resolve(url, baseUrl) {
+ return url_toolkit["buildAbsoluteURL"](baseUrl, url, {
+ alwaysNormalize: true
+ });
+ };
+
+ M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
+ // TODO(typescript-level)
+ var levels = [];
+ var sessionData = {};
+ var hasSessionData = false;
+ MASTER_PLAYLIST_REGEX.lastIndex = 0; // TODO(typescript-level)
+
+ function setCodecs(codecs, level) {
+ ['video', 'audio'].forEach(function (type) {
+ var filtered = codecs.filter(function (codec) {
+ return isCodecType(codec, type);
+ });
+
+ if (filtered.length) {
+ var preferred = filtered.filter(function (codec) {
+ return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
+ });
+ level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
+
+ codecs = codecs.filter(function (codec) {
+ return filtered.indexOf(codec) === -1;
+ });
+ }
+ });
+ level.unknownCodecs = codecs;
+ }
+
+ var result;
+
+ while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
+ if (result[1]) {
+ // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
+ // TODO(typescript-level)
+ var level = {};
+ var attrs = level.attrs = new attr_list(result[1]);
+ level.url = M3U8Parser.resolve(result[2], baseurl);
+ var resolution = attrs.decimalResolution('RESOLUTION');
+
+ if (resolution) {
+ level.width = resolution.width;
+ level.height = resolution.height;
+ }
+
+ level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
+ level.name = attrs.NAME;
+ setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
+
+ if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
+ level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
+ }
+
+ levels.push(level);
+ } else if (result[3]) {
+ // '#EXT-X-SESSION-DATA' is found, parse session data in group 3
+ var sessionAttrs = new attr_list(result[3]);
+
+ if (sessionAttrs['DATA-ID']) {
+ hasSessionData = true;
+ sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
+ }
+ }
+ }
+
+ return {
+ levels: levels,
+ sessionData: hasSessionData ? sessionData : null
+ };
+ };
+
+ M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, audioGroups) {
+ if (audioGroups === void 0) {
+ audioGroups = [];
+ }
+
+ var result;
+ var medias = [];
+ var id = 0;
+ MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
+
+ while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
+ var attrs = new attr_list(result[1]);
+
+ if (attrs.TYPE === type) {
+ var media = {
+ attrs: attrs,
+ id: id++,
+ groupId: attrs['GROUP-ID'],
+ instreamId: attrs['INSTREAM-ID'],
+ name: attrs.NAME || attrs.LANGUAGE,
+ type: type,
+ default: attrs.DEFAULT === 'YES',
+ autoselect: attrs.AUTOSELECT === 'YES',
+ forced: attrs.FORCED === 'YES',
+ lang: attrs.LANGUAGE
+ };
+
+ if (attrs.URI) {
+ media.url = M3U8Parser.resolve(attrs.URI, baseurl);
+ }
+
+ if (audioGroups.length) {
+ // If there are audio groups signalled in the manifest, let's look for a matching codec string for this track
+ var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId); // If we don't find the track signalled, lets use the first audio groups codec we have
+ // Acting as a best guess
+
+ media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
+ }
+
+ medias.push(media);
+ }
+ }
+
+ return medias;
+ };
+
+ M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
+ var currentSN = 0;
+ var totalduration = 0;
+ var level = new level_Level(baseurl);
+ var discontinuityCounter = 0;
+ var prevFrag = null;
+ var frag = new fragment_Fragment();
+ var result;
+ var i;
+ var levelkey;
+ var firstPdtIndex = null;
+ LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
+
+ while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
+ var duration = result[1];
+
+ if (duration) {
+ // INF
+ frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
+
+ var title = (' ' + result[2]).slice(1);
+ frag.title = title || null;
+ frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
+ } else if (result[3]) {
+ // url
+ if (Object(number["isFiniteNumber"])(frag.duration)) {
+ var sn = currentSN++;
+ frag.type = type;
+ frag.start = totalduration;
+
+ if (levelkey) {
+ frag.levelkey = levelkey;
+ }
+
+ frag.sn = sn;
+ frag.level = id;
+ frag.cc = discontinuityCounter;
+ frag.urlId = levelUrlId;
+ frag.baseurl = baseurl; // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
+
+ frag.relurl = (' ' + result[3]).slice(1);
+ assignProgramDateTime(frag, prevFrag);
+ level.fragments.push(frag);
+ prevFrag = frag;
+ totalduration += frag.duration;
+ frag = new fragment_Fragment();
+ }
+ } else if (result[4]) {
+ // X-BYTERANGE
+ var data = (' ' + result[4]).slice(1);
+
+ if (prevFrag) {
+ frag.setByteRange(data, prevFrag);
+ } else {
+ frag.setByteRange(data);
+ }
+ } else if (result[5]) {
+ // PROGRAM-DATE-TIME
+ // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
+ frag.rawProgramDateTime = (' ' + result[5]).slice(1);
+ frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
+
+ if (firstPdtIndex === null) {
+ firstPdtIndex = level.fragments.length;
+ }
+ } else {
+ result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
+
+ if (!result) {
+ logger["logger"].warn('No matches on slow regex match for level playlist!');
+ continue;
+ }
+
+ for (i = 1; i < result.length; i++) {
+ if (typeof result[i] !== 'undefined') {
+ break;
+ }
+ } // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
+
+
+ var value1 = (' ' + result[i + 1]).slice(1);
+ var value2 = (' ' + result[i + 2]).slice(1);
+
+ switch (result[i]) {
+ case '#':
+ frag.tagList.push(value2 ? [value1, value2] : [value1]);
+ break;
+
+ case 'PLAYLIST-TYPE':
+ level.type = value1.toUpperCase();
+ break;
+
+ case 'MEDIA-SEQUENCE':
+ currentSN = level.startSN = parseInt(value1);
+ break;
+
+ case 'TARGETDURATION':
+ level.targetduration = parseFloat(value1);
+ break;
+
+ case 'VERSION':
+ level.version = parseInt(value1);
+ break;
+
+ case 'EXTM3U':
+ break;
+
+ case 'ENDLIST':
+ level.live = false;
+ break;
+
+ case 'DIS':
+ discontinuityCounter++;
+ frag.tagList.push(['DIS']);
+ break;
+
+ case 'DISCONTINUITY-SEQ':
+ discontinuityCounter = parseInt(value1);
+ break;
+
+ case 'KEY':
+ {
+ // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
+ var decryptparams = value1;
+ var keyAttrs = new attr_list(decryptparams);
+ var decryptmethod = keyAttrs.enumeratedString('METHOD');
+ var decrypturi = keyAttrs.URI;
+ var decryptiv = keyAttrs.hexadecimalInteger('IV'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
+
+ var decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';
+
+ if (decryptkeyformat === 'com.apple.streamingkeydelivery') {
+ logger["logger"].warn('Keyformat com.apple.streamingkeydelivery is not supported');
+ continue;
+ }
+
+ if (decryptmethod) {
+ levelkey = new level_key_LevelKey(baseurl, decrypturi);
+
+ if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
+ levelkey.method = decryptmethod;
+ levelkey.key = null; // Initialization Vector (IV)
+
+ levelkey.iv = decryptiv;
+ }
+ }
+
+ break;
+ }
+
+ case 'START':
+ {
+ var startAttrs = new attr_list(value1);
+ var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
+
+ if (Object(number["isFiniteNumber"])(startTimeOffset)) {
+ level.startTimeOffset = startTimeOffset;
+ }
+
+ break;
+ }
+
+ case 'MAP':
+ {
+ var mapAttrs = new attr_list(value1);
+ frag.relurl = mapAttrs.URI;
+
+ if (mapAttrs.BYTERANGE) {
+ frag.setByteRange(mapAttrs.BYTERANGE);
+ }
+
+ frag.baseurl = baseurl;
+ frag.level = id;
+ frag.type = type;
+ frag.sn = 'initSegment';
+ level.initSegment = frag;
+ frag = new fragment_Fragment();
+ frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
+ break;
+ }
+
+ default:
+ logger["logger"].warn("line parsed but not handled: " + result);
+ break;
+ }
+ }
+ }
+
+ frag = prevFrag; // logger.log('found ' + level.fragments.length + ' fragments');
+
+ if (frag && !frag.relurl) {
+ level.fragments.pop();
+ totalduration -= frag.duration;
+ }
+
+ level.totalduration = totalduration;
+ level.averagetargetduration = totalduration / level.fragments.length;
+ level.endSN = currentSN - 1;
+ level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
+ level.endCC = discontinuityCounter;
+
+ if (!level.initSegment && level.fragments.length) {
+ // this is a bit lurky but HLS really has no other way to tell us
+ // if the fragments are TS or MP4, except if we download them :/
+ // but this is to be able to handle SIDX.
+ if (level.fragments.every(function (frag) {
+ return MP4_REGEX_SUFFIX.test(frag.relurl);
+ })) {
+ logger["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
+ frag = new fragment_Fragment();
+ frag.relurl = level.fragments[0].relurl;
+ frag.baseurl = baseurl;
+ frag.level = id;
+ frag.type = type;
+ frag.sn = 'initSegment';
+ level.initSegment = frag;
+ level.needSidxRanges = true;
+ }
+ }
+ /**
+ * Backfill any missing PDT values
+ "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
+ one or more Media Segment URIs, the client SHOULD extrapolate
+ backward from that tag (using EXTINF durations and/or media
+ timestamps) to associate dates with those segments."
+ * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
+ * computed.
+ */
+
+
+ if (firstPdtIndex) {
+ backfillProgramDateTimes(level.fragments, firstPdtIndex);
+ }
+
+ return level;
+ };
+
+ return M3U8Parser;
+}();
+
+
+
+function backfillProgramDateTimes(fragments, startIndex) {
+ var fragPrev = fragments[startIndex];
+
+ for (var i = startIndex - 1; i >= 0; i--) {
+ var frag = fragments[i];
+ frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
+ fragPrev = frag;
+ }
+}
+
+function assignProgramDateTime(frag, prevFrag) {
+ if (frag.rawProgramDateTime) {
+ frag.programDateTime = Date.parse(frag.rawProgramDateTime);
+ } else if (prevFrag === null || prevFrag === void 0 ? void 0 : prevFrag.programDateTime) {
+ frag.programDateTime = prevFrag.endProgramDateTime;
+ }
+
+ if (!Object(number["isFiniteNumber"])(frag.programDateTime)) {
+ frag.programDateTime = null;
+ frag.rawProgramDateTime = null;
+ }
+}
+// CONCATENATED MODULE: ./src/loader/playlist-loader.ts
+
+
+
+function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/**
+ * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
+ *
+ * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
+ *
+ * Uses loader(s) set in config to do actual internal loading of resource tasks.
+ *
+ * @module
+ *
+ */
+
+
+
+
+
+
+
+var _window = window,
+ performance = _window.performance;
+/**
+ * @constructor
+ */
+
+var playlist_loader_PlaylistLoader = /*#__PURE__*/function (_EventHandler) {
+ _inheritsLoose(PlaylistLoader, _EventHandler);
+
+ /**
+ * @constructs
+ * @param {Hls} hls
+ */
+ function PlaylistLoader(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADING, events["default"].LEVEL_LOADING, events["default"].AUDIO_TRACK_LOADING, events["default"].SUBTITLE_TRACK_LOADING) || this;
+ _this.loaders = {};
+ return _this;
+ }
+ /**
+ * @param {PlaylistContextType} type
+ * @returns {boolean}
+ */
+
+
+ PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {
+ return type !== PlaylistContextType.AUDIO_TRACK && type !== PlaylistContextType.SUBTITLE_TRACK;
+ }
+ /**
+ * Map context.type to LevelType
+ * @param {PlaylistLoaderContext} context
+ * @returns {LevelType}
+ */
+ ;
+
+ PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {
+ var type = context.type;
+
+ switch (type) {
+ case PlaylistContextType.AUDIO_TRACK:
+ return PlaylistLevelType.AUDIO;
+
+ case PlaylistContextType.SUBTITLE_TRACK:
+ return PlaylistLevelType.SUBTITLE;
+
+ default:
+ return PlaylistLevelType.MAIN;
+ }
+ };
+
+ PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {
+ var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
+ // data-uri mode also not supported (but no need to detect redirection)
+
+ if (url === undefined || url.indexOf('data:') === 0) {
+ // fallback to initial URL
+ url = context.url;
+ }
+
+ return url;
+ }
+ /**
+ * Returns defaults or configured loader-type overloads (pLoader and loader config params)
+ * Default loader is XHRLoader (see utils)
+ * @param {PlaylistLoaderContext} context
+ * @returns {Loader} or other compatible configured overload
+ */
+ ;
+
+ var _proto = PlaylistLoader.prototype;
+
+ _proto.createInternalLoader = function createInternalLoader(context) {
+ var config = this.hls.config;
+ var PLoader = config.pLoader;
+ var Loader = config.loader; // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader
+
+ var InternalLoader = PLoader || Loader;
+ var loader = new InternalLoader(config); // TODO - Do we really need to assign the instance or if the dep has been lost
+
+ context.loader = loader;
+ this.loaders[context.type] = loader;
+ return loader;
+ };
+
+ _proto.getInternalLoader = function getInternalLoader(context) {
+ return this.loaders[context.type];
+ };
+
+ _proto.resetInternalLoader = function resetInternalLoader(contextType) {
+ if (this.loaders[contextType]) {
+ delete this.loaders[contextType];
+ }
+ }
+ /**
+ * Call `destroy` on all internal loader instances mapped (one per context type)
+ */
+ ;
+
+ _proto.destroyInternalLoaders = function destroyInternalLoaders() {
+ for (var contextType in this.loaders) {
+ var loader = this.loaders[contextType];
+
+ if (loader) {
+ loader.destroy();
+ }
+
+ this.resetInternalLoader(contextType);
+ }
+ };
+
+ _proto.destroy = function destroy() {
+ this.destroyInternalLoaders();
+
+ _EventHandler.prototype.destroy.call(this);
+ };
+
+ _proto.onManifestLoading = function onManifestLoading(data) {
+ this.load({
+ url: data.url,
+ type: PlaylistContextType.MANIFEST,
+ level: 0,
+ id: null,
+ responseType: 'text'
+ });
+ };
+
+ _proto.onLevelLoading = function onLevelLoading(data) {
+ this.load({
+ url: data.url,
+ type: PlaylistContextType.LEVEL,
+ level: data.level,
+ id: data.id,
+ responseType: 'text'
+ });
+ };
+
+ _proto.onAudioTrackLoading = function onAudioTrackLoading(data) {
+ this.load({
+ url: data.url,
+ type: PlaylistContextType.AUDIO_TRACK,
+ level: null,
+ id: data.id,
+ responseType: 'text'
+ });
+ };
+
+ _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {
+ this.load({
+ url: data.url,
+ type: PlaylistContextType.SUBTITLE_TRACK,
+ level: null,
+ id: data.id,
+ responseType: 'text'
+ });
+ };
+
+ _proto.load = function load(context) {
+ var config = this.hls.config;
+ logger["logger"].debug("Loading playlist of type " + context.type + ", level: " + context.level + ", id: " + context.id); // Check if a loader for this context already exists
+
+ var loader = this.getInternalLoader(context);
+
+ if (loader) {
+ var loaderContext = loader.context;
+
+ if (loaderContext && loaderContext.url === context.url) {
+ // same URL can't overlap
+ logger["logger"].trace('playlist request ongoing');
+ return false;
+ } else {
+ logger["logger"].warn("aborting previous loader for type: " + context.type);
+ loader.abort();
+ }
+ }
+
+ var maxRetry;
+ var timeout;
+ var retryDelay;
+ var maxRetryDelay; // apply different configs for retries depending on
+ // context (manifest, level, audio/subs playlist)
+
+ switch (context.type) {
+ case PlaylistContextType.MANIFEST:
+ maxRetry = config.manifestLoadingMaxRetry;
+ timeout = config.manifestLoadingTimeOut;
+ retryDelay = config.manifestLoadingRetryDelay;
+ maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
+ break;
+
+ case PlaylistContextType.LEVEL:
+ // Disable internal loader retry logic, since we are managing retries in Level Controller
+ maxRetry = 0;
+ maxRetryDelay = 0;
+ retryDelay = 0;
+ timeout = config.levelLoadingTimeOut; // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
+
+ break;
+
+ default:
+ maxRetry = config.levelLoadingMaxRetry;
+ timeout = config.levelLoadingTimeOut;
+ retryDelay = config.levelLoadingRetryDelay;
+ maxRetryDelay = config.levelLoadingMaxRetryTimeout;
+ break;
+ }
+
+ loader = this.createInternalLoader(context);
+ var loaderConfig = {
+ timeout: timeout,
+ maxRetry: maxRetry,
+ retryDelay: retryDelay,
+ maxRetryDelay: maxRetryDelay
+ };
+ var loaderCallbacks = {
+ onSuccess: this.loadsuccess.bind(this),
+ onError: this.loaderror.bind(this),
+ onTimeout: this.loadtimeout.bind(this)
+ };
+ logger["logger"].debug("Calling internal loader delegate for URL: " + context.url);
+ loader.load(context, loaderConfig, loaderCallbacks);
+ return true;
+ };
+
+ _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ if (context.isSidxRequest) {
+ this._handleSidxRequest(response, context);
+
+ this._handlePlaylistLoaded(response, stats, context, networkDetails);
+
+ return;
+ }
+
+ this.resetInternalLoader(context.type);
+
+ if (typeof response.data !== 'string') {
+ throw new Error('expected responseType of "text" for PlaylistLoader');
+ }
+
+ var string = response.data;
+ stats.tload = performance.now(); // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
+ // Validate if it is an M3U8 at all
+
+ if (string.indexOf('#EXTM3U') !== 0) {
+ this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
+
+ return;
+ } // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
+
+
+ if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
+ this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
+ } else {
+ this._handleMasterPlaylist(response, stats, context, networkDetails);
+ }
+ };
+
+ _proto.loaderror = function loaderror(response, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ this._handleNetworkError(context, networkDetails, false, response);
+ };
+
+ _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ this._handleNetworkError(context, networkDetails, true);
+ } // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,
+ // but with custom loaders it could be generic investigate this further when config is typed
+ ;
+
+ _proto._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {
+ var hls = this.hls;
+ var string = response.data;
+ var url = PlaylistLoader.getResponseUrl(response, context);
+
+ var _M3U8Parser$parseMast = m3u8_parser_M3U8Parser.parseMasterPlaylist(string, url),
+ levels = _M3U8Parser$parseMast.levels,
+ sessionData = _M3U8Parser$parseMast.sessionData;
+
+ if (!levels.length) {
+ this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
+
+ return;
+ } // multi level playlist, parse level info
+
+
+ var audioGroups = levels.map(function (level) {
+ return {
+ id: level.attrs.AUDIO,
+ codec: level.audioCodec
+ };
+ });
+ var audioTracks = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
+ var subtitles = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
+ var captions = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
+
+ if (audioTracks.length) {
+ // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
+ var embeddedAudioFound = false;
+ audioTracks.forEach(function (audioTrack) {
+ if (!audioTrack.url) {
+ embeddedAudioFound = true;
+ }
+ }); // if no embedded audio track defined, but audio codec signaled in quality level,
+ // we need to signal this main audio track this could happen with playlists with
+ // alt audio rendition in which quality levels (main)
+ // contains both audio+video. but with mixed audio track not signaled
+
+ if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
+ logger["logger"].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
+ audioTracks.unshift({
+ type: 'main',
+ name: 'main',
+ default: false,
+ autoselect: false,
+ forced: false,
+ id: -1,
+ attrs: {},
+ url: ''
+ });
+ }
+ }
+
+ hls.trigger(events["default"].MANIFEST_LOADED, {
+ levels: levels,
+ audioTracks: audioTracks,
+ subtitles: subtitles,
+ captions: captions,
+ url: url,
+ stats: stats,
+ networkDetails: networkDetails,
+ sessionData: sessionData
+ });
+ };
+
+ _proto._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
+ var hls = this.hls;
+ var id = context.id,
+ level = context.level,
+ type = context.type;
+ var url = PlaylistLoader.getResponseUrl(response, context); // if the values are null, they will result in the else conditional
+
+ var levelUrlId = Object(number["isFiniteNumber"])(id) ? id : 0;
+ var levelId = Object(number["isFiniteNumber"])(level) ? level : levelUrlId;
+ var levelType = PlaylistLoader.mapContextToLevelType(context);
+ var levelDetails = m3u8_parser_M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); // set stats on level structure
+ // TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?
+
+ levelDetails.tload = stats.tload;
+
+ if (!levelDetails.fragments.length) {
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].LEVEL_EMPTY_ERROR,
+ fatal: false,
+ url: url,
+ reason: 'no fragments found in level',
+ level: typeof context.level === 'number' ? context.level : undefined
+ });
+ return;
+ } // We have done our first request (Manifest-type) and receive
+ // not a master playlist but a chunk-list (track/level)
+ // We fire the manifest-loaded event anyway with the parsed level-details
+ // by creating a single-level structure for it.
+
+
+ if (type === PlaylistContextType.MANIFEST) {
+ var singleLevel = {
+ url: url,
+ details: levelDetails
+ };
+ hls.trigger(events["default"].MANIFEST_LOADED, {
+ levels: [singleLevel],
+ audioTracks: [],
+ url: url,
+ stats: stats,
+ networkDetails: networkDetails,
+ sessionData: null
+ });
+ } // save parsing time
+
+
+ stats.tparsed = performance.now(); // in case we need SIDX ranges
+ // return early after calling load for
+ // the SIDX box.
+
+ if (levelDetails.needSidxRanges) {
+ var sidxUrl = levelDetails.initSegment.url;
+ this.load({
+ url: sidxUrl,
+ isSidxRequest: true,
+ type: type,
+ level: level,
+ levelDetails: levelDetails,
+ id: id,
+ rangeStart: 0,
+ rangeEnd: 2048,
+ responseType: 'arraybuffer'
+ });
+ return;
+ } // extend the context with the new levelDetails property
+
+
+ context.levelDetails = levelDetails;
+
+ this._handlePlaylistLoaded(response, stats, context, networkDetails);
+ };
+
+ _proto._handleSidxRequest = function _handleSidxRequest(response, context) {
+ if (typeof response.data === 'string') {
+ throw new Error('sidx request must be made with responseType of array buffer');
+ }
+
+ var sidxInfo = mp4demuxer["default"].parseSegmentIndex(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
+
+ if (!sidxInfo) {
+ return;
+ }
+
+ var sidxReferences = sidxInfo.references;
+ var levelDetails = context.levelDetails;
+ sidxReferences.forEach(function (segmentRef, index) {
+ var segRefInfo = segmentRef.info;
+
+ if (!levelDetails) {
+ return;
+ }
+
+ var frag = levelDetails.fragments[index];
+
+ if (frag.byteRange.length === 0) {
+ frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
+ }
+ });
+
+ if (levelDetails) {
+ levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
+ }
+ };
+
+ _proto._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].MANIFEST_PARSING_ERROR,
+ fatal: true,
+ url: response.url,
+ reason: reason,
+ networkDetails: networkDetails
+ });
+ };
+
+ _proto._handleNetworkError = function _handleNetworkError(context, networkDetails, timeout, response) {
+ if (timeout === void 0) {
+ timeout = false;
+ }
+
+ if (response === void 0) {
+ response = null;
+ }
+
+ logger["logger"].info("A network error occured while loading a " + context.type + "-type playlist");
+ var details;
+ var fatal;
+ var loader = this.getInternalLoader(context);
+
+ switch (context.type) {
+ case PlaylistContextType.MANIFEST:
+ details = timeout ? errors["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : errors["ErrorDetails"].MANIFEST_LOAD_ERROR;
+ fatal = true;
+ break;
+
+ case PlaylistContextType.LEVEL:
+ details = timeout ? errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT : errors["ErrorDetails"].LEVEL_LOAD_ERROR;
+ fatal = false;
+ break;
+
+ case PlaylistContextType.AUDIO_TRACK:
+ details = timeout ? errors["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
+ fatal = false;
+ break;
+
+ default:
+ // details = ...?
+ fatal = false;
+ }
+
+ if (loader) {
+ loader.abort();
+ this.resetInternalLoader(context.type);
+ } // TODO(typescript-events): when error events are handled, type this
+
+
+ var errorData = {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: details,
+ fatal: fatal,
+ url: context.url,
+ loader: loader,
+ context: context,
+ networkDetails: networkDetails
+ };
+
+ if (response) {
+ errorData.response = response;
+ }
+
+ this.hls.trigger(events["default"].ERROR, errorData);
+ };
+
+ _proto._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {
+ var type = context.type,
+ level = context.level,
+ id = context.id,
+ levelDetails = context.levelDetails;
+
+ if (!levelDetails || !levelDetails.targetduration) {
+ this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
+
+ return;
+ }
+
+ var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
+
+ if (canHaveLevels) {
+ this.hls.trigger(events["default"].LEVEL_LOADED, {
+ details: levelDetails,
+ level: level || 0,
+ id: id || 0,
+ stats: stats,
+ networkDetails: networkDetails
+ });
+ } else {
+ switch (type) {
+ case PlaylistContextType.AUDIO_TRACK:
+ this.hls.trigger(events["default"].AUDIO_TRACK_LOADED, {
+ details: levelDetails,
+ id: id,
+ stats: stats,
+ networkDetails: networkDetails
+ });
+ break;
+
+ case PlaylistContextType.SUBTITLE_TRACK:
+ this.hls.trigger(events["default"].SUBTITLE_TRACK_LOADED, {
+ details: levelDetails,
+ id: id,
+ stats: stats,
+ networkDetails: networkDetails
+ });
+ break;
+ }
+ }
+ };
+
+ return PlaylistLoader;
+}(event_handler);
+
+/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
+// CONCATENATED MODULE: ./src/loader/fragment-loader.js
+
+
+
+function fragment_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Fragment Loader
+*/
+
+
+
+
+
+var fragment_loader_FragmentLoader = /*#__PURE__*/function (_EventHandler) {
+ fragment_loader_inheritsLoose(FragmentLoader, _EventHandler);
+
+ function FragmentLoader(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING) || this;
+ _this.loaders = {};
+ return _this;
+ }
+
+ var _proto = FragmentLoader.prototype;
+
+ _proto.destroy = function destroy() {
+ var loaders = this.loaders;
+
+ for (var loaderName in loaders) {
+ var loader = loaders[loaderName];
+
+ if (loader) {
+ loader.destroy();
+ }
+ }
+
+ this.loaders = {};
+
+ _EventHandler.prototype.destroy.call(this);
+ };
+
+ _proto.onFragLoading = function onFragLoading(data) {
+ var frag = data.frag,
+ type = frag.type,
+ loaders = this.loaders,
+ config = this.hls.config,
+ FragmentILoader = config.fLoader,
+ DefaultILoader = config.loader; // reset fragment state
+
+ frag.loaded = 0;
+ var loader = loaders[type];
+
+ if (loader) {
+ logger["logger"].warn("abort previous fragment loader for type: " + type);
+ loader.abort();
+ }
+
+ loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
+ var loaderContext, loaderConfig, loaderCallbacks;
+ loaderContext = {
+ url: frag.url,
+ frag: frag,
+ responseType: 'arraybuffer',
+ progressData: false
+ };
+ var start = frag.byteRangeStartOffset,
+ end = frag.byteRangeEndOffset;
+
+ if (Object(number["isFiniteNumber"])(start) && Object(number["isFiniteNumber"])(end)) {
+ loaderContext.rangeStart = start;
+ loaderContext.rangeEnd = end;
+ }
+
+ loaderConfig = {
+ timeout: config.fragLoadingTimeOut,
+ maxRetry: 0,
+ retryDelay: 0,
+ maxRetryDelay: config.fragLoadingMaxRetryTimeout
+ };
+ loaderCallbacks = {
+ onSuccess: this.loadsuccess.bind(this),
+ onError: this.loaderror.bind(this),
+ onTimeout: this.loadtimeout.bind(this),
+ onProgress: this.loadprogress.bind(this)
+ };
+ loader.load(loaderContext, loaderConfig, loaderCallbacks);
+ };
+
+ _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ var payload = response.data,
+ frag = context.frag; // detach fragment loader on load success
+
+ frag.loader = undefined;
+ this.loaders[frag.type] = undefined;
+ this.hls.trigger(events["default"].FRAG_LOADED, {
+ payload: payload,
+ frag: frag,
+ stats: stats,
+ networkDetails: networkDetails
+ });
+ };
+
+ _proto.loaderror = function loaderror(response, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ var frag = context.frag;
+ var loader = frag.loader;
+
+ if (loader) {
+ loader.abort();
+ }
+
+ this.loaders[frag.type] = undefined;
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].FRAG_LOAD_ERROR,
+ fatal: false,
+ frag: context.frag,
+ response: response,
+ networkDetails: networkDetails
+ });
+ };
+
+ _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ var frag = context.frag;
+ var loader = frag.loader;
+
+ if (loader) {
+ loader.abort();
+ }
+
+ this.loaders[frag.type] = undefined;
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].FRAG_LOAD_TIMEOUT,
+ fatal: false,
+ frag: context.frag,
+ networkDetails: networkDetails
+ });
+ } // data will be used for progressive parsing
+ ;
+
+ _proto.loadprogress = function loadprogress(stats, context, data, networkDetails) {
+ if (networkDetails === void 0) {
+ networkDetails = null;
+ }
+
+ // jshint ignore:line
+ var frag = context.frag;
+ frag.loaded = stats.loaded;
+ this.hls.trigger(events["default"].FRAG_LOAD_PROGRESS, {
+ frag: frag,
+ stats: stats,
+ networkDetails: networkDetails
+ });
+ };
+
+ return FragmentLoader;
+}(event_handler);
+
+/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
+// CONCATENATED MODULE: ./src/loader/key-loader.ts
+function key_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Decrypt key Loader
+*/
+
+
+
+
+
+var key_loader_KeyLoader = /*#__PURE__*/function (_EventHandler) {
+ key_loader_inheritsLoose(KeyLoader, _EventHandler);
+
+ function KeyLoader(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].KEY_LOADING) || this;
+ _this.loaders = {};
+ _this.decryptkey = null;
+ _this.decrypturl = null;
+ return _this;
+ }
+
+ var _proto = KeyLoader.prototype;
+
+ _proto.destroy = function destroy() {
+ for (var loaderName in this.loaders) {
+ var loader = this.loaders[loaderName];
+
+ if (loader) {
+ loader.destroy();
+ }
+ }
+
+ this.loaders = {};
+
+ _EventHandler.prototype.destroy.call(this);
+ };
+
+ _proto.onKeyLoading = function onKeyLoading(data) {
+ var frag = data.frag;
+ var type = frag.type;
+ var loader = this.loaders[type];
+
+ if (!frag.decryptdata) {
+ logger["logger"].warn('Missing decryption data on fragment in onKeyLoading');
+ return;
+ } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
+
+
+ var uri = frag.decryptdata.uri;
+
+ if (uri !== this.decrypturl || this.decryptkey === null) {
+ var config = this.hls.config;
+
+ if (loader) {
+ logger["logger"].warn("abort previous key loader for type:" + type);
+ loader.abort();
+ }
+
+ if (!uri) {
+ logger["logger"].warn('key uri is falsy');
+ return;
+ }
+
+ frag.loader = this.loaders[type] = new config.loader(config);
+ this.decrypturl = uri;
+ this.decryptkey = null;
+ var loaderContext = {
+ url: uri,
+ frag: frag,
+ responseType: 'arraybuffer'
+ }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
+ // key-loader will trigger an error and rely on stream-controller to handle retry logic.
+ // this will also align retry logic with fragment-loader
+
+ var loaderConfig = {
+ timeout: config.fragLoadingTimeOut,
+ maxRetry: 0,
+ retryDelay: config.fragLoadingRetryDelay,
+ maxRetryDelay: config.fragLoadingMaxRetryTimeout
+ };
+ var loaderCallbacks = {
+ onSuccess: this.loadsuccess.bind(this),
+ onError: this.loaderror.bind(this),
+ onTimeout: this.loadtimeout.bind(this)
+ };
+ frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
+ } else if (this.decryptkey) {
+ // Return the key if it's already been loaded
+ frag.decryptdata.key = this.decryptkey;
+ this.hls.trigger(events["default"].KEY_LOADED, {
+ frag: frag
+ });
+ }
+ };
+
+ _proto.loadsuccess = function loadsuccess(response, stats, context) {
+ var frag = context.frag;
+
+ if (!frag.decryptdata) {
+ logger["logger"].error('after key load, decryptdata unset');
+ return;
+ }
+
+ this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
+
+ frag.loader = undefined;
+ delete this.loaders[frag.type];
+ this.hls.trigger(events["default"].KEY_LOADED, {
+ frag: frag
+ });
+ };
+
+ _proto.loaderror = function loaderror(response, context) {
+ var frag = context.frag;
+ var loader = frag.loader;
+
+ if (loader) {
+ loader.abort();
+ }
+
+ delete this.loaders[frag.type];
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].KEY_LOAD_ERROR,
+ fatal: false,
+ frag: frag,
+ response: response
+ });
+ };
+
+ _proto.loadtimeout = function loadtimeout(stats, context) {
+ var frag = context.frag;
+ var loader = frag.loader;
+
+ if (loader) {
+ loader.abort();
+ }
+
+ delete this.loaders[frag.type];
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].NETWORK_ERROR,
+ details: errors["ErrorDetails"].KEY_LOAD_TIMEOUT,
+ fatal: false,
+ frag: frag
+ });
+ };
+
+ return KeyLoader;
+}(event_handler);
+
+/* harmony default export */ var key_loader = (key_loader_KeyLoader);
+// CONCATENATED MODULE: ./src/controller/fragment-tracker.js
+
+
+function fragment_tracker_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+var FragmentState = {
+ NOT_LOADED: 'NOT_LOADED',
+ APPENDING: 'APPENDING',
+ PARTIAL: 'PARTIAL',
+ OK: 'OK'
+};
+var fragment_tracker_FragmentTracker = /*#__PURE__*/function (_EventHandler) {
+ fragment_tracker_inheritsLoose(FragmentTracker, _EventHandler);
+
+ function FragmentTracker(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].BUFFER_APPENDED, events["default"].FRAG_BUFFERED, events["default"].FRAG_LOADED) || this;
+ _this.bufferPadding = 0.2;
+ _this.fragments = Object.create(null);
+ _this.timeRanges = Object.create(null);
+ _this.config = hls.config;
+ return _this;
+ }
+
+ var _proto = FragmentTracker.prototype;
+
+ _proto.destroy = function destroy() {
+ this.fragments = Object.create(null);
+ this.timeRanges = Object.create(null);
+ this.config = null;
+ event_handler.prototype.destroy.call(this);
+
+ _EventHandler.prototype.destroy.call(this);
+ }
+ /**
+ * Return a Fragment that match the position and levelType.
+ * If not found any Fragment, return null
+ * @param {number} position
+ * @param {LevelType} levelType
+ * @returns {Fragment|null}
+ */
+ ;
+
+ _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
+ var fragments = this.fragments;
+ var bufferedFrags = Object.keys(fragments).filter(function (key) {
+ var fragmentEntity = fragments[key];
+
+ if (fragmentEntity.body.type !== levelType) {
+ return false;
+ }
+
+ if (!fragmentEntity.buffered) {
+ return false;
+ }
+
+ var frag = fragmentEntity.body;
+ return frag.startPTS <= position && position <= frag.endPTS;
+ });
+
+ if (bufferedFrags.length === 0) {
+ return null;
+ } else {
+ // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
+ var bufferedFragKey = bufferedFrags.pop();
+ return fragments[bufferedFragKey].body;
+ }
+ }
+ /**
+ * Partial fragments effected by coded frame eviction will be removed
+ * The browser will unload parts of the buffer to free up memory for new buffer data
+ * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
+ * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
+ * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
+ */
+ ;
+
+ _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {
+ var _this2 = this;
+
+ // Check if any flagged fragments have been unloaded
+ Object.keys(this.fragments).forEach(function (key) {
+ var fragmentEntity = _this2.fragments[key];
+
+ if (!fragmentEntity || !fragmentEntity.buffered) {
+ return;
+ }
+
+ var esData = fragmentEntity.range[elementaryStream];
+
+ if (!esData) {
+ return;
+ }
+
+ var fragmentTimes = esData.time;
+
+ for (var i = 0; i < fragmentTimes.length; i++) {
+ var time = fragmentTimes[i];
+
+ if (!_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {
+ // Unregister partial fragment as it needs to load again to be reused
+ _this2.removeFragment(fragmentEntity.body);
+
+ break;
+ }
+ }
+ });
+ }
+ /**
+ * Checks if the fragment passed in is loaded in the buffer properly
+ * Partially loaded fragments will be registered as a partial fragment
+ * @param {Object} fragment Check the fragment against all sourceBuffers loaded
+ */
+ ;
+
+ _proto.detectPartialFragments = function detectPartialFragments(fragment) {
+ var _this3 = this;
+
+ var fragKey = this.getFragmentKey(fragment);
+ var fragmentEntity = this.fragments[fragKey];
+
+ if (fragmentEntity) {
+ fragmentEntity.buffered = true;
+ Object.keys(this.timeRanges).forEach(function (elementaryStream) {
+ if (fragment.hasElementaryStream(elementaryStream)) {
+ var timeRange = _this3.timeRanges[elementaryStream]; // Check for malformed fragments
+ // Gaps need to be calculated for each elementaryStream
+
+ fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
+ }
+ });
+ }
+ };
+
+ _proto.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {
+ var fragmentTimes = [];
+ var startTime, endTime;
+ var fragmentPartial = false;
+
+ for (var i = 0; i < timeRange.length; i++) {
+ startTime = timeRange.start(i) - this.bufferPadding;
+ endTime = timeRange.end(i) + this.bufferPadding;
+
+ if (startPTS >= startTime && endPTS <= endTime) {
+ // Fragment is entirely contained in buffer
+ // No need to check the other timeRange times since it's completely playable
+ fragmentTimes.push({
+ startPTS: Math.max(startPTS, timeRange.start(i)),
+ endPTS: Math.min(endPTS, timeRange.end(i))
+ });
+ break;
+ } else if (startPTS < endTime && endPTS > startTime) {
+ // Check for intersection with buffer
+ // Get playable sections of the fragment
+ fragmentTimes.push({
+ startPTS: Math.max(startPTS, timeRange.start(i)),
+ endPTS: Math.min(endPTS, timeRange.end(i))
+ });
+ fragmentPartial = true;
+ } else if (endPTS <= startTime) {
+ // No need to check the rest of the timeRange as it is in order
+ break;
+ }
+ }
+
+ return {
+ time: fragmentTimes,
+ partial: fragmentPartial
+ };
+ };
+
+ _proto.getFragmentKey = function getFragmentKey(fragment) {
+ return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
+ }
+ /**
+ * Gets the partial fragment for a certain time
+ * @param {Number} time
+ * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
+ */
+ ;
+
+ _proto.getPartialFragment = function getPartialFragment(time) {
+ var _this4 = this;
+
+ var timePadding, startTime, endTime;
+ var bestFragment = null;
+ var bestOverlap = 0;
+ Object.keys(this.fragments).forEach(function (key) {
+ var fragmentEntity = _this4.fragments[key];
+
+ if (_this4.isPartial(fragmentEntity)) {
+ startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
+ endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
+
+ if (time >= startTime && time <= endTime) {
+ // Use the fragment that has the most padding from start and end time
+ timePadding = Math.min(time - startTime, endTime - time);
+
+ if (bestOverlap <= timePadding) {
+ bestFragment = fragmentEntity.body;
+ bestOverlap = timePadding;
+ }
+ }
+ }
+ });
+ return bestFragment;
+ }
+ /**
+ * @param {Object} fragment The fragment to check
+ * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
+ */
+ ;
+
+ _proto.getState = function getState(fragment) {
+ var fragKey = this.getFragmentKey(fragment);
+ var fragmentEntity = this.fragments[fragKey];
+ var state = FragmentState.NOT_LOADED;
+
+ if (fragmentEntity !== undefined) {
+ if (!fragmentEntity.buffered) {
+ state = FragmentState.APPENDING;
+ } else if (this.isPartial(fragmentEntity) === true) {
+ state = FragmentState.PARTIAL;
+ } else {
+ state = FragmentState.OK;
+ }
+ }
+
+ return state;
+ };
+
+ _proto.isPartial = function isPartial(fragmentEntity) {
+ return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
+ };
+
+ _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
+ var startTime, endTime;
+
+ for (var i = 0; i < timeRange.length; i++) {
+ startTime = timeRange.start(i) - this.bufferPadding;
+ endTime = timeRange.end(i) + this.bufferPadding;
+
+ if (startPTS >= startTime && endPTS <= endTime) {
+ return true;
+ }
+
+ if (endPTS <= startTime) {
+ // No need to check the rest of the timeRange as it is in order
+ return false;
+ }
+ }
+
+ return false;
+ }
+ /**
+ * Fires when a fragment loading is completed
+ */
+ ;
+
+ _proto.onFragLoaded = function onFragLoaded(e) {
+ var fragment = e.frag; // don't track initsegment (for which sn is not a number)
+ // don't track frags used for bitrateTest, they're irrelevant.
+
+ if (!Object(number["isFiniteNumber"])(fragment.sn) || fragment.bitrateTest) {
+ return;
+ }
+
+ this.fragments[this.getFragmentKey(fragment)] = {
+ body: fragment,
+ range: Object.create(null),
+ buffered: false
+ };
+ }
+ /**
+ * Fires when the buffer is updated
+ */
+ ;
+
+ _proto.onBufferAppended = function onBufferAppended(e) {
+ var _this5 = this;
+
+ // Store the latest timeRanges loaded in the buffer
+ this.timeRanges = e.timeRanges;
+ Object.keys(this.timeRanges).forEach(function (elementaryStream) {
+ var timeRange = _this5.timeRanges[elementaryStream];
+
+ _this5.detectEvictedFragments(elementaryStream, timeRange);
+ });
+ }
+ /**
+ * Fires after a fragment has been loaded into the source buffer
+ */
+ ;
+
+ _proto.onFragBuffered = function onFragBuffered(e) {
+ this.detectPartialFragments(e.frag);
+ }
+ /**
+ * Return true if fragment tracker has the fragment.
+ * @param {Object} fragment
+ * @returns {boolean}
+ */
+ ;
+
+ _proto.hasFragment = function hasFragment(fragment) {
+ var fragKey = this.getFragmentKey(fragment);
+ return this.fragments[fragKey] !== undefined;
+ }
+ /**
+ * Remove a fragment from fragment tracker until it is loaded again
+ * @param {Object} fragment The fragment to remove
+ */
+ ;
+
+ _proto.removeFragment = function removeFragment(fragment) {
+ var fragKey = this.getFragmentKey(fragment);
+ delete this.fragments[fragKey];
+ }
+ /**
+ * Remove all fragments from fragment tracker.
+ */
+ ;
+
+ _proto.removeAllFragments = function removeAllFragments() {
+ this.fragments = Object.create(null);
+ };
+
+ return FragmentTracker;
+}(event_handler);
+// CONCATENATED MODULE: ./src/utils/binary-search.ts
+var BinarySearch = {
+ /**
+ * Searches for an item in an array which matches a certain condition.
+ * This requires the condition to only match one item in the array,
+ * and for the array to be ordered.
+ *
+ * @param {Array<T>} list The array to search.
+ * @param {BinarySearchComparison<T>} comparisonFn
+ * Called and provided a candidate item as the first argument.
+ * Should return:
+ * > -1 if the item should be located at a lower index than the provided item.
+ * > 1 if the item should be located at a higher index than the provided item.
+ * > 0 if the item is the item you're looking for.
+ *
+ * @return {T | null} The object if it is found or null otherwise.
+ */
+ search: function search(list, comparisonFn) {
+ var minIndex = 0;
+ var maxIndex = list.length - 1;
+ var currentIndex = null;
+ var currentElement = null;
+
+ while (minIndex <= maxIndex) {
+ currentIndex = (minIndex + maxIndex) / 2 | 0;
+ currentElement = list[currentIndex];
+ var comparisonResult = comparisonFn(currentElement);
+
+ if (comparisonResult > 0) {
+ minIndex = currentIndex + 1;
+ } else if (comparisonResult < 0) {
+ maxIndex = currentIndex - 1;
+ } else {
+ return currentElement;
+ }
+ }
+
+ return null;
+ }
+};
+/* harmony default export */ var binary_search = (BinarySearch);
+// CONCATENATED MODULE: ./src/utils/buffer-helper.ts
+/**
+ * @module BufferHelper
+ *
+ * Providing methods dealing with buffer length retrieval for example.
+ *
+ * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
+ *
+ * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
+*/
+var BufferHelper = /*#__PURE__*/function () {
+ function BufferHelper() {}
+
+ /**
+ * Return true if `media`'s buffered include `position`
+ * @param {Bufferable} media
+ * @param {number} position
+ * @returns {boolean}
+ */
+ BufferHelper.isBuffered = function isBuffered(media, position) {
+ try {
+ if (media) {
+ var buffered = media.buffered;
+
+ for (var i = 0; i < buffered.length; i++) {
+ if (position >= buffered.start(i) && position <= buffered.end(i)) {
+ return true;
+ }
+ }
+ }
+ } catch (error) {// this is to catch
+ // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
+ // This SourceBuffer has been removed from the parent media source
+ }
+
+ return false;
+ };
+
+ BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
+ try {
+ if (media) {
+ var vbuffered = media.buffered;
+ var buffered = [];
+ var i;
+
+ for (i = 0; i < vbuffered.length; i++) {
+ buffered.push({
+ start: vbuffered.start(i),
+ end: vbuffered.end(i)
+ });
+ }
+
+ return this.bufferedInfo(buffered, pos, maxHoleDuration);
+ }
+ } catch (error) {// this is to catch
+ // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
+ // This SourceBuffer has been removed from the parent media source
+ }
+
+ return {
+ len: 0,
+ start: pos,
+ end: pos,
+ nextStart: undefined
+ };
+ };
+
+ BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
+ // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
+ buffered.sort(function (a, b) {
+ var diff = a.start - b.start;
+
+ if (diff) {
+ return diff;
+ } else {
+ return b.end - a.end;
+ }
+ });
+ var buffered2 = [];
+
+ if (maxHoleDuration) {
+ // there might be some small holes between buffer time range
+ // consider that holes smaller than maxHoleDuration are irrelevant and build another
+ // buffer time range representations that discards those holes
+ for (var i = 0; i < buffered.length; i++) {
+ var buf2len = buffered2.length;
+
+ if (buf2len) {
+ var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
+
+ if (buffered[i].start - buf2end < maxHoleDuration) {
+ // merge overlapping time ranges
+ // update lastRange.end only if smaller than item.end
+ // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
+ // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
+ if (buffered[i].end > buf2end) {
+ buffered2[buf2len - 1].end = buffered[i].end;
+ }
+ } else {
+ // big hole
+ buffered2.push(buffered[i]);
+ }
+ } else {
+ // first value
+ buffered2.push(buffered[i]);
+ }
+ }
+ } else {
+ buffered2 = buffered;
+ }
+
+ var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
+
+ var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
+
+ var bufferStart = pos;
+ var bufferEnd = pos;
+
+ for (var _i = 0; _i < buffered2.length; _i++) {
+ var start = buffered2[_i].start,
+ end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
+
+ if (pos + maxHoleDuration >= start && pos < end) {
+ // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
+ bufferStart = start;
+ bufferEnd = end;
+ bufferLen = bufferEnd - pos;
+ } else if (pos + maxHoleDuration < start) {
+ bufferStartNext = start;
+ break;
+ }
+ }
+
+ return {
+ len: bufferLen,
+ start: bufferStart,
+ end: bufferEnd,
+ nextStart: bufferStartNext
+ };
+ };
+
+ return BufferHelper;
+}();
+// EXTERNAL MODULE: ./node_modules/eventemitter3/index.js
+var eventemitter3 = __webpack_require__("./node_modules/eventemitter3/index.js");
+
+// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js
+var webworkify_webpack = __webpack_require__("./node_modules/webworkify-webpack/index.js");
+
+// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 12 modules
+var demuxer_inline = __webpack_require__("./src/demux/demuxer-inline.js");
+
+// CONCATENATED MODULE: ./src/utils/mediasource-helper.ts
+/**
+ * MediaSource helper
+ */
+function getMediaSource() {
+ return window.MediaSource || window.WebKitMediaSource;
+}
+// EXTERNAL MODULE: ./src/utils/get-self-scope.js
+var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
+
+// CONCATENATED MODULE: ./src/observer.ts
+function observer_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+/**
+ * Simple adapter sub-class of Nodejs-like EventEmitter.
+ */
+
+var Observer = /*#__PURE__*/function (_EventEmitter) {
+ observer_inheritsLoose(Observer, _EventEmitter);
+
+ function Observer() {
+ return _EventEmitter.apply(this, arguments) || this;
+ }
+
+ var _proto = Observer.prototype;
+
+ /**
+ * We simply want to pass along the event-name itself
+ * in every call to a handler, which is the purpose of our `trigger` method
+ * extending the standard API.
+ */
+ _proto.trigger = function trigger(event) {
+ for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ data[_key - 1] = arguments[_key];
+ }
+
+ this.emit.apply(this, [event, event].concat(data));
+ };
+
+ return Observer;
+}(eventemitter3["EventEmitter"]);
+// CONCATENATED MODULE: ./src/demux/demuxer.js
+
+
+
+
+
+
+
+
+
+ // see https://stackoverflow.com/a/11237259/589493
+
+var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
+
+var demuxer_MediaSource = getMediaSource() || {
+ isTypeSupported: function isTypeSupported() {
+ return false;
+ }
+};
+
+var demuxer_Demuxer = /*#__PURE__*/function () {
+ function Demuxer(hls, id) {
+ var _this = this;
+
+ this.hls = hls;
+ this.id = id;
+ var observer = this.observer = new Observer();
+ var config = hls.config;
+
+ var forwardMessage = function forwardMessage(ev, data) {
+ data = data || {};
+ data.frag = _this.frag;
+ data.id = _this.id;
+ hls.trigger(ev, data);
+ }; // forward events to main thread
+
+
+ observer.on(events["default"].FRAG_DECRYPTED, forwardMessage);
+ observer.on(events["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
+ observer.on(events["default"].FRAG_PARSING_DATA, forwardMessage);
+ observer.on(events["default"].FRAG_PARSED, forwardMessage);
+ observer.on(events["default"].ERROR, forwardMessage);
+ observer.on(events["default"].FRAG_PARSING_METADATA, forwardMessage);
+ observer.on(events["default"].FRAG_PARSING_USERDATA, forwardMessage);
+ observer.on(events["default"].INIT_PTS_FOUND, forwardMessage);
+ var typeSupported = {
+ mp4: demuxer_MediaSource.isTypeSupported('video/mp4'),
+ mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'),
+ mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
+ }; // navigator.vendor is not always available in Web Worker
+ // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
+
+ var vendor = navigator.vendor;
+
+ if (config.enableWorker && typeof Worker !== 'undefined') {
+ logger["logger"].log('demuxing in webworker');
+ var w;
+
+ try {
+ w = this.w = webworkify_webpack(/*require.resolve*/(/*! ../demux/demuxer-worker.js */ "./src/demux/demuxer-worker.js"));
+ this.onwmsg = this.onWorkerMessage.bind(this);
+ w.addEventListener('message', this.onwmsg);
+
+ w.onerror = function (event) {
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].OTHER_ERROR,
+ details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
+ fatal: true,
+ event: 'demuxerWorker',
+ err: {
+ message: event.message + ' (' + event.filename + ':' + event.lineno + ')'
+ }
+ });
+ };
+
+ w.postMessage({
+ cmd: 'init',
+ typeSupported: typeSupported,
+ vendor: vendor,
+ id: id,
+ config: JSON.stringify(config)
+ });
+ } catch (err) {
+ logger["logger"].warn('Error in worker:', err);
+ logger["logger"].error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
+
+ if (w) {
+ // revoke the Object URL that was used to create demuxer worker, so as not to leak it
+ global.URL.revokeObjectURL(w.objectURL);
+ }
+
+ this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
+ this.w = undefined;
+ }
+ } else {
+ this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
+ }
+ }
+
+ var _proto = Demuxer.prototype;
+
+ _proto.destroy = function destroy() {
+ var w = this.w;
+
+ if (w) {
+ w.removeEventListener('message', this.onwmsg);
+ w.terminate();
+ this.w = null;
+ } else {
+ var demuxer = this.demuxer;
+
+ if (demuxer) {
+ demuxer.destroy();
+ this.demuxer = null;
+ }
+ }
+
+ var observer = this.observer;
+
+ if (observer) {
+ observer.removeAllListeners();
+ this.observer = null;
+ }
+ };
+
+ _proto.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
+ var w = this.w;
+ var timeOffset = Object(number["isFiniteNumber"])(frag.startPTS) ? frag.startPTS : frag.start;
+ var decryptdata = frag.decryptdata;
+ var lastFrag = this.frag;
+ var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
+ var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
+ var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
+ var contiguous = !trackSwitch && nextSN;
+
+ if (discontinuity) {
+ logger["logger"].log(this.id + ":discontinuity detected");
+ }
+
+ if (trackSwitch) {
+ logger["logger"].log(this.id + ":switch detected");
+ }
+
+ this.frag = frag;
+
+ if (w) {
+ // post fragment payload as transferable objects for ArrayBuffer (no copy)
+ w.postMessage({
+ cmd: 'demux',
+ data: data,
+ decryptdata: decryptdata,
+ initSegment: initSegment,
+ audioCodec: audioCodec,
+ videoCodec: videoCodec,
+ timeOffset: timeOffset,
+ discontinuity: discontinuity,
+ trackSwitch: trackSwitch,
+ contiguous: contiguous,
+ duration: duration,
+ accurateTimeOffset: accurateTimeOffset,
+ defaultInitPTS: defaultInitPTS
+ }, data instanceof ArrayBuffer ? [data] : []);
+ } else {
+ var demuxer = this.demuxer;
+
+ if (demuxer) {
+ demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
+ }
+ }
+ };
+
+ _proto.onWorkerMessage = function onWorkerMessage(ev) {
+ var data = ev.data,
+ hls = this.hls;
+
+ switch (data.event) {
+ case 'init':
+ // revoke the Object URL that was used to create demuxer worker, so as not to leak it
+ global.URL.revokeObjectURL(this.w.objectURL);
+ break;
+ // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
+
+ case events["default"].FRAG_PARSING_DATA:
+ data.data.data1 = new Uint8Array(data.data1);
+
+ if (data.data2) {
+ data.data.data2 = new Uint8Array(data.data2);
+ }
+
+ /* falls through */
+
+ default:
+ data.data = data.data || {};
+ data.data.frag = this.frag;
+ data.data.id = this.id;
+ hls.trigger(data.event, data.data);
+ break;
+ }
+ };
+
+ return Demuxer;
+}();
+
+/* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
+// CONCATENATED MODULE: ./src/controller/level-helper.js
+
+
+
+
+
+/**
+ * @module LevelHelper
+ *
+ * Providing methods dealing with playlist sliding and drift
+ *
+ * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
+ *
+ * */
+
+function addGroupId(level, type, id) {
+ switch (type) {
+ case 'audio':
+ if (!level.audioGroupIds) {
+ level.audioGroupIds = [];
+ }
+
+ level.audioGroupIds.push(id);
+ break;
+
+ case 'text':
+ if (!level.textGroupIds) {
+ level.textGroupIds = [];
+ }
+
+ level.textGroupIds.push(id);
+ break;
+ }
+}
+function updatePTS(fragments, fromIdx, toIdx) {
+ var fragFrom = fragments[fromIdx],
+ fragTo = fragments[toIdx],
+ fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
+
+ if (Object(number["isFiniteNumber"])(fragToPTS)) {
+ // update fragment duration.
+ // it helps to fix drifts between playlist reported duration and fragment real duration
+ if (toIdx > fromIdx) {
+ fragFrom.duration = fragToPTS - fragFrom.start;
+
+ if (fragFrom.duration < 0) {
+ logger["logger"].warn("negative duration computed for frag " + fragFrom.sn + ",level " + fragFrom.level + ", there should be some duration drift between playlist and fragment!");
+ }
+ } else {
+ fragTo.duration = fragFrom.start - fragToPTS;
+
+ if (fragTo.duration < 0) {
+ logger["logger"].warn("negative duration computed for frag " + fragTo.sn + ",level " + fragTo.level + ", there should be some duration drift between playlist and fragment!");
+ }
+ }
+ } else {
+ // we dont know startPTS[toIdx]
+ if (toIdx > fromIdx) {
+ var contiguous = fragFrom.cc === fragTo.cc;
+ fragTo.start = fragFrom.start + (contiguous && fragFrom.minEndPTS ? fragFrom.minEndPTS - fragFrom.start : fragFrom.duration);
+ } else {
+ fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
+ }
+ }
+}
+function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
+ // update frag PTS/DTS
+ var maxStartPTS = startPTS;
+ var minEndPTS = endPTS;
+
+ if (Object(number["isFiniteNumber"])(frag.startPTS)) {
+ // delta PTS between audio and video
+ var deltaPTS = Math.abs(frag.startPTS - startPTS);
+
+ if (!Object(number["isFiniteNumber"])(frag.deltaPTS)) {
+ frag.deltaPTS = deltaPTS;
+ } else {
+ frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
+ }
+
+ maxStartPTS = Math.max(startPTS, frag.startPTS);
+ startPTS = Math.min(startPTS, frag.startPTS);
+ minEndPTS = Math.min(endPTS, frag.endPTS);
+ endPTS = Math.max(endPTS, frag.endPTS);
+ startDTS = Math.min(startDTS, frag.startDTS);
+ endDTS = Math.max(endDTS, frag.endDTS);
+ }
+
+ var drift = startPTS - frag.start;
+ frag.start = frag.startPTS = startPTS;
+ frag.maxStartPTS = maxStartPTS;
+ frag.endPTS = endPTS;
+ frag.minEndPTS = minEndPTS;
+ frag.startDTS = startDTS;
+ frag.endDTS = endDTS;
+ frag.duration = endPTS - startPTS;
+ var sn = frag.sn; // exit if sn out of range
+
+ if (!details || sn < details.startSN || sn > details.endSN) {
+ return 0;
+ }
+
+ var fragIdx, fragments, i;
+ fragIdx = sn - details.startSN;
+ fragments = details.fragments; // update frag reference in fragments array
+ // rationale is that fragments array might not contain this frag object.
+ // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
+ // if we don't update frag, we won't be able to propagate PTS info on the playlist
+ // resulting in invalid sliding computation
+
+ fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
+
+ for (i = fragIdx; i > 0; i--) {
+ updatePTS(fragments, i, i - 1);
+ } // adjust fragment PTS/duration from seqnum to last frag
+
+
+ for (i = fragIdx; i < fragments.length - 1; i++) {
+ updatePTS(fragments, i, i + 1);
+ }
+
+ details.PTSKnown = true;
+ return drift;
+}
+function mergeDetails(oldDetails, newDetails) {
+ // potentially retrieve cached initsegment
+ if (newDetails.initSegment && oldDetails.initSegment) {
+ newDetails.initSegment = oldDetails.initSegment;
+ } // check if old/new playlists have fragments in common
+ // loop through overlapping SN and update startPTS , cc, and duration if any found
+
+
+ var ccOffset = 0;
+ var PTSFrag;
+ mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
+ ccOffset = oldFrag.cc - newFrag.cc;
+
+ if (Object(number["isFiniteNumber"])(oldFrag.startPTS)) {
+ newFrag.start = newFrag.startPTS = oldFrag.startPTS;
+ newFrag.endPTS = oldFrag.endPTS;
+ newFrag.duration = oldFrag.duration;
+ newFrag.backtracked = oldFrag.backtracked;
+ newFrag.dropped = oldFrag.dropped;
+ PTSFrag = newFrag;
+ } // PTS is known when there are overlapping segments
+
+
+ newDetails.PTSKnown = true;
+ });
+
+ if (!newDetails.PTSKnown) {
+ return;
+ }
+
+ if (ccOffset) {
+ logger["logger"].log('discontinuity sliding from playlist, take drift into account');
+ var newFragments = newDetails.fragments;
+
+ for (var i = 0; i < newFragments.length; i++) {
+ newFragments[i].cc += ccOffset;
+ }
+ } // if at least one fragment contains PTS info, recompute PTS information for all fragments
+
+
+ if (PTSFrag) {
+ updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
+ } else {
+ // ensure that delta is within oldFragments range
+ // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
+ // in that case we also need to adjust start offset of all fragments
+ adjustSliding(oldDetails, newDetails);
+ } // if we are here, it means we have fragments overlapping between
+ // old and new level. reliable PTS info is thus relying on old level
+
+
+ newDetails.PTSKnown = oldDetails.PTSKnown;
+}
+function mergeSubtitlePlaylists(oldPlaylist, newPlaylist, referenceStart) {
+ if (referenceStart === void 0) {
+ referenceStart = 0;
+ }
+
+ var lastIndex = -1;
+ mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
+ newFrag.start = oldFrag.start;
+ lastIndex = index;
+ });
+ var frags = newPlaylist.fragments;
+
+ if (lastIndex < 0) {
+ frags.forEach(function (frag) {
+ frag.start += referenceStart;
+ });
+ return;
+ }
+
+ for (var i = lastIndex + 1; i < frags.length; i++) {
+ frags[i].start = frags[i - 1].start + frags[i - 1].duration;
+ }
+}
+function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
+ if (!oldPlaylist || !newPlaylist) {
+ return;
+ }
+
+ var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
+ var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
+ var delta = newPlaylist.startSN - oldPlaylist.startSN;
+
+ for (var i = start; i <= end; i++) {
+ var oldFrag = oldPlaylist.fragments[delta + i];
+ var newFrag = newPlaylist.fragments[i];
+
+ if (!oldFrag || !newFrag) {
+ break;
+ }
+
+ intersectionFn(oldFrag, newFrag, i);
+ }
+}
+function adjustSliding(oldPlaylist, newPlaylist) {
+ var delta = newPlaylist.startSN - oldPlaylist.startSN;
+ var oldFragments = oldPlaylist.fragments;
+ var newFragments = newPlaylist.fragments;
+
+ if (delta < 0 || delta > oldFragments.length) {
+ return;
+ }
+
+ for (var i = 0; i < newFragments.length; i++) {
+ newFragments[i].start += oldFragments[delta].start;
+ }
+}
+function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
+ var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
+ var minReloadInterval = reloadInterval / 2;
+
+ if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
+ // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
+ // changed then it MUST wait for a period of one-half the target
+ // duration before retrying.
+ reloadInterval = minReloadInterval;
+ }
+
+ if (lastRequestTime) {
+ reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
+ } // in any case, don't reload more than half of target duration
+
+
+ return Math.round(reloadInterval);
+}
+// CONCATENATED MODULE: ./src/utils/time-ranges.ts
+/**
+ * TimeRanges to string helper
+ */
+var TimeRanges = {
+ toString: function toString(r) {
+ var log = '';
+ var len = r.length;
+
+ for (var i = 0; i < len; i++) {
+ log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
+ }
+
+ return log;
+ }
+};
+/* harmony default export */ var time_ranges = (TimeRanges);
+// CONCATENATED MODULE: ./src/utils/discontinuities.js
+
+
+
+function findFirstFragWithCC(fragments, cc) {
+ var firstFrag = null;
+
+ for (var i = 0; i < fragments.length; i += 1) {
+ var currentFrag = fragments[i];
+
+ if (currentFrag && currentFrag.cc === cc) {
+ firstFrag = currentFrag;
+ break;
+ }
+ }
+
+ return firstFrag;
+}
+function findFragWithCC(fragments, CC) {
+ return binary_search.search(fragments, function (candidate) {
+ if (candidate.cc < CC) {
+ return 1;
+ } else if (candidate.cc > CC) {
+ return -1;
+ } else {
+ return 0;
+ }
+ });
+}
+function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
+ var shouldAlign = false;
+
+ if (lastLevel && lastLevel.details && details) {
+ if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
+ shouldAlign = true;
+ }
+ }
+
+ return shouldAlign;
+} // Find the first frag in the previous level which matches the CC of the first frag of the new level
+
+function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
+ var prevFrags = prevDetails.fragments;
+ var curFrags = curDetails.fragments;
+
+ if (!curFrags.length || !prevFrags.length) {
+ logger["logger"].log('No fragments to align');
+ return;
+ }
+
+ var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
+
+ if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
+ logger["logger"].log('No frag in previous level to align on');
+ return;
+ }
+
+ return prevStartFrag;
+}
+function adjustPts(sliding, details) {
+ details.fragments.forEach(function (frag) {
+ if (frag) {
+ var start = frag.start + sliding;
+ frag.start = frag.startPTS = start;
+ frag.endPTS = start + frag.duration;
+ }
+ });
+ details.PTSKnown = true;
+}
+/**
+ * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
+ * contiguous stream with the last fragments.
+ * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
+ * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
+ * and an extra download.
+ * @param lastFrag
+ * @param lastLevel
+ * @param details
+ */
+
+function alignStream(lastFrag, lastLevel, details) {
+ alignDiscontinuities(lastFrag, details, lastLevel);
+
+ if (!details.PTSKnown && lastLevel) {
+ // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
+ // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
+ // discontinuity sequence.
+ alignPDT(details, lastLevel.details);
+ }
+}
+/**
+ * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
+ * discontinuity sequence.
+ * @param lastLevel - The details of the last loaded level
+ * @param details - The details of the new level
+ */
+
+function alignDiscontinuities(lastFrag, details, lastLevel) {
+ if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
+ var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
+
+ if (referenceFrag) {
+ logger["logger"].log('Adjusting PTS using last level due to CC increase within current level');
+ adjustPts(referenceFrag.start, details);
+ }
+ }
+}
+/**
+ * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
+ * @param details - The details of the new level
+ * @param lastDetails - The details of the last loaded level
+ */
+
+function alignPDT(details, lastDetails) {
+ if (lastDetails && lastDetails.fragments.length) {
+ if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
+ return;
+ } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
+ // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
+ // then we can deduce that playlist B sliding is 1000+8 = 1008s
+
+
+ var lastPDT = lastDetails.fragments[0].programDateTime;
+ var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
+
+ var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
+
+ if (Object(number["isFiniteNumber"])(sliding)) {
+ logger["logger"].log("adjusting PTS using programDateTime delta, sliding:" + sliding.toFixed(3));
+ adjustPts(sliding, details);
+ }
+ }
+}
+// CONCATENATED MODULE: ./src/controller/fragment-finders.ts
+
+
+
+/**
+ * Returns first fragment whose endPdt value exceeds the given PDT.
+ * @param {Array<Fragment>} fragments - The array of candidate fragments
+ * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
+ * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
+ * @returns {*|null} fragment - The best matching fragment
+ */
+function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
+ if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(number["isFiniteNumber"])(PDTValue)) {
+ return null;
+ } // if less than start
+
+
+ var startPDT = fragments[0].programDateTime;
+
+ if (PDTValue < (startPDT || 0)) {
+ return null;
+ }
+
+ var endPDT = fragments[fragments.length - 1].endProgramDateTime;
+
+ if (PDTValue >= (endPDT || 0)) {
+ return null;
+ }
+
+ maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
+
+ for (var seg = 0; seg < fragments.length; ++seg) {
+ var frag = fragments[seg];
+
+ if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
+ return frag;
+ }
+ }
+
+ return null;
+}
+/**
+ * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
+ * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
+ * breaking any traps which would cause the same fragment to be continuously selected within a small range.
+ * @param {*} fragPrevious - The last frag successfully appended
+ * @param {Array<Fragment>} fragments - The array of candidate fragments
+ * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
+ * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
+ * @returns {*} foundFrag - The best matching fragment
+ */
+
+function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
+ if (bufferEnd === void 0) {
+ bufferEnd = 0;
+ }
+
+ if (maxFragLookUpTolerance === void 0) {
+ maxFragLookUpTolerance = 0;
+ }
+
+ var fragNext = null;
+
+ if (fragPrevious) {
+ fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1];
+ } else if (bufferEnd === 0 && fragments[0].start === 0) {
+ fragNext = fragments[0];
+ } // Prefer the next fragment if it's within tolerance
+
+
+ if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
+ return fragNext;
+ } // We might be seeking past the tolerance so find the best match
+
+
+ var foundFragment = binary_search.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
+
+ if (foundFragment) {
+ return foundFragment;
+ } // If no match was found return the next fragment after fragPrevious, or null
+
+
+ return fragNext;
+}
+/**
+ * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
+ * @param {*} candidate - The fragment to test
+ * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
+ * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
+ * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
+ */
+
+function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
+ if (bufferEnd === void 0) {
+ bufferEnd = 0;
+ }
+
+ if (maxFragLookUpTolerance === void 0) {
+ maxFragLookUpTolerance = 0;
+ }
+
+ // offset should be within fragment boundary - config.maxFragLookUpTolerance
+ // this is to cope with situations like
+ // bufferEnd = 9.991
+ // frag[Ø] : [0,10]
+ // frag[1] : [10,20]
+ // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
+ // frag start frag start+duration
+ // |-----------------------------|
+ // <---> <--->
+ // ...--------><-----------------------------><---------....
+ // previous frag matching fragment next frag
+ // return -1 return 0 return 1
+ // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
+ // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
+ var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
+
+ if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
+ return 1;
+ } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
+ // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
+ return -1;
+ }
+
+ return 0;
+}
+/**
+ * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
+ * This function tests the candidate's program date time values, as represented in Unix time
+ * @param {*} candidate - The fragment to test
+ * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
+ * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
+ * @returns {boolean} True if contiguous, false otherwise
+ */
+
+function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
+ var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
+
+ var endProgramDateTime = candidate.endProgramDateTime || 0;
+ return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
+}
+// CONCATENATED MODULE: ./src/controller/gap-controller.js
+
+
+
+
+var STALL_MINIMUM_DURATION_MS = 250;
+var MAX_START_GAP_JUMP = 2.0;
+var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
+var SKIP_BUFFER_RANGE_START = 0.05;
+
+var gap_controller_GapController = /*#__PURE__*/function () {
+ function GapController(config, media, fragmentTracker, hls) {
+ this.config = config;
+ this.media = media;
+ this.fragmentTracker = fragmentTracker;
+ this.hls = hls;
+ this.nudgeRetry = 0;
+ this.stallReported = false;
+ this.stalled = null;
+ this.moved = false;
+ this.seeking = false;
+ }
+ /**
+ * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
+ * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
+ *
+ * @param {number} lastCurrentTime Previously read playhead position
+ */
+
+
+ var _proto = GapController.prototype;
+
+ _proto.poll = function poll(lastCurrentTime) {
+ var config = this.config,
+ media = this.media,
+ stalled = this.stalled;
+ var currentTime = media.currentTime,
+ seeking = media.seeking;
+ var seeked = this.seeking && !seeking;
+ var beginSeek = !this.seeking && seeking;
+ this.seeking = seeking; // The playhead is moving, no-op
+
+ if (currentTime !== lastCurrentTime) {
+ this.moved = true;
+
+ if (stalled !== null) {
+ // The playhead is now moving, but was previously stalled
+ if (this.stallReported) {
+ var _stalledDuration = self.performance.now() - stalled;
+
+ logger["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
+ this.stallReported = false;
+ }
+
+ this.stalled = null;
+ this.nudgeRetry = 0;
+ }
+
+ return;
+ } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
+
+
+ if (beginSeek || seeked) {
+ this.stalled = null;
+ } // The playhead should not be moving
+
+
+ if (media.paused || media.ended || media.playbackRate === 0 || !media.buffered.length) {
+ return;
+ }
+
+ var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
+ var isBuffered = bufferInfo.len > 0;
+ var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (waiting for buffer append)
+
+ if (!isBuffered && !nextStart) {
+ return;
+ }
+
+ if (seeking) {
+ // Waiting for seeking in a buffered range to complete
+ var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
+
+ var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
+
+ if (hasEnoughBuffer || noBufferGap) {
+ return;
+ } // Reset moved state when seeking to a point in or before a gap
+
+
+ this.moved = false;
+ } // Skip start gaps if we haven't played, but the last poll detected the start of a stall
+ // The addition poll gives the browser a chance to jump the gap for us
+
+
+ if (!this.moved && this.stalled) {
+ // Jump start gaps within jump threshold
+ var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
+
+ if (startJump > 0 && startJump <= MAX_START_GAP_JUMP) {
+ this._trySkipBufferHole(null);
+
+ return;
+ }
+ } // Start tracking stall time
+
+
+ var tnow = self.performance.now();
+
+ if (stalled === null) {
+ this.stalled = tnow;
+ return;
+ }
+
+ var stalledDuration = tnow - stalled;
+
+ if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
+ // Report stalling after trying to fix
+ this._reportStall(bufferInfo.len);
+ }
+
+ var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
+
+ this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
+ }
+ /**
+ * Detects and attempts to fix known buffer stalling issues.
+ * @param bufferInfo - The properties of the current buffer.
+ * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
+ * @private
+ */
+ ;
+
+ _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
+ var config = this.config,
+ fragmentTracker = this.fragmentTracker,
+ media = this.media;
+ var currentTime = media.currentTime;
+ var partial = fragmentTracker.getPartialFragment(currentTime);
+
+ if (partial) {
+ // Try to skip over the buffer hole caused by a partial fragment
+ // This method isn't limited by the size of the gap between buffered ranges
+ var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
+ // the branch below only executes when we don't handle a partial fragment
+
+
+ if (targetTime) {
+ return;
+ }
+ } // if we haven't had to skip over a buffer hole of a partial fragment
+ // we may just have to "nudge" the playlist as the browser decoding/rendering engine
+ // needs to cross some sort of threshold covering all source-buffers content
+ // to start playing properly.
+
+
+ if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
+ logger["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
+ // We only try to jump the hole if it's under the configured size
+ // Reset stalled so to rearm watchdog timer
+
+ this.stalled = null;
+
+ this._tryNudgeBuffer();
+ }
+ }
+ /**
+ * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
+ * @param bufferLen - The playhead distance from the end of the current buffer segment.
+ * @private
+ */
+ ;
+
+ _proto._reportStall = function _reportStall(bufferLen) {
+ var hls = this.hls,
+ media = this.media,
+ stallReported = this.stallReported;
+
+ if (!stallReported) {
+ // Report stalled error once
+ this.stallReported = true;
+ logger["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
+ fatal: false,
+ buffer: bufferLen
+ });
+ }
+ }
+ /**
+ * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
+ * @param partial - The partial fragment found at the current time (where playback is stalling).
+ * @private
+ */
+ ;
+
+ _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
+ var config = this.config,
+ hls = this.hls,
+ media = this.media;
+ var currentTime = media.currentTime;
+ var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
+
+ for (var i = 0; i < media.buffered.length; i++) {
+ var startTime = media.buffered.start(i);
+
+ if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
+ var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
+ logger["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
+ this.moved = true;
+ this.stalled = null;
+ media.currentTime = targetTime;
+
+ if (partial) {
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
+ fatal: false,
+ reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
+ frag: partial
+ });
+ }
+
+ return targetTime;
+ }
+
+ lastEndTime = media.buffered.end(i);
+ }
+
+ return 0;
+ }
+ /**
+ * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
+ * @private
+ */
+ ;
+
+ _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
+ var config = this.config,
+ hls = this.hls,
+ media = this.media;
+ var currentTime = media.currentTime;
+ var nudgeRetry = (this.nudgeRetry || 0) + 1;
+ this.nudgeRetry = nudgeRetry;
+
+ if (nudgeRetry < config.nudgeMaxRetry) {
+ var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
+
+ logger["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
+ media.currentTime = targetTime;
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
+ fatal: false
+ });
+ } else {
+ logger["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
+ fatal: true
+ });
+ }
+ };
+
+ return GapController;
+}();
+
+
+// CONCATENATED MODULE: ./src/task-loop.ts
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function task_loop_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+/**
+ * Sub-class specialization of EventHandler base class.
+ *
+ * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
+ * scheduled asynchroneously, avoiding recursive calls in the same tick.
+ *
+ * The task itself is implemented in `doTick`. It can be requested and called for single execution
+ * using the `tick` method.
+ *
+ * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
+ * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
+ *
+ * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
+ * and cancelled with `clearNextTick`.
+ *
+ * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
+ *
+ * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
+ *
+ * Further explanations:
+ *
+ * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
+ * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
+ *
+ * When the task execution (`tick` method) is called in re-entrant way this is detected and
+ * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
+ * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
+ */
+var TaskLoop = /*#__PURE__*/function (_EventHandler) {
+ task_loop_inheritsLoose(TaskLoop, _EventHandler);
+
+ function TaskLoop(hls) {
+ var _this;
+
+ for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ events[_key - 1] = arguments[_key];
+ }
+
+ _this = _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)) || this;
+ _this._boundTick = void 0;
+ _this._tickTimer = null;
+ _this._tickInterval = null;
+ _this._tickCallCount = 0;
+ _this._boundTick = _this.tick.bind(_assertThisInitialized(_this));
+ return _this;
+ }
+ /**
+ * @override
+ */
+
+
+ var _proto = TaskLoop.prototype;
+
+ _proto.onHandlerDestroying = function onHandlerDestroying() {
+ // clear all timers before unregistering from event bus
+ this.clearNextTick();
+ this.clearInterval();
+ }
+ /**
+ * @returns {boolean}
+ */
+ ;
+
+ _proto.hasInterval = function hasInterval() {
+ return !!this._tickInterval;
+ }
+ /**
+ * @returns {boolean}
+ */
+ ;
+
+ _proto.hasNextTick = function hasNextTick() {
+ return !!this._tickTimer;
+ }
+ /**
+ * @param {number} millis Interval time (ms)
+ * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
+ */
+ ;
+
+ _proto.setInterval = function setInterval(millis) {
+ if (!this._tickInterval) {
+ this._tickInterval = self.setInterval(this._boundTick, millis);
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * @returns {boolean} True when interval was cleared, false when none was set (no effect)
+ */
+ ;
+
+ _proto.clearInterval = function clearInterval() {
+ if (this._tickInterval) {
+ self.clearInterval(this._tickInterval);
+ this._tickInterval = null;
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
+ */
+ ;
+
+ _proto.clearNextTick = function clearNextTick() {
+ if (this._tickTimer) {
+ self.clearTimeout(this._tickTimer);
+ this._tickTimer = null;
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Will call the subclass doTick implementation in this main loop tick
+ * or in the next one (via setTimeout(,0)) in case it has already been called
+ * in this tick (in case this is a re-entrant call).
+ */
+ ;
+
+ _proto.tick = function tick() {
+ this._tickCallCount++;
+
+ if (this._tickCallCount === 1) {
+ this.doTick(); // re-entrant call to tick from previous doTick call stack
+ // -> schedule a call on the next main loop iteration to process this task processing request
+
+ if (this._tickCallCount > 1) {
+ // make sure only one timer exists at any time at max
+ this.clearNextTick();
+ this._tickTimer = self.setTimeout(this._boundTick, 0);
+ }
+
+ this._tickCallCount = 0;
+ }
+ }
+ /**
+ * For subclass to implement task logic
+ * @abstract
+ */
+ ;
+
+ _proto.doTick = function doTick() {};
+
+ return TaskLoop;
+}(event_handler);
+
+
+// CONCATENATED MODULE: ./src/controller/base-stream-controller.js
+
+
+function base_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+
+
+var State = {
+ STOPPED: 'STOPPED',
+ STARTING: 'STARTING',
+ IDLE: 'IDLE',
+ PAUSED: 'PAUSED',
+ KEY_LOADING: 'KEY_LOADING',
+ FRAG_LOADING: 'FRAG_LOADING',
+ FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
+ WAITING_TRACK: 'WAITING_TRACK',
+ PARSING: 'PARSING',
+ PARSED: 'PARSED',
+ BUFFER_FLUSHING: 'BUFFER_FLUSHING',
+ ENDED: 'ENDED',
+ ERROR: 'ERROR',
+ WAITING_INIT_PTS: 'WAITING_INIT_PTS',
+ WAITING_LEVEL: 'WAITING_LEVEL'
+};
+
+var base_stream_controller_BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
+ base_stream_controller_inheritsLoose(BaseStreamController, _TaskLoop);
+
+ function BaseStreamController() {
+ return _TaskLoop.apply(this, arguments) || this;
+ }
+
+ var _proto = BaseStreamController.prototype;
+
+ _proto.doTick = function doTick() {};
+
+ _proto.startLoad = function startLoad() {};
+
+ _proto.stopLoad = function stopLoad() {
+ var frag = this.fragCurrent;
+
+ if (frag) {
+ if (frag.loader) {
+ frag.loader.abort();
+ }
+
+ this.fragmentTracker.removeFragment(frag);
+ }
+
+ if (this.demuxer) {
+ this.demuxer.destroy();
+ this.demuxer = null;
+ }
+
+ this.fragCurrent = null;
+ this.fragPrevious = null;
+ this.clearInterval();
+ this.clearNextTick();
+ this.state = State.STOPPED;
+ };
+
+ _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
+ var fragCurrent = this.fragCurrent,
+ fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
+ // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
+ // so we should not switch to ENDED in that case, to be able to buffer them
+ // dont switch to ENDED if we need to backtrack last fragment
+
+ if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
+ var fragState = fragmentTracker.getState(fragCurrent);
+ return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;
+ }
+
+ return false;
+ };
+
+ _proto.onMediaSeeking = function onMediaSeeking() {
+ var config = this.config,
+ media = this.media,
+ mediaBuffer = this.mediaBuffer,
+ state = this.state;
+ var currentTime = media ? media.currentTime : null;
+ var bufferInfo = BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
+ logger["logger"].log("media seeking to " + (Object(number["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime));
+
+ if (state === State.FRAG_LOADING) {
+ var fragCurrent = this.fragCurrent; // check if we are seeking to a unbuffered area AND if frag loading is in progress
+
+ if (bufferInfo.len === 0 && fragCurrent) {
+ var tolerance = config.maxFragLookUpTolerance;
+ var fragStartOffset = fragCurrent.start - tolerance;
+ var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
+
+ if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
+ if (fragCurrent.loader) {
+ logger["logger"].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
+ fragCurrent.loader.abort();
+ }
+
+ this.fragCurrent = null;
+ this.fragPrevious = null; // switch to IDLE state to load new fragment
+
+ this.state = State.IDLE;
+ } else {
+ logger["logger"].log('seeking outside of buffer but within currently loaded fragment range');
+ }
+ }
+ } else if (state === State.ENDED) {
+ // if seeking to unbuffered area, clean up fragPrevious
+ if (bufferInfo.len === 0) {
+ this.fragPrevious = null;
+ this.fragCurrent = null;
+ } // switch to IDLE state to check for potential new fragment
+
+
+ this.state = State.IDLE;
+ }
+
+ if (media) {
+ this.lastCurrentTime = currentTime;
+ } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
+
+
+ if (!this.loadedmetadata) {
+ this.nextLoadPosition = this.startPosition = currentTime;
+ } // tick to speed up processing
+
+
+ this.tick();
+ };
+
+ _proto.onMediaEnded = function onMediaEnded() {
+ // reset startPosition and lastCurrentTime to restart playback @ stream beginning
+ this.startPosition = this.lastCurrentTime = 0;
+ };
+
+ _proto.onHandlerDestroying = function onHandlerDestroying() {
+ this.stopLoad();
+
+ _TaskLoop.prototype.onHandlerDestroying.call(this);
+ };
+
+ _proto.onHandlerDestroyed = function onHandlerDestroyed() {
+ this.state = State.STOPPED;
+ this.fragmentTracker = null;
+ };
+
+ _proto.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
+ var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
+ return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
+ };
+
+ return BaseStreamController;
+}(TaskLoop);
+
+
+// CONCATENATED MODULE: ./src/controller/stream-controller.js
+
+
+
+
+
+
+
+function stream_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function stream_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) stream_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) stream_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Stream Controller
+*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var TICK_INTERVAL = 100; // how often to tick in ms
+
+var stream_controller_StreamController = /*#__PURE__*/function (_BaseStreamController) {
+ stream_controller_inheritsLoose(StreamController, _BaseStreamController);
+
+ function StreamController(hls, fragmentTracker) {
+ var _this;
+
+ _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_PARSED, events["default"].LEVEL_LOADED, events["default"].LEVELS_UPDATED, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].FRAG_LOAD_EMERGENCY_ABORTED, events["default"].FRAG_PARSING_INIT_SEGMENT, events["default"].FRAG_PARSING_DATA, events["default"].FRAG_PARSED, events["default"].ERROR, events["default"].AUDIO_TRACK_SWITCHING, events["default"].AUDIO_TRACK_SWITCHED, events["default"].BUFFER_CREATED, events["default"].BUFFER_APPENDED, events["default"].BUFFER_FLUSHED) || this;
+ _this.fragmentTracker = fragmentTracker;
+ _this.config = hls.config;
+ _this.audioCodecSwap = false;
+ _this._state = State.STOPPED;
+ _this.stallReported = false;
+ _this.gapController = null;
+ _this.altAudio = false;
+ _this.audioOnly = false;
+ _this.bitrateTest = false;
+ return _this;
+ }
+
+ var _proto = StreamController.prototype;
+
+ _proto.startLoad = function startLoad(startPosition) {
+ if (this.levels) {
+ var lastCurrentTime = this.lastCurrentTime,
+ hls = this.hls;
+ this.stopLoad();
+ this.setInterval(TICK_INTERVAL);
+ this.level = -1;
+ this.fragLoadError = 0;
+
+ if (!this.startFragRequested) {
+ // determine load level
+ var startLevel = hls.startLevel;
+
+ if (startLevel === -1) {
+ if (hls.config.testBandwidth) {
+ // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
+ startLevel = 0;
+ this.bitrateTest = true;
+ } else {
+ startLevel = hls.nextAutoLevel;
+ }
+ } // set new level to playlist loader : this will trigger start level load
+ // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
+
+
+ this.level = hls.nextLoadLevel = startLevel;
+ this.loadedmetadata = false;
+ } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
+
+
+ if (lastCurrentTime > 0 && startPosition === -1) {
+ logger["logger"].log("override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
+ startPosition = lastCurrentTime;
+ }
+
+ this.state = State.IDLE;
+ this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
+ this.tick();
+ } else {
+ this.forceStartLoad = true;
+ this.state = State.STOPPED;
+ }
+ };
+
+ _proto.stopLoad = function stopLoad() {
+ this.forceStartLoad = false;
+
+ _BaseStreamController.prototype.stopLoad.call(this);
+ };
+
+ _proto.doTick = function doTick() {
+ switch (this.state) {
+ case State.BUFFER_FLUSHING:
+ // in buffer flushing state, reset fragLoadError counter
+ this.fragLoadError = 0;
+ break;
+
+ case State.IDLE:
+ this._doTickIdle();
+
+ break;
+
+ case State.WAITING_LEVEL:
+ var level = this.levels[this.level]; // check if playlist is already loaded
+
+ if (level && level.details) {
+ this.state = State.IDLE;
+ }
+
+ break;
+
+ case State.FRAG_LOADING_WAITING_RETRY:
+ var now = window.performance.now();
+ var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
+
+ if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
+ logger["logger"].log('mediaController: retryDate reached, switch back to IDLE state');
+ this.state = State.IDLE;
+ }
+
+ break;
+
+ case State.ERROR:
+ case State.STOPPED:
+ case State.FRAG_LOADING:
+ case State.PARSING:
+ case State.PARSED:
+ case State.ENDED:
+ break;
+
+ default:
+ break;
+ } // check buffer
+
+
+ this._checkBuffer(); // check/update current fragment
+
+
+ this._checkFragmentChanged();
+ } // Ironically the "idle" state is the on we do the most logic in it seems ....
+ // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
+ // played segment, or on pause/play/seek instead of naively checking every 100ms?
+ ;
+
+ _proto._doTickIdle = function _doTickIdle() {
+ var hls = this.hls,
+ config = hls.config,
+ media = this.media; // if start level not parsed yet OR
+ // if video not attached AND start fragment already requested OR start frag prefetch disable
+ // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
+
+ if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
+ return;
+ } // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
+
+
+ if (this.altAudio && this.audioOnly) {
+ // Clear audio demuxer state so when switching back to main audio we're not still appending where we left off
+ this.demuxer.frag = null;
+ return;
+ } // if we have not yet loaded any fragment, start loading from start position
+
+
+ var pos;
+
+ if (this.loadedmetadata) {
+ pos = media.currentTime;
+ } else {
+ pos = this.nextLoadPosition;
+ } // determine next load level
+
+
+ var level = hls.nextLoadLevel,
+ levelInfo = this.levels[level];
+
+ if (!levelInfo) {
+ return;
+ }
+
+ var levelBitrate = levelInfo.bitrate,
+ maxBufLen; // compute max Buffer Length that we could get from this load level, based on level bitrate.
+
+ if (levelBitrate) {
+ maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
+ } else {
+ maxBufLen = config.maxBufferLength;
+ }
+
+ maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); // determine next candidate fragment to be loaded, based on current position and end of buffer position
+ // ensure up to `config.maxMaxBufferLength` of buffer upfront
+
+ var maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;
+ var bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);
+ var bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins
+
+ if (bufferLen >= maxBufLen) {
+ return;
+ } // if buffer length is less than maxBufLen try to load a new fragment ...
+
+
+ logger["logger"].trace("buffer length of " + bufferLen.toFixed(3) + " is below max of " + maxBufLen.toFixed(3) + ". checking for more payload ..."); // set next load level : this will trigger a playlist load if needed
+
+ this.level = hls.nextLoadLevel = level;
+ var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
+ // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
+ // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
+
+ if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
+ this.state = State.WAITING_LEVEL;
+ return;
+ }
+
+ if (this._streamEnded(bufferInfo, levelDetails)) {
+ var data = {};
+
+ if (this.altAudio) {
+ data.type = 'video';
+ }
+
+ this.hls.trigger(events["default"].BUFFER_EOS, data);
+ this.state = State.ENDED;
+ return;
+ } // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
+
+
+ this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
+ };
+
+ _proto._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
+ var fragPrevious = this.fragPrevious,
+ level = this.level,
+ fragments = levelDetails.fragments,
+ fragLen = fragments.length; // empty playlist
+
+ if (fragLen === 0) {
+ return;
+ } // find fragment index, contiguous with end of buffer position
+
+
+ var start = fragments[0].start,
+ end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
+ bufferEnd = bufferInfo.end,
+ frag;
+
+ if (levelDetails.initSegment && !levelDetails.initSegment.data) {
+ frag = levelDetails.initSegment;
+ } else {
+ // in case of live playlist we need to ensure that requested position is not located before playlist start
+ if (levelDetails.live) {
+ var initialLiveManifestSize = this.config.initialLiveManifestSize;
+
+ if (fragLen < initialLiveManifestSize) {
+ logger["logger"].warn("Can not start playback of a level, reason: not enough fragments " + fragLen + " < " + initialLiveManifestSize);
+ return;
+ }
+
+ frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments); // if it explicitely returns null don't load any fragment and exit function now
+
+ if (frag === null) {
+ return;
+ }
+ } else {
+ // VoD playlist: if bufferEnd before start of playlist, load first fragment
+ if (bufferEnd < start) {
+ frag = fragments[0];
+ }
+ }
+ }
+
+ if (!frag) {
+ frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
+ }
+
+ if (frag) {
+ if (frag.encrypted) {
+ this._loadKey(frag, levelDetails);
+ } else {
+ this._loadFragment(frag, levelDetails, pos, bufferEnd);
+ }
+ }
+ };
+
+ _proto._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments) {
+ var config = this.hls.config,
+ media = this.media;
+ var frag; // check if requested position is within seekable boundaries :
+ // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
+
+ var maxLatency = Infinity;
+
+ if (config.liveMaxLatencyDuration !== undefined) {
+ maxLatency = config.liveMaxLatencyDuration;
+ } else if (Object(number["isFiniteNumber"])(config.liveMaxLatencyDurationCount)) {
+ maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;
+ }
+
+ if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
+ var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
+ bufferEnd = liveSyncPosition;
+
+ if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {
+ logger["logger"].log("buffer end: " + bufferEnd.toFixed(3) + " is located too far from the end of live sliding playlist, reset currentTime to : " + liveSyncPosition.toFixed(3));
+ media.currentTime = liveSyncPosition;
+ }
+
+ this.nextLoadPosition = liveSyncPosition;
+ } // if end of buffer greater than live edge, don't load any fragment
+ // this could happen if live playlist intermittently slides in the past.
+ // level 1 loaded [182580161,182580167]
+ // level 1 loaded [182580162,182580169]
+ // Loading 182580168 of [182580162 ,182580169],level 1 ..
+ // Loading 182580169 of [182580162 ,182580169],level 1 ..
+ // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
+ // level 1 loaded [182580164,182580171]
+ //
+ // don't return null in case media not loaded yet (readystate === 0)
+
+
+ if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
+ return null;
+ }
+
+ if (this.startFragRequested && !levelDetails.PTSKnown) {
+ /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
+ try to load frag matching with next SN.
+ even if SN are not synchronized between playlists, loading this frag will help us
+ compute playlist sliding and find the right one after in case it was not the right consecutive one */
+ if (fragPrevious) {
+ if (levelDetails.hasProgramDateTime) {
+ // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
+ logger["logger"].log("live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
+ frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
+ } else {
+ // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
+ var targetSN = fragPrevious.sn + 1;
+
+ if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
+ var fragNext = fragments[targetSN - levelDetails.startSN];
+
+ if (fragPrevious.cc === fragNext.cc) {
+ frag = fragNext;
+ logger["logger"].log("live playlist, switching playlist, load frag with next SN: " + frag.sn);
+ }
+ } // next frag SN not available (or not with same continuity counter)
+ // look for a frag sharing the same CC
+
+
+ if (!frag) {
+ frag = binary_search.search(fragments, function (frag) {
+ return fragPrevious.cc - frag.cc;
+ });
+
+ if (frag) {
+ logger["logger"].log("live playlist, switching playlist, load frag with same CC: " + frag.sn);
+ }
+ }
+ }
+ }
+ }
+
+ return frag;
+ };
+
+ _proto._findFragment = function _findFragment(start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {
+ var config = this.hls.config;
+ var fragNextLoad;
+
+ if (bufferEnd < end) {
+ var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
+ // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
+
+ fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);
+ } else {
+ // reach end of playlist
+ fragNextLoad = fragments[fragmentIndexRange - 1];
+ }
+
+ if (fragNextLoad) {
+ var curSNIdx = fragNextLoad.sn - levelDetails.startSN;
+ var sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;
+ var prevSnFrag = fragments[curSNIdx - 1];
+ var nextSnFrag = fragments[curSNIdx + 1]; // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
+
+ if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {
+ if (sameLevel && !fragNextLoad.backtracked) {
+ if (fragNextLoad.sn < levelDetails.endSN) {
+ var deltaPTS = fragPreviousLoad.deltaPTS; // if there is a significant delta between audio and video, larger than max allowed hole,
+ // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
+ // let's try to load previous fragment again to get last keyframe
+ // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
+
+ if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {
+ fragNextLoad = prevSnFrag;
+ logger["logger"].warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');
+ } else {
+ fragNextLoad = nextSnFrag;
+
+ if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {
+ logger["logger"].log("Re-loading fragment with SN: " + fragNextLoad.sn);
+ }
+ }
+ } else {
+ fragNextLoad = null;
+ }
+ } else if (fragNextLoad.backtracked) {
+ // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
+ if (nextSnFrag && nextSnFrag.backtracked) {
+ logger["logger"].warn("Already backtracked from fragment " + nextSnFrag.sn + ", will not backtrack to fragment " + fragNextLoad.sn + ". Loading fragment " + nextSnFrag.sn);
+ fragNextLoad = nextSnFrag;
+ } else {
+ // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
+ // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
+ logger["logger"].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
+ fragNextLoad.dropped = 0;
+
+ if (prevSnFrag) {
+ fragNextLoad = prevSnFrag;
+ fragNextLoad.backtracked = true;
+ } else if (curSNIdx) {
+ // can't backtrack on very first fragment
+ fragNextLoad = null;
+ }
+ }
+ }
+ }
+ }
+
+ return fragNextLoad;
+ };
+
+ _proto._loadKey = function _loadKey(frag, levelDetails) {
+ logger["logger"].log("Loading key for " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level);
+ this.state = State.KEY_LOADING;
+ this.hls.trigger(events["default"].KEY_LOADING, {
+ frag: frag
+ });
+ };
+
+ _proto._loadFragment = function _loadFragment(frag, levelDetails, pos, bufferEnd) {
+ // Check if fragment is not loaded
+ var fragState = this.fragmentTracker.getState(frag);
+ this.fragCurrent = frag;
+
+ if (frag.sn !== 'initSegment') {
+ this.startFragRequested = true;
+ } // Don't update nextLoadPosition for fragments which are not buffered
+
+
+ if (Object(number["isFiniteNumber"])(frag.sn) && !frag.bitrateTest) {
+ this.nextLoadPosition = frag.start + frag.duration;
+ } // Allow backtracked fragments to load
+
+
+ if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
+ frag.autoLevel = this.hls.autoLevelEnabled;
+ frag.bitrateTest = this.bitrateTest;
+ logger["logger"].log("Loading " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level + ", " + (this.loadedmetadata ? 'currentTime' : 'nextLoadPosition') + ": " + parseFloat(pos.toFixed(3)) + ", bufferEnd: " + parseFloat(bufferEnd.toFixed(3)));
+ this.hls.trigger(events["default"].FRAG_LOADING, {
+ frag: frag
+ }); // lazy demuxer init, as this could take some time ... do it during frag loading
+
+ if (!this.demuxer) {
+ this.demuxer = new demux_demuxer(this.hls, 'main');
+ }
+
+ this.state = State.FRAG_LOADING;
+ } else if (fragState === FragmentState.APPENDING) {
+ // Lower the buffer size and try again
+ if (this._reduceMaxBufferLength(frag.duration)) {
+ this.fragmentTracker.removeFragment(frag);
+ }
+ }
+ };
+
+ _proto.getBufferedFrag = function getBufferedFrag(position) {
+ return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
+ };
+
+ _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
+ if (frag) {
+ // try to get range of next fragment (500ms after this range)
+ return this.getBufferedFrag(frag.endPTS + 0.5);
+ }
+
+ return null;
+ };
+
+ _proto._checkFragmentChanged = function _checkFragmentChanged() {
+ var fragPlayingCurrent,
+ currentTime,
+ video = this.media;
+
+ if (video && video.readyState && video.seeking === false) {
+ currentTime = video.currentTime;
+ /* if video element is in seeked state, currentTime can only increase.
+ (assuming that playback rate is positive ...)
+ As sometimes currentTime jumps back to zero after a
+ media decode error, check this, to avoid seeking back to
+ wrong position after a media decode error
+ */
+
+ if (currentTime > this.lastCurrentTime) {
+ this.lastCurrentTime = currentTime;
+ }
+
+ if (BufferHelper.isBuffered(video, currentTime)) {
+ fragPlayingCurrent = this.getBufferedFrag(currentTime);
+ } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
+ /* ensure that FRAG_CHANGED event is triggered at startup,
+ when first video frame is displayed and playback is paused.
+ add a tolerance of 100ms, in case current position is not buffered,
+ check if current pos+100ms is buffered and use that buffer range
+ for FRAG_CHANGED event reporting */
+ fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
+ }
+
+ if (fragPlayingCurrent) {
+ var fragPlaying = fragPlayingCurrent;
+
+ if (fragPlaying !== this.fragPlaying) {
+ this.hls.trigger(events["default"].FRAG_CHANGED, {
+ frag: fragPlaying
+ });
+ var fragPlayingLevel = fragPlaying.level;
+
+ if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
+ this.hls.trigger(events["default"].LEVEL_SWITCHED, {
+ level: fragPlayingLevel
+ });
+ }
+
+ this.fragPlaying = fragPlaying;
+ }
+ }
+ }
+ }
+ /*
+ on immediate level switch :
+ - pause playback if playing
+ - cancel any pending load request
+ - and trigger a buffer flush
+ */
+ ;
+
+ _proto.immediateLevelSwitch = function immediateLevelSwitch() {
+ logger["logger"].log('immediateLevelSwitch');
+
+ if (!this.immediateSwitch) {
+ this.immediateSwitch = true;
+ var media = this.media,
+ previouslyPaused;
+
+ if (media) {
+ previouslyPaused = media.paused;
+
+ if (!previouslyPaused) {
+ media.pause();
+ }
+ } else {
+ // don't restart playback after instant level switch in case media not attached
+ previouslyPaused = true;
+ }
+
+ this.previouslyPaused = previouslyPaused;
+ }
+
+ var fragCurrent = this.fragCurrent;
+
+ if (fragCurrent && fragCurrent.loader) {
+ fragCurrent.loader.abort();
+ }
+
+ this.fragCurrent = null; // flush everything
+
+ this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
+ }
+ /**
+ * on immediate level switch end, after new fragment has been buffered:
+ * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
+ * - resume the playback if needed
+ */
+ ;
+
+ _proto.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
+ var media = this.media;
+
+ if (media && media.buffered.length) {
+ this.immediateSwitch = false;
+
+ if (media.currentTime > 0 && BufferHelper.isBuffered(media, media.currentTime)) {
+ // only nudge if currentTime is buffered
+ media.currentTime -= 0.0001;
+ }
+
+ if (!this.previouslyPaused) {
+ media.play();
+ }
+ }
+ }
+ /**
+ * try to switch ASAP without breaking video playback:
+ * in order to ensure smooth but quick level switching,
+ * we need to find the next flushable buffer range
+ * we should take into account new segment fetch time
+ */
+ ;
+
+ _proto.nextLevelSwitch = function nextLevelSwitch() {
+ var media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
+
+ if (media && media.readyState) {
+ var fetchdelay;
+ var fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
+
+ if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
+ // flush buffer preceding current fragment (flush until current fragment start offset)
+ // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
+ this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
+ }
+
+ if (!media.paused) {
+ // add a safety delay of 1s
+ var nextLevelId = this.hls.nextLoadLevel,
+ nextLevel = this.levels[nextLevelId],
+ fragLastKbps = this.fragLastKbps;
+
+ if (fragLastKbps && this.fragCurrent) {
+ fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
+ } else {
+ fetchdelay = 0;
+ }
+ } else {
+ fetchdelay = 0;
+ } // logger.log('fetchdelay:'+fetchdelay);
+ // find buffer range that will be reached once new fragment will be fetched
+
+
+ var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
+
+ if (bufferedFrag) {
+ // we can flush buffer range following this one without stalling playback
+ var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
+
+ if (nextBufferedFrag) {
+ // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
+ var fragCurrent = this.fragCurrent;
+
+ if (fragCurrent && fragCurrent.loader) {
+ fragCurrent.loader.abort();
+ }
+
+ this.fragCurrent = null; // start flush position is the start PTS of next buffered frag.
+ // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
+ // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
+
+ var startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));
+ this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
+ }
+ }
+ }
+ };
+
+ _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
+ this.state = State.BUFFER_FLUSHING;
+ var flushScope = {
+ startOffset: startOffset,
+ endOffset: endOffset
+ }; // if alternate audio tracks are used, only flush video, otherwise flush everything
+
+ if (this.altAudio) {
+ flushScope.type = 'video';
+ }
+
+ this.hls.trigger(events["default"].BUFFER_FLUSHING, flushScope);
+ };
+
+ _proto.onMediaAttached = function onMediaAttached(data) {
+ var media = this.media = this.mediaBuffer = data.media;
+ this.onvseeking = this.onMediaSeeking.bind(this);
+ this.onvseeked = this.onMediaSeeked.bind(this);
+ this.onvended = this.onMediaEnded.bind(this);
+ media.addEventListener('seeking', this.onvseeking);
+ media.addEventListener('seeked', this.onvseeked);
+ media.addEventListener('ended', this.onvended);
+ var config = this.config;
+
+ if (this.levels && config.autoStartLoad) {
+ this.hls.startLoad(config.startPosition);
+ }
+
+ this.gapController = new gap_controller_GapController(config, media, this.fragmentTracker, this.hls);
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ var media = this.media;
+
+ if (media && media.ended) {
+ logger["logger"].log('MSE detaching and video ended, reset startPosition');
+ this.startPosition = this.lastCurrentTime = 0;
+ } // reset fragment backtracked flag
+
+
+ var levels = this.levels;
+
+ if (levels) {
+ levels.forEach(function (level) {
+ if (level.details) {
+ level.details.fragments.forEach(function (fragment) {
+ fragment.backtracked = undefined;
+ });
+ }
+ });
+ } // remove video listeners
+
+
+ if (media) {
+ media.removeEventListener('seeking', this.onvseeking);
+ media.removeEventListener('seeked', this.onvseeked);
+ media.removeEventListener('ended', this.onvended);
+ this.onvseeking = this.onvseeked = this.onvended = null;
+ }
+
+ this.fragmentTracker.removeAllFragments();
+ this.media = this.mediaBuffer = null;
+ this.loadedmetadata = false;
+ this.stopLoad();
+ };
+
+ _proto.onMediaSeeked = function onMediaSeeked() {
+ var media = this.media;
+ var currentTime = media ? media.currentTime : undefined;
+
+ if (Object(number["isFiniteNumber"])(currentTime)) {
+ logger["logger"].log("media seeked to " + currentTime.toFixed(3));
+ } // tick to speed up FRAGMENT_PLAYING triggering
+
+
+ this.tick();
+ };
+
+ _proto.onManifestLoading = function onManifestLoading() {
+ // reset buffer on manifest loading
+ logger["logger"].log('trigger BUFFER_RESET');
+ this.hls.trigger(events["default"].BUFFER_RESET);
+ this.fragmentTracker.removeAllFragments();
+ this.stalled = false;
+ this.startPosition = this.lastCurrentTime = 0;
+ };
+
+ _proto.onManifestParsed = function onManifestParsed(data) {
+ var aac = false,
+ heaac = false,
+ codec;
+ data.levels.forEach(function (level) {
+ // detect if we have different kind of audio codecs used amongst playlists
+ codec = level.audioCodec;
+
+ if (codec) {
+ if (codec.indexOf('mp4a.40.2') !== -1) {
+ aac = true;
+ }
+
+ if (codec.indexOf('mp4a.40.5') !== -1) {
+ heaac = true;
+ }
+ }
+ });
+ this.audioCodecSwitch = aac && heaac;
+
+ if (this.audioCodecSwitch) {
+ logger["logger"].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
+ }
+
+ this.altAudio = data.altAudio;
+ this.levels = data.levels;
+ this.startFragRequested = false;
+ var config = this.config;
+
+ if (config.autoStartLoad || this.forceStartLoad) {
+ this.hls.startLoad(config.startPosition);
+ }
+ };
+
+ _proto.onLevelLoaded = function onLevelLoaded(data) {
+ var newDetails = data.details;
+ var newLevelId = data.level;
+ var lastLevel = this.levels[this.levelLastLoaded];
+ var curLevel = this.levels[newLevelId];
+ var duration = newDetails.totalduration;
+ var sliding = 0;
+ logger["logger"].log("level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
+
+ if (newDetails.live || curLevel.details && curLevel.details.live) {
+ var curDetails = curLevel.details;
+
+ if (curDetails && newDetails.fragments.length > 0) {
+ // we already have details for that level, merge them
+ mergeDetails(curDetails, newDetails);
+ sliding = newDetails.fragments[0].start;
+ this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
+
+ if (newDetails.PTSKnown && Object(number["isFiniteNumber"])(sliding)) {
+ logger["logger"].log("live playlist sliding:" + sliding.toFixed(3));
+ } else {
+ logger["logger"].log('live playlist - outdated PTS, unknown sliding');
+ alignStream(this.fragPrevious, lastLevel, newDetails);
+ }
+ } else {
+ logger["logger"].log('live playlist - first load, unknown sliding');
+ newDetails.PTSKnown = false;
+ alignStream(this.fragPrevious, lastLevel, newDetails);
+ }
+ } else {
+ newDetails.PTSKnown = false;
+ } // override level info
+
+
+ curLevel.details = newDetails;
+ this.levelLastLoaded = newLevelId;
+ this.hls.trigger(events["default"].LEVEL_UPDATED, {
+ details: newDetails,
+ level: newLevelId
+ });
+
+ if (this.startFragRequested === false) {
+ // compute start position if set to -1. use it straight away if value is defined
+ if (this.startPosition === -1 || this.lastCurrentTime === -1) {
+ // first, check if start time offset has been set in playlist, if yes, use this value
+ var startTimeOffset = newDetails.startTimeOffset;
+
+ if (Object(number["isFiniteNumber"])(startTimeOffset)) {
+ if (startTimeOffset < 0) {
+ logger["logger"].log("negative start time offset " + startTimeOffset + ", count from end of last fragment");
+ startTimeOffset = sliding + duration + startTimeOffset;
+ }
+
+ logger["logger"].log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
+ this.startPosition = startTimeOffset;
+ } else {
+ // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
+ if (newDetails.live) {
+ this.startPosition = this.computeLivePosition(sliding, newDetails);
+ logger["logger"].log("configure startPosition to " + this.startPosition);
+ } else {
+ this.startPosition = 0;
+ }
+ }
+
+ this.lastCurrentTime = this.startPosition;
+ }
+
+ this.nextLoadPosition = this.startPosition;
+ } // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
+
+
+ if (this.state === State.WAITING_LEVEL) {
+ this.state = State.IDLE;
+ } // trigger handler right now
+
+
+ this.tick();
+ };
+
+ _proto.onKeyLoaded = function onKeyLoaded() {
+ if (this.state === State.KEY_LOADING) {
+ this.state = State.IDLE;
+ this.tick();
+ }
+ };
+
+ _proto.onFragLoaded = function onFragLoaded(data) {
+ var fragCurrent = this.fragCurrent,
+ hls = this.hls,
+ levels = this.levels,
+ media = this.media;
+ var fragLoaded = data.frag;
+
+ if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
+ var stats = data.stats;
+ var currentLevel = levels[fragCurrent.level];
+ var details = currentLevel.details; // reset frag bitrate test in any case after frag loaded event
+ // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
+ // then this means that we should be able to load a fragment at a higher quality level
+
+ this.bitrateTest = false;
+ this.stats = stats;
+ logger["logger"].log("Loaded " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level);
+
+ if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
+ // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
+ this.state = State.IDLE;
+ this.startFragRequested = false;
+ stats.tparsed = stats.tbuffered = window.performance.now();
+ hls.trigger(events["default"].FRAG_BUFFERED, {
+ stats: stats,
+ frag: fragCurrent,
+ id: 'main'
+ });
+ this.tick();
+ } else if (fragLoaded.sn === 'initSegment') {
+ this.state = State.IDLE;
+ stats.tparsed = stats.tbuffered = window.performance.now();
+ details.initSegment.data = data.payload;
+ hls.trigger(events["default"].FRAG_BUFFERED, {
+ stats: stats,
+ frag: fragCurrent,
+ id: 'main'
+ });
+ this.tick();
+ } else {
+ logger["logger"].log("Parsing " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level + ", cc " + fragCurrent.cc);
+ this.state = State.PARSING;
+ this.pendingBuffering = true;
+ this.appended = false; // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
+ // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
+
+ if (fragLoaded.bitrateTest) {
+ fragLoaded.bitrateTest = false;
+ this.fragmentTracker.onFragLoaded({
+ frag: fragLoaded
+ });
+ } // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
+
+
+ var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
+ var initSegmentData = details.initSegment ? details.initSegment.data : [];
+
+ var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
+
+
+ var demuxer = this.demuxer = this.demuxer || new demux_demuxer(this.hls, 'main');
+ demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
+ }
+ }
+
+ this.fragLoadError = 0;
+ };
+
+ _proto.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
+ var tracks = data.tracks,
+ trackName,
+ track;
+ this.audioOnly = tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
+
+ if (this.altAudio && !this.audioOnly) {
+ delete tracks.audio;
+ } // include levelCodec in audio and video tracks
+
+
+ track = tracks.audio;
+
+ if (track) {
+ var audioCodec = this.levels[this.level].audioCodec,
+ ua = navigator.userAgent.toLowerCase();
+
+ if (audioCodec && this.audioCodecSwap) {
+ logger["logger"].log('swapping playlist audio codec');
+
+ if (audioCodec.indexOf('mp4a.40.5') !== -1) {
+ audioCodec = 'mp4a.40.2';
+ } else {
+ audioCodec = 'mp4a.40.5';
+ }
+ } // in case AAC and HE-AAC audio codecs are signalled in manifest
+ // force HE-AAC , as it seems that most browsers prefers that way,
+ // except for mono streams OR on FF
+ // these conditions might need to be reviewed ...
+
+
+ if (this.audioCodecSwitch) {
+ // don't force HE-AAC if mono stream
+ if (track.metadata.channelCount !== 1 && // don't force HE-AAC if firefox
+ ua.indexOf('firefox') === -1) {
+ audioCodec = 'mp4a.40.5';
+ }
+ } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
+
+
+ if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
+ // Exclude mpeg audio
+ audioCodec = 'mp4a.40.2';
+ logger["logger"].log("Android: force audio codec to " + audioCodec);
+ }
+
+ track.levelCodec = audioCodec;
+ track.id = data.id;
+ }
+
+ track = tracks.video;
+
+ if (track) {
+ track.levelCodec = this.levels[this.level].videoCodec;
+ track.id = data.id;
+ }
+
+ this.hls.trigger(events["default"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
+
+ for (trackName in tracks) {
+ track = tracks[trackName];
+ logger["logger"].log("main track:" + trackName + ",container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
+ var initSegment = track.initSegment;
+
+ if (initSegment) {
+ this.appended = true; // arm pending Buffering flag before appending a segment
+
+ this.pendingBuffering = true;
+ this.hls.trigger(events["default"].BUFFER_APPENDING, {
+ type: trackName,
+ data: initSegment,
+ parent: 'main',
+ content: 'initSegment'
+ });
+ }
+ } // trigger handler right now
+
+
+ this.tick();
+ }
+ };
+
+ _proto.onFragParsingData = function onFragParsingData(data) {
+ var _this2 = this;
+
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
+ this.state === State.PARSING) {
+ var level = this.levels[this.level],
+ frag = fragCurrent;
+
+ if (!Object(number["isFiniteNumber"])(data.endPTS)) {
+ data.endPTS = data.startPTS + fragCurrent.duration;
+ data.endDTS = data.startDTS + fragCurrent.duration;
+ }
+
+ if (data.hasAudio === true) {
+ frag.addElementaryStream(ElementaryStreamTypes.AUDIO);
+ }
+
+ if (data.hasVideo === true) {
+ frag.addElementaryStream(ElementaryStreamTypes.VIDEO);
+ }
+
+ logger["logger"].log("Parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb + ",dropped:" + (data.dropped || 0)); // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
+
+ if (data.type === 'video') {
+ frag.dropped = data.dropped;
+
+ if (frag.dropped) {
+ if (!frag.backtracked) {
+ var levelDetails = level.details;
+
+ if (levelDetails && frag.sn === levelDetails.startSN) {
+ logger["logger"].warn('missing video frame(s) on first frag, appending with gap', frag.sn);
+ } else {
+ logger["logger"].warn('missing video frame(s), backtracking fragment', frag.sn); // Return back to the IDLE state without appending to buffer
+ // Causes findFragments to backtrack a segment and find the keyframe
+ // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
+
+ this.fragmentTracker.removeFragment(frag);
+ frag.backtracked = true;
+ this.nextLoadPosition = data.startPTS;
+ this.state = State.IDLE;
+ this.fragPrevious = frag;
+
+ if (this.demuxer) {
+ this.demuxer.destroy();
+ this.demuxer = null;
+ }
+
+ this.tick();
+ return;
+ }
+ } else {
+ logger["logger"].warn('Already backtracked on this fragment, appending with the gap', frag.sn);
+ }
+ } else {
+ // Only reset the backtracked flag if we've loaded the frag without any dropped frames
+ frag.backtracked = false;
+ }
+ }
+
+ var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
+ hls = this.hls;
+ hls.trigger(events["default"].LEVEL_PTS_UPDATED, {
+ details: level.details,
+ level: this.level,
+ drift: drift,
+ type: data.type,
+ start: data.startPTS,
+ end: data.endPTS
+ }); // has remuxer dropped video frames located before first keyframe ?
+
+ [data.data1, data.data2].forEach(function (buffer) {
+ // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
+ // in that case it is useless to append following segments
+ if (buffer && buffer.length && _this2.state === State.PARSING) {
+ _this2.appended = true; // arm pending Buffering flag before appending a segment
+
+ _this2.pendingBuffering = true;
+ hls.trigger(events["default"].BUFFER_APPENDING, {
+ type: data.type,
+ data: buffer,
+ parent: 'main',
+ content: 'data'
+ });
+ }
+ }); // trigger handler right now
+
+ this.tick();
+ }
+ };
+
+ _proto.onFragParsed = function onFragParsed(data) {
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
+ this.stats.tparsed = window.performance.now();
+ this.state = State.PARSED;
+
+ this._checkAppendedParsed();
+ }
+ };
+
+ _proto.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
+ // if any URL found on new audio track, it is an alternate audio track
+ var fromAltAudio = this.altAudio;
+ var altAudio = !!data.url;
+ var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
+ // don't do anything if we switch to alt audio: audio stream controller is handling it.
+ // we will just have to change buffer scheduling on audioTrackSwitched
+
+ if (!altAudio) {
+ if (this.mediaBuffer !== this.media) {
+ logger["logger"].log('switching on main audio, use media.buffered to schedule main fragment loading');
+ this.mediaBuffer = this.media;
+ var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
+
+ if (fragCurrent.loader) {
+ logger["logger"].log('switching to main audio track, cancel main fragment load');
+ fragCurrent.loader.abort();
+ }
+
+ this.fragCurrent = null;
+ this.fragPrevious = null; // destroy demuxer to force init segment generation (following audio switch)
+
+ if (this.demuxer) {
+ this.demuxer.destroy();
+ this.demuxer = null;
+ } // switch to IDLE state to load new fragment
+
+
+ this.state = State.IDLE;
+ }
+
+ var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
+
+ if (fromAltAudio) {
+ hls.trigger(events["default"].BUFFER_FLUSHING, {
+ startOffset: 0,
+ endOffset: Number.POSITIVE_INFINITY,
+ type: 'audio'
+ });
+ }
+
+ hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
+ id: trackId
+ });
+ }
+ };
+
+ _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
+ var trackId = data.id,
+ altAudio = !!this.hls.audioTracks[trackId].url;
+
+ if (altAudio) {
+ var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
+
+ if (videoBuffer && this.mediaBuffer !== videoBuffer) {
+ logger["logger"].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
+ this.mediaBuffer = videoBuffer;
+ }
+ }
+
+ this.altAudio = altAudio;
+ this.tick();
+ };
+
+ _proto.onBufferCreated = function onBufferCreated(data) {
+ var tracks = data.tracks,
+ mediaTrack,
+ name,
+ alternate = false;
+
+ for (var type in tracks) {
+ var track = tracks[type];
+
+ if (track.id === 'main') {
+ name = type;
+ mediaTrack = track; // keep video source buffer reference
+
+ if (type === 'video') {
+ this.videoBuffer = tracks[type].buffer;
+ }
+ } else {
+ alternate = true;
+ }
+ }
+
+ if (alternate && mediaTrack) {
+ logger["logger"].log("alternate track found, use " + name + ".buffered to schedule main fragment loading");
+ this.mediaBuffer = mediaTrack.buffer;
+ } else {
+ this.mediaBuffer = this.media;
+ }
+ };
+
+ _proto.onBufferAppended = function onBufferAppended(data) {
+ if (data.parent === 'main') {
+ var state = this.state;
+
+ if (state === State.PARSING || state === State.PARSED) {
+ // check if all buffers have been appended
+ this.pendingBuffering = data.pending > 0;
+
+ this._checkAppendedParsed();
+ }
+ }
+ };
+
+ _proto._checkAppendedParsed = function _checkAppendedParsed() {
+ // trigger handler right now
+ if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
+ var frag = this.fragCurrent;
+
+ if (frag) {
+ var media = this.mediaBuffer ? this.mediaBuffer : this.media;
+ logger["logger"].log("main buffered : " + time_ranges.toString(media.buffered));
+ this.fragPrevious = frag;
+ var stats = this.stats;
+ stats.tbuffered = window.performance.now(); // we should get rid of this.fragLastKbps
+
+ this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
+ this.hls.trigger(events["default"].FRAG_BUFFERED, {
+ stats: stats,
+ frag: frag,
+ id: 'main'
+ });
+ this.state = State.IDLE;
+ } // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point
+
+
+ if (this.loadedmetadata || this.startPosition <= 0) {
+ this.tick();
+ }
+ }
+ };
+
+ _proto.onError = function onError(data) {
+ var frag = data.frag || this.fragCurrent; // don't handle frag error not related to main fragment
+
+ if (frag && frag.type !== 'main') {
+ return;
+ } // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
+
+
+ var mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
+
+ switch (data.details) {
+ case errors["ErrorDetails"].FRAG_LOAD_ERROR:
+ case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
+ case errors["ErrorDetails"].KEY_LOAD_ERROR:
+ case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
+ if (!data.fatal) {
+ // keep retrying until the limit will be reached
+ if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
+ // exponential backoff capped to config.fragLoadingMaxRetryTimeout
+ var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
+ logger["logger"].warn("mediaController: frag loading failed, retry in " + delay + " ms");
+ this.retryDate = window.performance.now() + delay; // retry loading state
+ // if loadedmetadata is not set, it means that we are emergency switch down on first frag
+ // in that case, reset startFragRequested flag
+
+ if (!this.loadedmetadata) {
+ this.startFragRequested = false;
+ this.nextLoadPosition = this.startPosition;
+ }
+
+ this.fragLoadError++;
+ this.state = State.FRAG_LOADING_WAITING_RETRY;
+ } else {
+ logger["logger"].error("mediaController: " + data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
+
+ data.fatal = true;
+ this.state = State.ERROR;
+ }
+ }
+
+ break;
+
+ case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
+ case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
+ if (this.state !== State.ERROR) {
+ if (data.fatal) {
+ // if fatal error, stop processing
+ this.state = State.ERROR;
+ logger["logger"].warn("streamController: " + data.details + ",switch to " + this.state + " state ...");
+ } else {
+ // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
+ if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
+ this.state = State.IDLE;
+ }
+ }
+ }
+
+ break;
+
+ case errors["ErrorDetails"].BUFFER_FULL_ERROR:
+ // if in appending state
+ if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
+ // reduce max buf len if current position is buffered
+ if (mediaBuffered) {
+ this._reduceMaxBufferLength(this.config.maxBufferLength);
+
+ this.state = State.IDLE;
+ } else {
+ // current position is not buffered, but browser is still complaining about buffer full error
+ // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
+ // in that case flush the whole buffer to recover
+ logger["logger"].warn('buffer full error also media.currentTime is not buffered, flush everything');
+ this.fragCurrent = null; // flush everything
+
+ this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
+ }
+ }
+
+ break;
+
+ default:
+ break;
+ }
+ };
+
+ _proto._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {
+ var config = this.config;
+
+ if (config.maxMaxBufferLength >= minLength) {
+ // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
+ config.maxMaxBufferLength /= 2;
+ logger["logger"].warn("main:reduce max buffer length to " + config.maxMaxBufferLength + "s");
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Checks the health of the buffer and attempts to resolve playback stalls.
+ * @private
+ */
+ ;
+
+ _proto._checkBuffer = function _checkBuffer() {
+ var media = this.media;
+
+ if (!media || media.readyState === 0) {
+ // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
+ return;
+ }
+
+ var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
+ var buffered = mediaBuffer.buffered;
+
+ if (!this.loadedmetadata && buffered.length) {
+ this.loadedmetadata = true;
+
+ this._seekToStartPos();
+ } else if (this.immediateSwitch) {
+ this.immediateLevelSwitchEnd();
+ } else {
+ this.gapController.poll(this.lastCurrentTime, buffered);
+ }
+ };
+
+ _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
+ this.state = State.IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
+ // in that case, reset startFragRequested flag
+
+ if (!this.loadedmetadata) {
+ this.startFragRequested = false;
+ this.nextLoadPosition = this.startPosition;
+ }
+
+ this.tick();
+ };
+
+ _proto.onBufferFlushed = function onBufferFlushed() {
+ /* after successful buffer flushing, filter flushed fragments from bufferedFrags
+ use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
+ */
+ var media = this.mediaBuffer ? this.mediaBuffer : this.media;
+
+ if (media) {
+ // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
+ var elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
+ this.fragmentTracker.detectEvictedFragments(elementaryStreamType, media.buffered);
+ } // move to IDLE once flush complete. this should trigger new fragment loading
+
+
+ this.state = State.IDLE; // reset reference to frag
+
+ this.fragPrevious = null;
+ };
+
+ _proto.onLevelsUpdated = function onLevelsUpdated(data) {
+ this.levels = data.levels;
+ };
+
+ _proto.swapAudioCodec = function swapAudioCodec() {
+ this.audioCodecSwap = !this.audioCodecSwap;
+ }
+ /**
+ * Seeks to the set startPosition if not equal to the mediaElement's current time.
+ * @private
+ */
+ ;
+
+ _proto._seekToStartPos = function _seekToStartPos() {
+ var media = this.media;
+ var currentTime = media.currentTime;
+ var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
+ // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
+
+ if (currentTime !== startPosition && startPosition >= 0) {
+ if (media.seeking) {
+ logger["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
+ return;
+ }
+
+ var bufferStart = media.buffered.length ? media.buffered.start(0) : 0;
+ var delta = bufferStart - startPosition;
+
+ if (delta > 0 && delta < this.config.maxBufferHole) {
+ logger["logger"].log("adjusting start position by " + delta + " to match buffer start");
+ startPosition += delta;
+ this.startPosition = startPosition;
+ }
+
+ logger["logger"].log("seek to target start position " + startPosition + " from current time " + currentTime + ". ready state " + media.readyState);
+ media.currentTime = startPosition;
+ }
+ };
+
+ _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
+ var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
+
+ if (this.audioCodecSwap) {
+ logger["logger"].log('swapping playlist audio codec');
+
+ if (audioCodec) {
+ if (audioCodec.indexOf('mp4a.40.5') !== -1) {
+ audioCodec = 'mp4a.40.2';
+ } else {
+ audioCodec = 'mp4a.40.5';
+ }
+ }
+ }
+
+ return audioCodec;
+ };
+
+ stream_controller_createClass(StreamController, [{
+ key: "state",
+ set: function set(nextState) {
+ if (this.state !== nextState) {
+ var previousState = this.state;
+ this._state = nextState;
+ logger["logger"].log("main stream-controller: " + previousState + "->" + nextState);
+ this.hls.trigger(events["default"].STREAM_STATE_TRANSITION, {
+ previousState: previousState,
+ nextState: nextState
+ });
+ }
+ },
+ get: function get() {
+ return this._state;
+ }
+ }, {
+ key: "currentLevel",
+ get: function get() {
+ var media = this.media;
+
+ if (media) {
+ var frag = this.getBufferedFrag(media.currentTime);
+
+ if (frag) {
+ return frag.level;
+ }
+ }
+
+ return -1;
+ }
+ }, {
+ key: "nextBufferedFrag",
+ get: function get() {
+ var media = this.media;
+
+ if (media) {
+ // first get end range of current fragment
+ return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
+ } else {
+ return null;
+ }
+ }
+ }, {
+ key: "nextLevel",
+ get: function get() {
+ var frag = this.nextBufferedFrag;
+
+ if (frag) {
+ return frag.level;
+ } else {
+ return -1;
+ }
+ }
+ }, {
+ key: "liveSyncPosition",
+ get: function get() {
+ return this._liveSyncPosition;
+ },
+ set: function set(value) {
+ this._liveSyncPosition = value;
+ }
+ }]);
+
+ return StreamController;
+}(base_stream_controller_BaseStreamController);
+
+/* harmony default export */ var stream_controller = (stream_controller_StreamController);
+// CONCATENATED MODULE: ./src/controller/level-controller.js
+function level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Level Controller
+*/
+
+
+
+
+
+
+var chromeOrFirefox;
+
+var level_controller_LevelController = /*#__PURE__*/function (_EventHandler) {
+ level_controller_inheritsLoose(LevelController, _EventHandler);
+
+ function LevelController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADED, events["default"].LEVEL_LOADED, events["default"].AUDIO_TRACK_SWITCHED, events["default"].FRAG_LOADED, events["default"].ERROR) || this;
+ _this.canload = false;
+ _this.currentLevelIndex = null;
+ _this.manualLevelIndex = -1;
+ _this.timer = null;
+ chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
+ return _this;
+ }
+
+ var _proto = LevelController.prototype;
+
+ _proto.onHandlerDestroying = function onHandlerDestroying() {
+ this.clearTimer();
+ this.manualLevelIndex = -1;
+ };
+
+ _proto.clearTimer = function clearTimer() {
+ if (this.timer !== null) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ };
+
+ _proto.startLoad = function startLoad() {
+ var levels = this._levels;
+ this.canload = true;
+ this.levelRetryCount = 0; // clean up live level details to force reload them, and reset load errors
+
+ if (levels) {
+ levels.forEach(function (level) {
+ level.loadError = 0;
+ var levelDetails = level.details;
+
+ if (levelDetails && levelDetails.live) {
+ level.details = undefined;
+ }
+ });
+ } // speed up live playlist refresh if timer exists
+
+
+ if (this.timer !== null) {
+ this.loadLevel();
+ }
+ };
+
+ _proto.stopLoad = function stopLoad() {
+ this.canload = false;
+ };
+
+ _proto.onManifestLoaded = function onManifestLoaded(data) {
+ var levels = [];
+ var audioTracks = [];
+ var bitrateStart;
+ var levelSet = {};
+ var levelFromSet = null;
+ var videoCodecFound = false;
+ var audioCodecFound = false; // regroup redundant levels together
+
+ data.levels.forEach(function (level) {
+ var attributes = level.attrs;
+ level.loadError = 0;
+ level.fragmentError = false;
+ videoCodecFound = videoCodecFound || !!level.videoCodec;
+ audioCodecFound = audioCodecFound || !!level.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
+ // demuxer will autodetect codec and fallback to mpeg/audio
+
+ if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
+ level.audioCodec = undefined;
+ }
+
+ levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
+
+ if (!levelFromSet) {
+ level.url = [level.url];
+ level.urlId = 0;
+ levelSet[level.bitrate] = level;
+ levels.push(level);
+ } else {
+ levelFromSet.url.push(level.url);
+ }
+
+ if (attributes) {
+ if (attributes.AUDIO) {
+ addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);
+ }
+
+ if (attributes.SUBTITLES) {
+ addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);
+ }
+ }
+ }); // remove audio-only level if we also have levels with audio+video codecs signalled
+
+ if (videoCodecFound && audioCodecFound) {
+ levels = levels.filter(function (_ref) {
+ var videoCodec = _ref.videoCodec;
+ return !!videoCodec;
+ });
+ } // only keep levels with supported audio/video codecs
+
+
+ levels = levels.filter(function (_ref2) {
+ var audioCodec = _ref2.audioCodec,
+ videoCodec = _ref2.videoCodec;
+ return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));
+ });
+
+ if (data.audioTracks) {
+ audioTracks = data.audioTracks.filter(function (track) {
+ return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio');
+ }); // Reassign id's after filtering since they're used as array indices
+
+ audioTracks.forEach(function (track, index) {
+ track.id = index;
+ });
+ }
+
+ if (levels.length > 0) {
+ // start bitrate is the first bitrate of the manifest
+ bitrateStart = levels[0].bitrate; // sort level on bitrate
+
+ levels.sort(function (a, b) {
+ return a.bitrate - b.bitrate;
+ });
+ this._levels = levels; // find index of first level in sorted levels
+
+ for (var i = 0; i < levels.length; i++) {
+ if (levels[i].bitrate === bitrateStart) {
+ this._firstLevel = i;
+ logger["logger"].log("manifest loaded," + levels.length + " level(s) found, first bitrate:" + bitrateStart);
+ break;
+ }
+ } // Audio is only alternate if manifest include a URI along with the audio group tag,
+ // and this is not an audio-only stream where levels contain audio-only
+
+
+ var audioOnly = audioCodecFound && !videoCodecFound;
+ this.hls.trigger(events["default"].MANIFEST_PARSED, {
+ levels: levels,
+ audioTracks: audioTracks,
+ firstLevel: this._firstLevel,
+ stats: data.stats,
+ audio: audioCodecFound,
+ video: videoCodecFound,
+ altAudio: !audioOnly && audioTracks.some(function (t) {
+ return !!t.url;
+ })
+ });
+ } else {
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
+ fatal: true,
+ url: this.hls.url,
+ reason: 'no level with compatible codecs found in manifest'
+ });
+ }
+ };
+
+ _proto.setLevelInternal = function setLevelInternal(newLevel) {
+ var levels = this._levels;
+ var hls = this.hls; // check if level idx is valid
+
+ if (newLevel >= 0 && newLevel < levels.length) {
+ // stopping live reloading timer if any
+ this.clearTimer();
+
+ if (this.currentLevelIndex !== newLevel) {
+ logger["logger"].log("switching to level " + newLevel);
+ this.currentLevelIndex = newLevel;
+ var levelProperties = levels[newLevel];
+ levelProperties.level = newLevel;
+ hls.trigger(events["default"].LEVEL_SWITCHING, levelProperties);
+ }
+
+ var level = levels[newLevel];
+ var levelDetails = level.details; // check if we need to load playlist for this level
+
+ if (!levelDetails || levelDetails.live) {
+ // level not retrieved yet, or live playlist we need to (re)load it
+ var urlId = level.urlId;
+ hls.trigger(events["default"].LEVEL_LOADING, {
+ url: level.url[urlId],
+ level: newLevel,
+ id: urlId
+ });
+ }
+ } else {
+ // invalid level id given, trigger error
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].OTHER_ERROR,
+ details: errors["ErrorDetails"].LEVEL_SWITCH_ERROR,
+ level: newLevel,
+ fatal: false,
+ reason: 'invalid level idx'
+ });
+ }
+ };
+
+ _proto.onError = function onError(data) {
+ if (data.fatal) {
+ if (data.type === errors["ErrorTypes"].NETWORK_ERROR) {
+ this.clearTimer();
+ }
+
+ return;
+ }
+
+ var levelError = false,
+ fragmentError = false;
+ var levelIndex; // try to recover not fatal errors
+
+ switch (data.details) {
+ case errors["ErrorDetails"].FRAG_LOAD_ERROR:
+ case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
+ case errors["ErrorDetails"].KEY_LOAD_ERROR:
+ case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
+ levelIndex = data.frag.level;
+ fragmentError = true;
+ break;
+
+ case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
+ case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
+ levelIndex = data.context.level;
+ levelError = true;
+ break;
+
+ case errors["ErrorDetails"].REMUX_ALLOC_ERROR:
+ levelIndex = data.level;
+ levelError = true;
+ break;
+ }
+
+ if (levelIndex !== undefined) {
+ this.recoverLevel(data, levelIndex, levelError, fragmentError);
+ }
+ }
+ /**
+ * Switch to a redundant stream if any available.
+ * If redundant stream is not available, emergency switch down if ABR mode is enabled.
+ *
+ * @param {Object} errorEvent
+ * @param {Number} levelIndex current level index
+ * @param {Boolean} levelError
+ * @param {Boolean} fragmentError
+ */
+ // FIXME Find a better abstraction where fragment/level retry management is well decoupled
+ ;
+
+ _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
+ var _this2 = this;
+
+ var config = this.hls.config;
+ var errorDetails = errorEvent.details;
+ var level = this._levels[levelIndex];
+ var redundantLevels, delay, nextLevel;
+ level.loadError++;
+ level.fragmentError = fragmentError;
+
+ if (levelError) {
+ if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
+ // exponential backoff capped to max retry timeout
+ delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level reload
+
+ this.timer = setTimeout(function () {
+ return _this2.loadLevel();
+ }, delay); // boolean used to inform stream controller not to switch back to IDLE on non fatal error
+
+ errorEvent.levelRetry = true;
+ this.levelRetryCount++;
+ logger["logger"].warn("level controller, " + errorDetails + ", retry in " + delay + " ms, current retry count is " + this.levelRetryCount);
+ } else {
+ logger["logger"].error("level controller, cannot recover from " + errorDetails + " error");
+ this.currentLevelIndex = null; // stopping live reloading timer if any
+
+ this.clearTimer(); // switch error to fatal
+
+ errorEvent.fatal = true;
+ return;
+ }
+ } // Try any redundant streams if available for both errors: level and fragment
+ // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
+
+
+ if (levelError || fragmentError) {
+ redundantLevels = level.url.length;
+
+ if (redundantLevels > 1 && level.loadError < redundantLevels) {
+ level.urlId = (level.urlId + 1) % redundantLevels;
+ level.details = undefined;
+ logger["logger"].warn("level controller, " + errorDetails + " for level " + levelIndex + ": switching to redundant URL-id " + level.urlId); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
+ // console.log('New video quality level audio group id:', level.attrs.AUDIO);
+ } else {
+ // Search for available level
+ if (this.manualLevelIndex === -1) {
+ // When lowest level has been reached, let's start hunt from the top
+ nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
+ logger["logger"].warn("level controller, " + errorDetails + ": switch to " + nextLevel);
+ this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
+ } else if (fragmentError) {
+ // Allow fragment retry as long as configuration allows.
+ // reset this._level so that another call to set level() will trigger again a frag load
+ logger["logger"].warn("level controller, " + errorDetails + ": reload a fragment");
+ this.currentLevelIndex = null;
+ }
+ }
+ }
+ } // reset errors on the successful load of a fragment
+ ;
+
+ _proto.onFragLoaded = function onFragLoaded(_ref3) {
+ var frag = _ref3.frag;
+
+ if (frag !== undefined && frag.type === 'main') {
+ var level = this._levels[frag.level];
+
+ if (level !== undefined) {
+ level.fragmentError = false;
+ level.loadError = 0;
+ this.levelRetryCount = 0;
+ }
+ }
+ };
+
+ _proto.onLevelLoaded = function onLevelLoaded(data) {
+ var _this3 = this;
+
+ var level = data.level,
+ details = data.details; // only process level loaded events matching with expected level
+
+ if (level !== this.currentLevelIndex) {
+ return;
+ }
+
+ var curLevel = this._levels[level]; // reset level load error counter on successful level loaded only if there is no issues with fragments
+
+ if (!curLevel.fragmentError) {
+ curLevel.loadError = 0;
+ this.levelRetryCount = 0;
+ } // if current playlist is a live playlist, arm a timer to reload it
+
+
+ if (details.live) {
+ var reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);
+ logger["logger"].log("live playlist, reload in " + Math.round(reloadInterval) + " ms");
+ this.timer = setTimeout(function () {
+ return _this3.loadLevel();
+ }, reloadInterval);
+ } else {
+ this.clearTimer();
+ }
+ };
+
+ _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
+ var audioGroupId = this.hls.audioTracks[data.id].groupId;
+ var currentLevel = this.hls.levels[this.currentLevelIndex];
+
+ if (!currentLevel) {
+ return;
+ }
+
+ if (currentLevel.audioGroupIds) {
+ var urlId = -1;
+
+ for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
+ if (currentLevel.audioGroupIds[i] === audioGroupId) {
+ urlId = i;
+ break;
+ }
+ }
+
+ if (urlId !== currentLevel.urlId) {
+ currentLevel.urlId = urlId;
+ this.startLoad();
+ }
+ }
+ };
+
+ _proto.loadLevel = function loadLevel() {
+ logger["logger"].debug('call to loadLevel');
+
+ if (this.currentLevelIndex !== null && this.canload) {
+ var levelObject = this._levels[this.currentLevelIndex];
+
+ if (typeof levelObject === 'object' && levelObject.url.length > 0) {
+ var level = this.currentLevelIndex;
+ var id = levelObject.urlId;
+ var url = levelObject.url[id];
+ logger["logger"].log("Attempt loading level index " + level + " with URL-id " + id); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
+ // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
+
+ this.hls.trigger(events["default"].LEVEL_LOADING, {
+ url: url,
+ level: level,
+ id: id
+ });
+ }
+ }
+ };
+
+ _proto.removeLevel = function removeLevel(levelIndex, urlId) {
+ var levels = this.levels.filter(function (level, index) {
+ if (index !== levelIndex) {
+ return true;
+ }
+
+ if (level.url.length > 1 && urlId !== undefined) {
+ level.url = level.url.filter(function (url, id) {
+ return id !== urlId;
+ });
+ level.urlId = 0;
+ return true;
+ }
+
+ return false;
+ }).map(function (level, index) {
+ var details = level.details;
+
+ if (details && details.fragments) {
+ details.fragments.forEach(function (fragment) {
+ fragment.level = index;
+ });
+ }
+
+ return level;
+ });
+ this._levels = levels;
+ this.hls.trigger(events["default"].LEVELS_UPDATED, {
+ levels: levels
+ });
+ };
+
+ level_controller_createClass(LevelController, [{
+ key: "levels",
+ get: function get() {
+ return this._levels;
+ }
+ }, {
+ key: "level",
+ get: function get() {
+ return this.currentLevelIndex;
+ },
+ set: function set(newLevel) {
+ var levels = this._levels;
+
+ if (levels) {
+ newLevel = Math.min(newLevel, levels.length - 1);
+
+ if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
+ this.setLevelInternal(newLevel);
+ }
+ }
+ }
+ }, {
+ key: "manualLevel",
+ get: function get() {
+ return this.manualLevelIndex;
+ },
+ set: function set(newLevel) {
+ this.manualLevelIndex = newLevel;
+
+ if (this._startLevel === undefined) {
+ this._startLevel = newLevel;
+ }
+
+ if (newLevel !== -1) {
+ this.level = newLevel;
+ }
+ }
+ }, {
+ key: "firstLevel",
+ get: function get() {
+ return this._firstLevel;
+ },
+ set: function set(newLevel) {
+ this._firstLevel = newLevel;
+ }
+ }, {
+ key: "startLevel",
+ get: function get() {
+ // hls.startLevel takes precedence over config.startLevel
+ // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
+ if (this._startLevel === undefined) {
+ var configStartLevel = this.hls.config.startLevel;
+
+ if (configStartLevel !== undefined) {
+ return configStartLevel;
+ } else {
+ return this._firstLevel;
+ }
+ } else {
+ return this._startLevel;
+ }
+ },
+ set: function set(newLevel) {
+ this._startLevel = newLevel;
+ }
+ }, {
+ key: "nextLoadLevel",
+ get: function get() {
+ if (this.manualLevelIndex !== -1) {
+ return this.manualLevelIndex;
+ } else {
+ return this.hls.nextAutoLevel;
+ }
+ },
+ set: function set(nextLevel) {
+ this.level = nextLevel;
+
+ if (this.manualLevelIndex === -1) {
+ this.hls.nextAutoLevel = nextLevel;
+ }
+ }
+ }]);
+
+ return LevelController;
+}(event_handler);
+
+
+// EXTERNAL MODULE: ./src/demux/id3.js
+var id3 = __webpack_require__("./src/demux/id3.js");
+
+// CONCATENATED MODULE: ./src/utils/texttrack-utils.ts
+function sendAddTrackEvent(track, videoEl) {
+ var event;
+
+ try {
+ event = new Event('addtrack');
+ } catch (err) {
+ // for IE11
+ event = document.createEvent('Event');
+ event.initEvent('addtrack', false, false);
+ }
+
+ event.track = track;
+ videoEl.dispatchEvent(event);
+}
+function clearCurrentCues(track) {
+ if (track === null || track === void 0 ? void 0 : track.cues) {
+ while (track.cues.length > 0) {
+ track.removeCue(track.cues[0]);
+ }
+ }
+}
+/**
+ * Given a list of Cues, finds the closest cue matching the given time.
+ * Modified verison of binary search O(log(n)).
+ *
+ * @export
+ * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.
+ * @param {number} time - Target time, to find closest cue to.
+ * @returns {TextTrackCue}
+ */
+
+function getClosestCue(cues, time) {
+ // If the offset is less than the first element, the first element is the closest.
+ if (time < cues[0].endTime) {
+ return cues[0];
+ } // If the offset is greater than the last cue, the last is the closest.
+
+
+ if (time > cues[cues.length - 1].endTime) {
+ return cues[cues.length - 1];
+ }
+
+ var left = 0;
+ var right = cues.length - 1;
+
+ while (left <= right) {
+ var mid = Math.floor((right + left) / 2);
+
+ if (time < cues[mid].endTime) {
+ right = mid - 1;
+ } else if (time > cues[mid].endTime) {
+ left = mid + 1;
+ } else {
+ // If it's not lower or higher, it must be equal.
+ return cues[mid];
+ }
+ } // At this point, left and right have swapped.
+ // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
+
+
+ return cues[left].endTime - time < time - cues[right].endTime ? cues[left] : cues[right];
+}
+// CONCATENATED MODULE: ./src/controller/id3-track-controller.js
+function id3_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * id3 metadata track controller
+*/
+
+
+
+
+var MIN_CUE_DURATION = 0.25;
+
+var id3_track_controller_ID3TrackController = /*#__PURE__*/function (_EventHandler) {
+ id3_track_controller_inheritsLoose(ID3TrackController, _EventHandler);
+
+ function ID3TrackController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].FRAG_PARSING_METADATA, events["default"].LIVE_BACK_BUFFER_REACHED) || this;
+ _this.id3Track = undefined;
+ _this.media = undefined;
+ return _this;
+ }
+
+ var _proto = ID3TrackController.prototype;
+
+ _proto.destroy = function destroy() {
+ event_handler.prototype.destroy.call(this);
+ } // Add ID3 metatadata text track.
+ ;
+
+ _proto.onMediaAttached = function onMediaAttached(data) {
+ this.media = data.media;
+
+ if (!this.media) {}
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ clearCurrentCues(this.id3Track);
+ this.id3Track = undefined;
+ this.media = undefined;
+ };
+
+ _proto.getID3Track = function getID3Track(textTracks) {
+ for (var i = 0; i < textTracks.length; i++) {
+ var textTrack = textTracks[i];
+
+ if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
+ // send 'addtrack' when reusing the textTrack for metadata,
+ // same as what we do for captions
+ sendAddTrackEvent(textTrack, this.media);
+ return textTrack;
+ }
+ }
+
+ return this.media.addTextTrack('metadata', 'id3');
+ };
+
+ _proto.onFragParsingMetadata = function onFragParsingMetadata(data) {
+ var fragment = data.frag;
+ var samples = data.samples; // create track dynamically
+
+ if (!this.id3Track) {
+ this.id3Track = this.getID3Track(this.media.textTracks);
+ this.id3Track.mode = 'hidden';
+ } // Attempt to recreate Safari functionality by creating
+ // WebKitDataCue objects when available and store the decoded
+ // ID3 data in the value property of the cue
+
+
+ var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
+
+ for (var i = 0; i < samples.length; i++) {
+ var frames = id3["default"].getID3Frames(samples[i].data);
+
+ if (frames) {
+ // Ensure the pts is positive - sometimes it's reported as a small negative number
+ var startTime = Math.max(samples[i].pts, 0);
+ var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
+
+ if (!endTime) {
+ endTime = fragment.start + fragment.duration;
+ }
+
+ var timeDiff = endTime - startTime;
+
+ if (timeDiff <= 0) {
+ endTime = startTime + MIN_CUE_DURATION;
+ }
+
+ for (var j = 0; j < frames.length; j++) {
+ var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
+
+ if (!id3["default"].isTimeStampFrame(frame)) {
+ var cue = new Cue(startTime, endTime, '');
+ cue.value = frame;
+ this.id3Track.addCue(cue);
+ }
+ }
+ }
+ }
+ };
+
+ _proto.onLiveBackBufferReached = function onLiveBackBufferReached(_ref) {
+ var bufferEnd = _ref.bufferEnd;
+ var id3Track = this.id3Track;
+
+ if (!id3Track || !id3Track.cues || !id3Track.cues.length) {
+ return;
+ }
+
+ var foundCue = getClosestCue(id3Track.cues, bufferEnd);
+
+ if (!foundCue) {
+ return;
+ }
+
+ while (id3Track.cues[0] !== foundCue) {
+ id3Track.removeCue(id3Track.cues[0]);
+ }
+ };
+
+ return ID3TrackController;
+}(event_handler);
+
+/* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController);
+// CONCATENATED MODULE: ./src/is-supported.ts
+
+function is_supported_isSupported() {
+ var mediaSource = getMediaSource();
+
+ if (!mediaSource) {
+ return false;
+ }
+
+ var sourceBuffer = self.SourceBuffer || self.WebKitSourceBuffer;
+ var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
+ // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
+
+ var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
+ return !!isTypeSupported && !!sourceBufferValidAPI;
+}
+// CONCATENATED MODULE: ./src/utils/ewma.ts
+/*
+ * compute an Exponential Weighted moving average
+ * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
+ * - heavily inspired from shaka-player
+ */
+var EWMA = /*#__PURE__*/function () {
+ // About half of the estimated value will be from the last |halfLife| samples by weight.
+ function EWMA(halfLife) {
+ this.alpha_ = void 0;
+ this.estimate_ = void 0;
+ this.totalWeight_ = void 0;
+ // Larger values of alpha expire historical data more slowly.
+ this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
+ this.estimate_ = 0;
+ this.totalWeight_ = 0;
+ }
+
+ var _proto = EWMA.prototype;
+
+ _proto.sample = function sample(weight, value) {
+ var adjAlpha = Math.pow(this.alpha_, weight);
+ this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
+ this.totalWeight_ += weight;
+ };
+
+ _proto.getTotalWeight = function getTotalWeight() {
+ return this.totalWeight_;
+ };
+
+ _proto.getEstimate = function getEstimate() {
+ if (this.alpha_) {
+ var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
+ return this.estimate_ / zeroFactor;
+ } else {
+ return this.estimate_;
+ }
+ };
+
+ return EWMA;
+}();
+
+/* harmony default export */ var ewma = (EWMA);
+// CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.ts
+/*
+ * EWMA Bandwidth Estimator
+ * - heavily inspired from shaka-player
+ * Tracks bandwidth samples and estimates available bandwidth.
+ * Based on the minimum of two exponentially-weighted moving averages with
+ * different half-lives.
+ */
+
+
+var ewma_bandwidth_estimator_EwmaBandWidthEstimator = /*#__PURE__*/function () {
+ // TODO(typescript-hls)
+ function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
+ this.hls = void 0;
+ this.defaultEstimate_ = void 0;
+ this.minWeight_ = void 0;
+ this.minDelayMs_ = void 0;
+ this.slow_ = void 0;
+ this.fast_ = void 0;
+ this.hls = hls;
+ this.defaultEstimate_ = defaultEstimate;
+ this.minWeight_ = 0.001;
+ this.minDelayMs_ = 50;
+ this.slow_ = new ewma(slow);
+ this.fast_ = new ewma(fast);
+ }
+
+ var _proto = EwmaBandWidthEstimator.prototype;
+
+ _proto.sample = function sample(durationMs, numBytes) {
+ durationMs = Math.max(durationMs, this.minDelayMs_);
+ var numBits = 8 * numBytes,
+ // weight is duration in seconds
+ durationS = durationMs / 1000,
+ // value is bandwidth in bits/s
+ bandwidthInBps = numBits / durationS;
+ this.fast_.sample(durationS, bandwidthInBps);
+ this.slow_.sample(durationS, bandwidthInBps);
+ };
+
+ _proto.canEstimate = function canEstimate() {
+ var fast = this.fast_;
+ return fast && fast.getTotalWeight() >= this.minWeight_;
+ };
+
+ _proto.getEstimate = function getEstimate() {
+ if (this.canEstimate()) {
+ // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
+ // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
+ // Take the minimum of these two estimates. This should have the effect of
+ // adapting down quickly, but up more slowly.
+ return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
+ } else {
+ return this.defaultEstimate_;
+ }
+ };
+
+ _proto.destroy = function destroy() {};
+
+ return EwmaBandWidthEstimator;
+}();
+
+/* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator);
+// CONCATENATED MODULE: ./src/controller/abr-controller.js
+
+
+
+function abr_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function abr_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) abr_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) abr_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function abr_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function abr_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * simple ABR Controller
+ * - compute next level based on last fragment bw heuristics
+ * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
+ */
+
+
+
+
+
+
+var abr_controller_window = window,
+ abr_controller_performance = abr_controller_window.performance;
+
+var abr_controller_AbrController = /*#__PURE__*/function (_EventHandler) {
+ abr_controller_inheritsLoose(AbrController, _EventHandler);
+
+ function AbrController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING, events["default"].FRAG_LOADED, events["default"].FRAG_BUFFERED, events["default"].ERROR) || this;
+ _this.lastLoadedFragLevel = 0;
+ _this._nextAutoLevel = -1;
+ _this.hls = hls;
+ _this.timer = null;
+ _this._bwEstimator = null;
+ _this.onCheck = _this._abandonRulesCheck.bind(abr_controller_assertThisInitialized(_this));
+ return _this;
+ }
+
+ var _proto = AbrController.prototype;
+
+ _proto.destroy = function destroy() {
+ this.clearTimer();
+ event_handler.prototype.destroy.call(this);
+ };
+
+ _proto.onFragLoading = function onFragLoading(data) {
+ var frag = data.frag;
+
+ if (frag.type === 'main') {
+ if (!this.timer) {
+ this.fragCurrent = frag;
+ this.timer = setInterval(this.onCheck, 100);
+ } // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
+ // so we need to wait for stream manifest / playlist type to instantiate it.
+
+
+ if (!this._bwEstimator) {
+ var hls = this.hls;
+ var config = hls.config;
+ var level = frag.level;
+ var isLive = hls.levels[level].details.live;
+ var ewmaFast;
+ var ewmaSlow;
+
+ if (isLive) {
+ ewmaFast = config.abrEwmaFastLive;
+ ewmaSlow = config.abrEwmaSlowLive;
+ } else {
+ ewmaFast = config.abrEwmaFastVoD;
+ ewmaSlow = config.abrEwmaSlowVoD;
+ }
+
+ this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
+ }
+ }
+ };
+
+ _proto._abandonRulesCheck = function _abandonRulesCheck() {
+ /*
+ monitor fragment retrieval time...
+ we compute expected time of arrival of the complete fragment.
+ we compare it to expected time of buffer starvation
+ */
+ var hls = this.hls;
+ var video = hls.media;
+ var frag = this.fragCurrent;
+
+ if (!frag) {
+ return;
+ }
+
+ var loader = frag.loader; // if loader has been destroyed or loading has been aborted, stop timer and return
+
+ if (!loader || loader.stats && loader.stats.aborted) {
+ logger["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
+ this.clearTimer(); // reset forced auto level value so that next level will be selected
+
+ this._nextAutoLevel = -1;
+ return;
+ }
+
+ var stats = loader.stats;
+ /* only monitor frag retrieval time if
+ (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
+
+ if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
+ var requestDelay = abr_controller_performance.now() - stats.trequest;
+ var playbackRate = Math.abs(video.playbackRate); // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
+
+ if (requestDelay > 500 * frag.duration / playbackRate) {
+ var levels = hls.levels;
+ var loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero
+ // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
+
+ var level = levels[frag.level];
+
+ if (!level) {
+ return;
+ }
+
+ var levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;
+ var expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));
+ var pos = video.currentTime;
+ var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
+ var bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate; // consider emergency switch down only if we have less than 2 frag buffered AND
+ // time to finish loading current fragment is bigger than buffer starvation delay
+ // ie if we risk buffer starvation if bw does not increase quickly
+
+ if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
+ var minAutoLevel = hls.minAutoLevel;
+ var fragLevelNextLoadedDelay;
+ var nextLoadLevel; // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
+ // we start from current level - 1 and we step down , until we find a matching level
+
+ for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
+ // compute time to load next fragment at lower level
+ // 0.8 : consider only 80% of current bw to be conservative
+ // 8 = bits per byte (bps/Bps)
+ var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
+
+ var _fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
+
+ if (_fragLevelNextLoadedDelay < bufferStarvationDelay) {
+ // we found a lower level that be rebuffering free with current estimated bw !
+ break;
+ }
+ } // only emergency switch down if it takes less time to load new fragment at lowest level instead
+ // of finishing loading current one ...
+
+
+ if (fragLevelNextLoadedDelay < fragLoadedDelay) {
+ logger["logger"].warn("loading too slow, abort fragment loading and switch to level " + nextLoadLevel + ":fragLoadedDelay[" + nextLoadLevel + "]<fragLoadedDelay[" + (frag.level - 1) + "];bufferStarvationDelay:" + fragLevelNextLoadedDelay.toFixed(1) + "<" + fragLoadedDelay.toFixed(1) + ":" + bufferStarvationDelay.toFixed(1)); // force next load level in auto mode
+
+ hls.nextLoadLevel = nextLoadLevel; // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
+
+ this._bwEstimator.sample(requestDelay, stats.loaded); // abort fragment loading
+
+
+ loader.abort(); // stop abandon rules timer
+
+ this.clearTimer();
+ hls.trigger(events["default"].FRAG_LOAD_EMERGENCY_ABORTED, {
+ frag: frag,
+ stats: stats
+ });
+ }
+ }
+ }
+ }
+ };
+
+ _proto.onFragLoaded = function onFragLoaded(data) {
+ var frag = data.frag;
+
+ if (frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn)) {
+ // stop monitoring bw once frag loaded
+ this.clearTimer(); // store level id after successful fragment load
+
+ this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
+
+ this._nextAutoLevel = -1; // compute level average bitrate
+
+ if (this.hls.config.abrMaxWithRealBitrate) {
+ var level = this.hls.levels[frag.level];
+ var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
+ var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
+ level.loaded = {
+ bytes: loadedBytes,
+ duration: loadedDuration
+ };
+ level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
+ } // if fragment has been loaded to perform a bitrate test,
+
+
+ if (data.frag.bitrateTest) {
+ var stats = data.stats;
+ stats.tparsed = stats.tbuffered = stats.tload;
+ this.onFragBuffered(data);
+ }
+ }
+ };
+
+ _proto.onFragBuffered = function onFragBuffered(data) {
+ var stats = data.stats;
+ var frag = data.frag; // only update stats on first frag buffering
+ // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
+ // and leading to wrong bw estimation
+ // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
+
+ if (stats.aborted !== true && frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
+ // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
+ // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
+ // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
+ var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
+ logger["logger"].log("latency/loading/parsing/append/kbps:" + Math.round(stats.tfirst - stats.trequest) + "/" + Math.round(stats.tload - stats.tfirst) + "/" + Math.round(stats.tparsed - stats.tload) + "/" + Math.round(stats.tbuffered - stats.tparsed) + "/" + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
+
+ this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
+
+ stats.bwEstimate = this._bwEstimator.getEstimate(); // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
+
+ if (frag.bitrateTest) {
+ this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
+ } else {
+ this.bitrateTestDelay = 0;
+ }
+ }
+ };
+
+ _proto.onError = function onError(data) {
+ // stop timer in case of frag loading error
+ switch (data.details) {
+ case errors["ErrorDetails"].FRAG_LOAD_ERROR:
+ case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
+ this.clearTimer();
+ break;
+
+ default:
+ break;
+ }
+ };
+
+ _proto.clearTimer = function clearTimer() {
+ clearInterval(this.timer);
+ this.timer = null;
+ } // return next auto level
+ ;
+
+ _proto._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
+ for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
+ var levelInfo = levels[i];
+
+ if (!levelInfo) {
+ continue;
+ }
+
+ var levelDetails = levelInfo.details;
+ var avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;
+ var live = levelDetails ? levelDetails.live : false;
+ var adjustedbw = void 0; // follow algorithm captured from stagefright :
+ // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
+ // Pick the highest bandwidth stream below or equal to estimated bandwidth.
+ // consider only 80% of the available bandwidth, but if we are switching up,
+ // be even more conservative (70%) to avoid overestimating and immediately
+ // switching back.
+
+ if (i <= currentLevel) {
+ adjustedbw = bwFactor * currentBw;
+ } else {
+ adjustedbw = bwUpFactor * currentBw;
+ }
+
+ var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
+ var fetchDuration = bitrate * avgDuration / adjustedbw;
+ logger["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
+
+ if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
+ // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
+ // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
+ !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
+ // as we are looping from highest to lowest, this will return the best achievable quality level
+ return i;
+ }
+ } // not enough time budget even with quality level 0 ... rebuffering might happen
+
+
+ return -1;
+ };
+
+ abr_controller_createClass(AbrController, [{
+ key: "nextAutoLevel",
+ get: function get() {
+ var forcedAutoLevel = this._nextAutoLevel;
+ var bwEstimator = this._bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
+
+ if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
+ return forcedAutoLevel;
+ } // compute next level using ABR logic
+
+
+ var nextABRAutoLevel = this._nextABRAutoLevel; // if forced auto level has been defined, use it to cap ABR computed quality level
+
+ if (forcedAutoLevel !== -1) {
+ nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
+ }
+
+ return nextABRAutoLevel;
+ },
+ set: function set(nextLevel) {
+ this._nextAutoLevel = nextLevel;
+ }
+ }, {
+ key: "_nextABRAutoLevel",
+ get: function get() {
+ var hls = this.hls;
+ var maxAutoLevel = hls.maxAutoLevel,
+ levels = hls.levels,
+ config = hls.config,
+ minAutoLevel = hls.minAutoLevel;
+ var video = hls.media;
+ var currentLevel = this.lastLoadedFragLevel;
+ var currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;
+ var pos = video ? video.currentTime : 0; // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
+ // if we're playing back at the normal rate.
+
+ var playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0;
+ var avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
+
+ var bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
+
+ var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
+
+ if (bestLevel >= 0) {
+ return bestLevel;
+ } else {
+ logger["logger"].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering'); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
+ // if no matching level found, logic will return 0
+
+ var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
+ var bwFactor = config.abrBandWidthFactor;
+ var bwUpFactor = config.abrBandWidthUpFactor;
+
+ if (bufferStarvationDelay === 0) {
+ // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
+ var bitrateTestDelay = this.bitrateTestDelay;
+
+ if (bitrateTestDelay) {
+ // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
+ // max video loading delay used in automatic start level selection :
+ // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
+ // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
+ // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
+ var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
+ maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
+ logger["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
+
+ bwFactor = bwUpFactor = 1;
+ }
+ }
+
+ bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
+ return Math.max(bestLevel, 0);
+ }
+ }
+ }]);
+
+ return AbrController;
+}(event_handler);
+
+/* harmony default export */ var abr_controller = (abr_controller_AbrController);
+// CONCATENATED MODULE: ./src/controller/buffer-controller.ts
+
+
+function buffer_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Buffer Controller
+ */
+
+
+
+
+
+var buffer_controller_MediaSource = getMediaSource();
+
+var buffer_controller_BufferController = /*#__PURE__*/function (_EventHandler) {
+ buffer_controller_inheritsLoose(BufferController, _EventHandler);
+
+ // the value that we have set mediasource.duration to
+ // (the actual duration may be tweaked slighly by the browser)
+ // the value that we want to set mediaSource.duration to
+ // the target duration of the current media playlist
+ // current stream state: true - for live broadcast, false - for VoD content
+ // cache the self generated object url to detect hijack of video tag
+ // signals that the sourceBuffers need to be flushed
+ // signals that mediaSource should have endOfStream called
+ // this is optional because this property is removed from the class sometimes
+ // The number of BUFFER_CODEC events received before any sourceBuffers are created
+ // The total number of BUFFER_CODEC events received
+ // A reference to the attached media element
+ // A reference to the active media source
+ // List of pending segments to be appended to source buffer
+ // A guard to see if we are currently appending to the source buffer
+ // counters
+ function BufferController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_PARSED, events["default"].BUFFER_RESET, events["default"].BUFFER_APPENDING, events["default"].BUFFER_CODECS, events["default"].BUFFER_EOS, events["default"].BUFFER_FLUSHING, events["default"].LEVEL_PTS_UPDATED, events["default"].LEVEL_UPDATED) || this;
+ _this._msDuration = null;
+ _this._levelDuration = null;
+ _this._levelTargetDuration = 10;
+ _this._live = null;
+ _this._objectUrl = null;
+ _this._needsFlush = false;
+ _this._needsEos = false;
+ _this.config = void 0;
+ _this.audioTimestampOffset = void 0;
+ _this.bufferCodecEventsExpected = 0;
+ _this._bufferCodecEventsTotal = 0;
+ _this.media = null;
+ _this.mediaSource = null;
+ _this.segments = [];
+ _this.parent = void 0;
+ _this.appending = false;
+ _this.appended = 0;
+ _this.appendError = 0;
+ _this.flushBufferCounter = 0;
+ _this.tracks = {};
+ _this.pendingTracks = {};
+ _this.sourceBuffer = {};
+ _this.flushRange = [];
+
+ _this._onMediaSourceOpen = function () {
+ logger["logger"].log('media source opened');
+
+ _this.hls.trigger(events["default"].MEDIA_ATTACHED, {
+ media: _this.media
+ });
+
+ var mediaSource = _this.mediaSource;
+
+ if (mediaSource) {
+ // once received, don't listen anymore to sourceopen event
+ mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
+ }
+
+ _this.checkPendingTracks();
+ };
+
+ _this._onMediaSourceClose = function () {
+ logger["logger"].log('media source closed');
+ };
+
+ _this._onMediaSourceEnded = function () {
+ logger["logger"].log('media source ended');
+ };
+
+ _this._onSBUpdateEnd = function () {
+ // update timestampOffset
+ if (_this.audioTimestampOffset && _this.sourceBuffer.audio) {
+ var audioBuffer = _this.sourceBuffer.audio;
+ logger["logger"].warn("change mpeg audio timestamp offset from " + audioBuffer.timestampOffset + " to " + _this.audioTimestampOffset);
+ audioBuffer.timestampOffset = _this.audioTimestampOffset;
+ delete _this.audioTimestampOffset;
+ }
+
+ if (_this._needsFlush) {
+ _this.doFlush();
+ }
+
+ if (_this._needsEos) {
+ _this.checkEos();
+ }
+
+ _this.appending = false;
+ var parent = _this.parent; // count nb of pending segments waiting for appending on this sourcebuffer
+
+ var pending = _this.segments.reduce(function (counter, segment) {
+ return segment.parent === parent ? counter + 1 : counter;
+ }, 0); // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
+
+
+ var timeRanges = {};
+ var sbSet = _this.sourceBuffer;
+
+ for (var streamType in sbSet) {
+ var sb = sbSet[streamType];
+
+ if (!sb) {
+ throw Error("handling source buffer update end error: source buffer for " + streamType + " uninitilized and unable to update buffered TimeRanges.");
+ }
+
+ timeRanges[streamType] = sb.buffered;
+ }
+
+ _this.hls.trigger(events["default"].BUFFER_APPENDED, {
+ parent: parent,
+ pending: pending,
+ timeRanges: timeRanges
+ }); // don't append in flushing mode
+
+
+ if (!_this._needsFlush) {
+ _this.doAppending();
+ }
+
+ _this.updateMediaElementDuration(); // appending goes first
+
+
+ if (pending === 0) {
+ _this.flushLiveBackBuffer();
+ }
+ };
+
+ _this._onSBUpdateError = function (event) {
+ logger["logger"].error('sourceBuffer error:', event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
+ // this error might not always be fatal (it is fatal if decode error is set, in that case
+ // it will be followed by a mediaElement error ...)
+
+ _this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_APPENDING_ERROR,
+ fatal: false
+ }); // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
+
+ };
+
+ _this.config = hls.config;
+ return _this;
+ }
+
+ var _proto = BufferController.prototype;
+
+ _proto.destroy = function destroy() {
+ event_handler.prototype.destroy.call(this);
+ };
+
+ _proto.onLevelPtsUpdated = function onLevelPtsUpdated(data) {
+ var type = data.type;
+ var audioTrack = this.tracks.audio; // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
+ // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
+ // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue
+ // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
+ // event if SB is in updating state.
+ // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
+
+ if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
+ // Chrome audio mp3 track
+ var audioBuffer = this.sourceBuffer.audio;
+
+ if (!audioBuffer) {
+ throw Error('Level PTS Updated and source buffer for audio uninitalized');
+ }
+
+ var delta = Math.abs(audioBuffer.timestampOffset - data.start); // adjust timestamp offset if time delta is greater than 100ms
+
+ if (delta > 0.1) {
+ var updating = audioBuffer.updating;
+
+ try {
+ audioBuffer.abort();
+ } catch (err) {
+ logger["logger"].warn('can not abort audio buffer: ' + err);
+ }
+
+ if (!updating) {
+ logger["logger"].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
+ audioBuffer.timestampOffset = data.start;
+ } else {
+ this.audioTimestampOffset = data.start;
+ }
+ }
+ }
+ };
+
+ _proto.onManifestParsed = function onManifestParsed(data) {
+ // in case of alt audio (where all tracks have urls) 2 BUFFER_CODECS events will be triggered, one per stream controller
+ // sourcebuffers will be created all at once when the expected nb of tracks will be reached
+ // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
+ // it will contain the expected nb of source buffers, no need to compute it
+ var codecEvents = 2;
+
+ if (data.audio && !data.video || !data.altAudio) {
+ codecEvents = 1;
+ }
+
+ this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
+ logger["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
+ };
+
+ _proto.onMediaAttaching = function onMediaAttaching(data) {
+ var media = this.media = data.media;
+
+ if (media && buffer_controller_MediaSource) {
+ // setup the media source
+ var ms = this.mediaSource = new buffer_controller_MediaSource(); // Media Source listeners
+
+ ms.addEventListener('sourceopen', this._onMediaSourceOpen);
+ ms.addEventListener('sourceended', this._onMediaSourceEnded);
+ ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
+
+ media.src = window.URL.createObjectURL(ms); // cache the locally generated object url
+
+ this._objectUrl = media.src;
+ }
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ logger["logger"].log('media source detaching');
+ var ms = this.mediaSource;
+
+ if (ms) {
+ if (ms.readyState === 'open') {
+ try {
+ // endOfStream could trigger exception if any sourcebuffer is in updating state
+ // we don't really care about checking sourcebuffer state here,
+ // as we are anyway detaching the MediaSource
+ // let's just avoid this exception to propagate
+ ms.endOfStream();
+ } catch (err) {
+ logger["logger"].warn("onMediaDetaching:" + err.message + " while calling endOfStream");
+ }
+ }
+
+ ms.removeEventListener('sourceopen', this._onMediaSourceOpen);
+ ms.removeEventListener('sourceended', this._onMediaSourceEnded);
+ ms.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
+ // suggested in https://github.com/w3c/media-source/issues/53.
+
+ if (this.media) {
+ if (this._objectUrl) {
+ window.URL.revokeObjectURL(this._objectUrl);
+ } // clean up video tag src only if it's our own url. some external libraries might
+ // hijack the video tag and change its 'src' without destroying the Hls instance first
+
+
+ if (this.media.src === this._objectUrl) {
+ this.media.removeAttribute('src');
+ this.media.load();
+ } else {
+ logger["logger"].warn('media.src was changed by a third party - skip cleanup');
+ }
+ }
+
+ this.mediaSource = null;
+ this.media = null;
+ this._objectUrl = null;
+ this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
+ this.pendingTracks = {};
+ this.tracks = {};
+ this.sourceBuffer = {};
+ this.flushRange = [];
+ this.segments = [];
+ this.appended = 0;
+ }
+
+ this.hls.trigger(events["default"].MEDIA_DETACHED);
+ };
+
+ _proto.checkPendingTracks = function checkPendingTracks() {
+ var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
+ pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
+ // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
+ // data has been appended to existing ones.
+ // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
+
+ var pendingTracksCount = Object.keys(pendingTracks).length;
+
+ if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
+ // ok, let's create them now !
+ this.createSourceBuffers(pendingTracks);
+ this.pendingTracks = {}; // append any pending segments now !
+
+ this.doAppending();
+ }
+ };
+
+ _proto.onBufferReset = function onBufferReset() {
+ var sourceBuffer = this.sourceBuffer;
+
+ for (var type in sourceBuffer) {
+ var sb = sourceBuffer[type];
+
+ try {
+ if (sb) {
+ if (this.mediaSource) {
+ this.mediaSource.removeSourceBuffer(sb);
+ }
+
+ sb.removeEventListener('updateend', this._onSBUpdateEnd);
+ sb.removeEventListener('error', this._onSBUpdateError);
+ }
+ } catch (err) {}
+ }
+
+ this.sourceBuffer = {};
+ this.flushRange = [];
+ this.segments = [];
+ this.appended = 0;
+ };
+
+ _proto.onBufferCodecs = function onBufferCodecs(tracks) {
+ var _this2 = this;
+
+ // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
+ // if sourcebuffers already created, do nothing ...
+ if (Object.keys(this.sourceBuffer).length) {
+ return;
+ }
+
+ Object.keys(tracks).forEach(function (trackName) {
+ _this2.pendingTracks[trackName] = tracks[trackName];
+ });
+ this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
+
+ if (this.mediaSource && this.mediaSource.readyState === 'open') {
+ this.checkPendingTracks();
+ }
+ };
+
+ _proto.createSourceBuffers = function createSourceBuffers(tracks) {
+ var sourceBuffer = this.sourceBuffer,
+ mediaSource = this.mediaSource;
+
+ if (!mediaSource) {
+ throw Error('createSourceBuffers called when mediaSource was null');
+ }
+
+ for (var trackName in tracks) {
+ if (!sourceBuffer[trackName]) {
+ var track = tracks[trackName];
+
+ if (!track) {
+ throw Error("source buffer exists for track " + trackName + ", however track does not");
+ } // use levelCodec as first priority
+
+
+ var codec = track.levelCodec || track.codec;
+ var mimeType = track.container + ";codecs=" + codec;
+ logger["logger"].log("creating sourceBuffer(" + mimeType + ")");
+
+ try {
+ var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
+ sb.addEventListener('updateend', this._onSBUpdateEnd);
+ sb.addEventListener('error', this._onSBUpdateError);
+ this.tracks[trackName] = {
+ buffer: sb,
+ codec: codec,
+ id: track.id,
+ container: track.container,
+ levelCodec: track.levelCodec
+ };
+ } catch (err) {
+ logger["logger"].error("error while trying to add sourceBuffer:" + err.message);
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
+ fatal: false,
+ err: err,
+ mimeType: mimeType
+ });
+ }
+ }
+ }
+
+ this.hls.trigger(events["default"].BUFFER_CREATED, {
+ tracks: this.tracks
+ });
+ };
+
+ _proto.onBufferAppending = function onBufferAppending(data) {
+ if (!this._needsFlush) {
+ if (!this.segments) {
+ this.segments = [data];
+ } else {
+ this.segments.push(data);
+ }
+
+ this.doAppending();
+ }
+ } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
+ // an undefined data.type will mark all buffers as EOS.
+ ;
+
+ _proto.onBufferEos = function onBufferEos(data) {
+ for (var type in this.sourceBuffer) {
+ if (!data.type || data.type === type) {
+ var sb = this.sourceBuffer[type];
+
+ if (sb && !sb.ended) {
+ sb.ended = true;
+ logger["logger"].log(type + " sourceBuffer now EOS");
+ }
+ }
+ }
+
+ this.checkEos();
+ } // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
+ ;
+
+ _proto.checkEos = function checkEos() {
+ var sourceBuffer = this.sourceBuffer,
+ mediaSource = this.mediaSource;
+
+ if (!mediaSource || mediaSource.readyState !== 'open') {
+ this._needsEos = false;
+ return;
+ }
+
+ for (var type in sourceBuffer) {
+ var sb = sourceBuffer[type];
+ if (!sb) continue;
+
+ if (!sb.ended) {
+ return;
+ }
+
+ if (sb.updating) {
+ this._needsEos = true;
+ return;
+ }
+ }
+
+ logger["logger"].log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment'); // Notify the media element that it now has all of the media data
+
+ try {
+ mediaSource.endOfStream();
+ } catch (e) {
+ logger["logger"].warn('exception while calling mediaSource.endOfStream()');
+ }
+
+ this._needsEos = false;
+ };
+
+ _proto.onBufferFlushing = function onBufferFlushing(data) {
+ if (data.type) {
+ this.flushRange.push({
+ start: data.startOffset,
+ end: data.endOffset,
+ type: data.type
+ });
+ } else {
+ this.flushRange.push({
+ start: data.startOffset,
+ end: data.endOffset,
+ type: 'video'
+ });
+ this.flushRange.push({
+ start: data.startOffset,
+ end: data.endOffset,
+ type: 'audio'
+ });
+ } // attempt flush immediately
+
+
+ this.flushBufferCounter = 0;
+ this.doFlush();
+ };
+
+ _proto.flushLiveBackBuffer = function flushLiveBackBuffer() {
+ // clear back buffer for live only
+ if (!this._live) {
+ return;
+ }
+
+ var liveBackBufferLength = this.config.liveBackBufferLength;
+
+ if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
+ return;
+ }
+
+ if (!this.media) {
+ logger["logger"].error('flushLiveBackBuffer called without attaching media');
+ return;
+ }
+
+ var currentTime = this.media.currentTime;
+ var sourceBuffer = this.sourceBuffer;
+ var bufferTypes = Object.keys(sourceBuffer);
+ var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
+
+ for (var index = bufferTypes.length - 1; index >= 0; index--) {
+ var bufferType = bufferTypes[index];
+ var sb = sourceBuffer[bufferType];
+
+ if (sb) {
+ var buffered = sb.buffered; // when target buffer start exceeds actual buffer start
+
+ if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
+ // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
+ // time will lead to playback freezing)
+ // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
+ if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {
+ this.hls.trigger(events["default"].LIVE_BACK_BUFFER_REACHED, {
+ bufferEnd: targetBackBufferPosition
+ });
+ }
+ }
+ }
+ }
+ };
+
+ _proto.onLevelUpdated = function onLevelUpdated(_ref) {
+ var details = _ref.details;
+
+ if (details.fragments.length > 0) {
+ this._levelDuration = details.totalduration + details.fragments[0].start;
+ this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
+ this._live = details.live;
+ this.updateMediaElementDuration();
+ }
+ }
+ /**
+ * Update Media Source duration to current level duration or override to Infinity if configuration parameter
+ * 'liveDurationInfinity` is set to `true`
+ * More details: https://github.com/video-dev/hls.js/issues/355
+ */
+ ;
+
+ _proto.updateMediaElementDuration = function updateMediaElementDuration() {
+ var config = this.config;
+ var duration;
+
+ if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
+ return;
+ }
+
+ for (var type in this.sourceBuffer) {
+ var sb = this.sourceBuffer[type];
+
+ if (sb && sb.updating === true) {
+ // can't set duration whilst a buffer is updating
+ return;
+ }
+ }
+
+ duration = this.media.duration; // initialise to the value that the media source is reporting
+
+ if (this._msDuration === null) {
+ this._msDuration = this.mediaSource.duration;
+ }
+
+ if (this._live === true && config.liveDurationInfinity === true) {
+ // Override duration to Infinity
+ logger["logger"].log('Media Source duration is set to Infinity');
+ this._msDuration = this.mediaSource.duration = Infinity;
+ } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Object(number["isFiniteNumber"])(duration)) {
+ // levelDuration was the last value we set.
+ // not using mediaSource.duration as the browser may tweak this value
+ // only update Media Source duration if its value increase, this is to avoid
+ // flushing already buffered portion when switching between quality level
+ logger["logger"].log("Updating Media Source duration to " + this._levelDuration.toFixed(3));
+ this._msDuration = this.mediaSource.duration = this._levelDuration;
+ }
+ };
+
+ _proto.doFlush = function doFlush() {
+ // loop through all buffer ranges to flush
+ while (this.flushRange.length) {
+ var range = this.flushRange[0]; // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
+
+ if (this.flushBuffer(range.start, range.end, range.type)) {
+ // range flushed, remove from flush array
+ this.flushRange.shift();
+ this.flushBufferCounter = 0;
+ } else {
+ this._needsFlush = true; // avoid looping, wait for SB update end to retrigger a flush
+
+ return;
+ }
+ }
+
+ if (this.flushRange.length === 0) {
+ // everything flushed
+ this._needsFlush = false; // let's recompute this.appended, which is used to avoid flush looping
+
+ var appended = 0;
+ var sourceBuffer = this.sourceBuffer;
+
+ try {
+ for (var type in sourceBuffer) {
+ var sb = sourceBuffer[type];
+
+ if (sb) {
+ appended += sb.buffered.length;
+ }
+ }
+ } catch (error) {
+ // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
+ // this is harmess at this stage, catch this to avoid reporting an internal exception
+ logger["logger"].error('error while accessing sourceBuffer.buffered');
+ }
+
+ this.appended = appended;
+ this.hls.trigger(events["default"].BUFFER_FLUSHED);
+ }
+ };
+
+ _proto.doAppending = function doAppending() {
+ var config = this.config,
+ hls = this.hls,
+ segments = this.segments,
+ sourceBuffer = this.sourceBuffer;
+
+ if (!Object.keys(sourceBuffer).length) {
+ // early exit if no source buffers have been initialized yet
+ return;
+ }
+
+ if (!this.media || this.media.error) {
+ this.segments = [];
+ logger["logger"].error('trying to append although a media error occured, flush segment and abort');
+ return;
+ }
+
+ if (this.appending) {
+ // logger.log(`sb appending in progress`);
+ return;
+ }
+
+ var segment = segments.shift();
+
+ if (!segment) {
+ // handle undefined shift
+ return;
+ }
+
+ try {
+ var sb = sourceBuffer[segment.type];
+
+ if (!sb) {
+ // in case we don't have any source buffer matching with this segment type,
+ // it means that Mediasource fails to create sourcebuffer
+ // discard this segment, and trigger update end
+ this._onSBUpdateEnd();
+
+ return;
+ }
+
+ if (sb.updating) {
+ // if we are still updating the source buffer from the last segment, place this back at the front of the queue
+ segments.unshift(segment);
+ return;
+ } // reset sourceBuffer ended flag before appending segment
+
+
+ sb.ended = false; // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
+
+ this.parent = segment.parent;
+ sb.appendBuffer(segment.data);
+ this.appendError = 0;
+ this.appended++;
+ this.appending = true;
+ } catch (err) {
+ // in case any error occured while appending, put back segment in segments table
+ logger["logger"].error("error while trying to append buffer:" + err.message);
+ segments.unshift(segment);
+ var event = {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ parent: segment.parent,
+ details: '',
+ fatal: false
+ };
+
+ if (err.code === 22) {
+ // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
+ // let's stop appending any segments, and report BUFFER_FULL_ERROR error
+ this.segments = [];
+ event.details = errors["ErrorDetails"].BUFFER_FULL_ERROR;
+ } else {
+ this.appendError++;
+ event.details = errors["ErrorDetails"].BUFFER_APPEND_ERROR;
+ /* with UHD content, we could get loop of quota exceeded error until
+ browser is able to evict some data from sourcebuffer. retrying help recovering this
+ */
+
+ if (this.appendError > config.appendErrorMaxRetry) {
+ logger["logger"].log("fail " + config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
+ this.segments = [];
+ event.fatal = true;
+ }
+ }
+
+ hls.trigger(events["default"].ERROR, event);
+ }
+ }
+ /*
+ flush specified buffered range,
+ return true once range has been flushed.
+ as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
+ */
+ ;
+
+ _proto.flushBuffer = function flushBuffer(startOffset, endOffset, sbType) {
+ var sourceBuffer = this.sourceBuffer; // exit if no sourceBuffers are initialized
+
+ if (!Object.keys(sourceBuffer).length) {
+ return true;
+ }
+
+ var currentTime = 'null';
+
+ if (this.media) {
+ currentTime = this.media.currentTime.toFixed(3);
+ }
+
+ logger["logger"].log("flushBuffer,pos/start/end: " + currentTime + "/" + startOffset + "/" + endOffset); // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
+
+ if (this.flushBufferCounter >= this.appended) {
+ logger["logger"].warn('abort flushing too many retries');
+ return true;
+ }
+
+ var sb = sourceBuffer[sbType]; // we are going to flush buffer, mark source buffer as 'not ended'
+
+ if (sb) {
+ sb.ended = false;
+
+ if (!sb.updating) {
+ if (this.removeBufferRange(sbType, sb, startOffset, endOffset)) {
+ this.flushBufferCounter++;
+ return false;
+ }
+ } else {
+ logger["logger"].warn('cannot flush, sb updating in progress');
+ return false;
+ }
+ }
+
+ logger["logger"].log('buffer flushed'); // everything flushed !
+
+ return true;
+ }
+ /**
+ * Removes first buffered range from provided source buffer that lies within given start and end offsets.
+ *
+ * @param {string} type Type of the source buffer, logging purposes only.
+ * @param {SourceBuffer} sb Target SourceBuffer instance.
+ * @param {number} startOffset
+ * @param {number} endOffset
+ *
+ * @returns {boolean} True when source buffer remove requested.
+ */
+ ;
+
+ _proto.removeBufferRange = function removeBufferRange(type, sb, startOffset, endOffset) {
+ try {
+ for (var i = 0; i < sb.buffered.length; i++) {
+ var bufStart = sb.buffered.start(i);
+ var bufEnd = sb.buffered.end(i);
+ var removeStart = Math.max(bufStart, startOffset);
+ var removeEnd = Math.min(bufEnd, endOffset);
+ /* sometimes sourcebuffer.remove() does not flush
+ the exact expected time range.
+ to avoid rounding issues/infinite loop,
+ only flush buffer range of length greater than 500ms.
+ */
+
+ if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
+ var currentTime = 'null';
+
+ if (this.media) {
+ currentTime = this.media.currentTime.toString();
+ }
+
+ logger["logger"].log("sb remove " + type + " [" + removeStart + "," + removeEnd + "], of [" + bufStart + "," + bufEnd + "], pos:" + currentTime);
+ sb.remove(removeStart, removeEnd);
+ return true;
+ }
+ }
+ } catch (error) {
+ logger["logger"].warn('removeBufferRange failed', error);
+ }
+
+ return false;
+ };
+
+ return BufferController;
+}(event_handler);
+
+/* harmony default export */ var buffer_controller = (buffer_controller_BufferController);
+// CONCATENATED MODULE: ./src/controller/cap-level-controller.js
+function cap_level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function cap_level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) cap_level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) cap_level_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function cap_level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * cap stream level to media size dimension controller
+*/
+
+
+
+var cap_level_controller_CapLevelController = /*#__PURE__*/function (_EventHandler) {
+ cap_level_controller_inheritsLoose(CapLevelController, _EventHandler);
+
+ function CapLevelController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].FPS_DROP_LEVEL_CAPPING, events["default"].MEDIA_ATTACHING, events["default"].MANIFEST_PARSED, events["default"].LEVELS_UPDATED, events["default"].BUFFER_CODECS, events["default"].MEDIA_DETACHING) || this;
+ _this.autoLevelCapping = Number.POSITIVE_INFINITY;
+ _this.firstLevel = null;
+ _this.levels = [];
+ _this.media = null;
+ _this.restrictedLevels = [];
+ _this.timer = null;
+ _this.clientRect = null;
+ return _this;
+ }
+
+ var _proto = CapLevelController.prototype;
+
+ _proto.destroy = function destroy() {
+ if (this.hls.config.capLevelToPlayerSize) {
+ this.media = null;
+ this.clientRect = null;
+ this.stopCapping();
+ }
+ };
+
+ _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {
+ // Don't add a restricted level more than once
+ if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
+ this.restrictedLevels.push(data.droppedLevel);
+ }
+ };
+
+ _proto.onMediaAttaching = function onMediaAttaching(data) {
+ this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
+ };
+
+ _proto.onManifestParsed = function onManifestParsed(data) {
+ var hls = this.hls;
+ this.restrictedLevels = [];
+ this.levels = data.levels;
+ this.firstLevel = data.firstLevel;
+
+ if (hls.config.capLevelToPlayerSize && data.video) {
+ // Start capping immediately if the manifest has signaled video codecs
+ this.startCapping();
+ }
+ } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
+ // to the first level
+ ;
+
+ _proto.onBufferCodecs = function onBufferCodecs(data) {
+ var hls = this.hls;
+
+ if (hls.config.capLevelToPlayerSize && data.video) {
+ // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
+ this.startCapping();
+ }
+ };
+
+ _proto.onLevelsUpdated = function onLevelsUpdated(data) {
+ this.levels = data.levels;
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ this.stopCapping();
+ };
+
+ _proto.detectPlayerSize = function detectPlayerSize() {
+ if (this.media) {
+ var levelsLength = this.levels ? this.levels.length : 0;
+
+ if (levelsLength) {
+ var hls = this.hls;
+ hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
+
+ if (hls.autoLevelCapping > this.autoLevelCapping) {
+ // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
+ // usually happen when the user go to the fullscreen mode.
+ hls.streamController.nextLevelSwitch();
+ }
+
+ this.autoLevelCapping = hls.autoLevelCapping;
+ }
+ }
+ }
+ /*
+ * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
+ */
+ ;
+
+ _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
+ var _this2 = this;
+
+ if (!this.levels) {
+ return -1;
+ }
+
+ var validLevels = this.levels.filter(function (level, index) {
+ return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
+ });
+ this.clientRect = null;
+ return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
+ };
+
+ _proto.startCapping = function startCapping() {
+ if (this.timer) {
+ // Don't reset capping if started twice; this can happen if the manifest signals a video codec
+ return;
+ }
+
+ this.autoLevelCapping = Number.POSITIVE_INFINITY;
+ this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
+ clearInterval(this.timer);
+ this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
+ this.detectPlayerSize();
+ };
+
+ _proto.stopCapping = function stopCapping() {
+ this.restrictedLevels = [];
+ this.firstLevel = null;
+ this.autoLevelCapping = Number.POSITIVE_INFINITY;
+
+ if (this.timer) {
+ this.timer = clearInterval(this.timer);
+ this.timer = null;
+ }
+ };
+
+ _proto.getDimensions = function getDimensions() {
+ if (this.clientRect) {
+ return this.clientRect;
+ }
+
+ var media = this.media;
+ var boundsRect = {
+ width: 0,
+ height: 0
+ };
+
+ if (media) {
+ var clientRect = media.getBoundingClientRect();
+ boundsRect.width = clientRect.width;
+ boundsRect.height = clientRect.height;
+
+ if (!boundsRect.width && !boundsRect.height) {
+ // When the media element has no width or height (equivalent to not being in the DOM),
+ // then use its width and height attributes (media.width, media.height)
+ boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
+ boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
+ }
+ }
+
+ this.clientRect = boundsRect;
+ return boundsRect;
+ };
+
+ CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
+ if (restrictedLevels === void 0) {
+ restrictedLevels = [];
+ }
+
+ return restrictedLevels.indexOf(level) === -1;
+ };
+
+ CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
+ if (!levels || levels && !levels.length) {
+ return -1;
+ } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
+ // to determine whether we've chosen the greatest bandwidth for the media's dimensions
+
+
+ var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
+ if (!nextLevel) {
+ return true;
+ }
+
+ return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
+ }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
+ // the max level
+
+
+ var maxLevelIndex = levels.length - 1;
+
+ for (var i = 0; i < levels.length; i += 1) {
+ var level = levels[i];
+
+ if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
+ maxLevelIndex = i;
+ break;
+ }
+ }
+
+ return maxLevelIndex;
+ };
+
+ cap_level_controller_createClass(CapLevelController, [{
+ key: "mediaWidth",
+ get: function get() {
+ return this.getDimensions().width * CapLevelController.contentScaleFactor;
+ }
+ }, {
+ key: "mediaHeight",
+ get: function get() {
+ return this.getDimensions().height * CapLevelController.contentScaleFactor;
+ }
+ }], [{
+ key: "contentScaleFactor",
+ get: function get() {
+ var pixelRatio = 1;
+
+ try {
+ pixelRatio = window.devicePixelRatio;
+ } catch (e) {}
+
+ return pixelRatio;
+ }
+ }]);
+
+ return CapLevelController;
+}(event_handler);
+
+/* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController);
+// CONCATENATED MODULE: ./src/controller/fps-controller.js
+function fps_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * FPS Controller
+*/
+
+
+
+var fps_controller_window = window,
+ fps_controller_performance = fps_controller_window.performance;
+
+var fps_controller_FPSController = /*#__PURE__*/function (_EventHandler) {
+ fps_controller_inheritsLoose(FPSController, _EventHandler);
+
+ function FPSController(hls) {
+ return _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING) || this;
+ }
+
+ var _proto = FPSController.prototype;
+
+ _proto.destroy = function destroy() {
+ if (this.timer) {
+ clearInterval(this.timer);
+ }
+
+ this.isVideoPlaybackQualityAvailable = false;
+ };
+
+ _proto.onMediaAttaching = function onMediaAttaching(data) {
+ var config = this.hls.config;
+
+ if (config.capLevelOnFPSDrop) {
+ var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
+
+ if (typeof video.getVideoPlaybackQuality === 'function') {
+ this.isVideoPlaybackQualityAvailable = true;
+ }
+
+ clearInterval(this.timer);
+ this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
+ }
+ };
+
+ _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
+ var currentTime = fps_controller_performance.now();
+
+ if (decodedFrames) {
+ if (this.lastTime) {
+ var currentPeriod = currentTime - this.lastTime,
+ currentDropped = droppedFrames - this.lastDroppedFrames,
+ currentDecoded = decodedFrames - this.lastDecodedFrames,
+ droppedFPS = 1000 * currentDropped / currentPeriod,
+ hls = this.hls;
+ hls.trigger(events["default"].FPS_DROP, {
+ currentDropped: currentDropped,
+ currentDecoded: currentDecoded,
+ totalDroppedFrames: droppedFrames
+ });
+
+ if (droppedFPS > 0) {
+ // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
+ if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
+ var currentLevel = hls.currentLevel;
+ logger["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
+
+ if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
+ currentLevel = currentLevel - 1;
+ hls.trigger(events["default"].FPS_DROP_LEVEL_CAPPING, {
+ level: currentLevel,
+ droppedLevel: hls.currentLevel
+ });
+ hls.autoLevelCapping = currentLevel;
+ hls.streamController.nextLevelSwitch();
+ }
+ }
+ }
+ }
+
+ this.lastTime = currentTime;
+ this.lastDroppedFrames = droppedFrames;
+ this.lastDecodedFrames = decodedFrames;
+ }
+ };
+
+ _proto.checkFPSInterval = function checkFPSInterval() {
+ var video = this.video;
+
+ if (video) {
+ if (this.isVideoPlaybackQualityAvailable) {
+ var videoPlaybackQuality = video.getVideoPlaybackQuality();
+ this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
+ } else {
+ this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
+ }
+ }
+ };
+
+ return FPSController;
+}(event_handler);
+
+/* harmony default export */ var fps_controller = (fps_controller_FPSController);
+// CONCATENATED MODULE: ./src/utils/xhr-loader.js
+/**
+ * XHR based logger
+*/
+
+
+var xhr_loader_XhrLoader = /*#__PURE__*/function () {
+ function XhrLoader(config) {
+ if (config && config.xhrSetup) {
+ this.xhrSetup = config.xhrSetup;
+ }
+ }
+
+ var _proto = XhrLoader.prototype;
+
+ _proto.destroy = function destroy() {
+ this.abort();
+ this.loader = null;
+ };
+
+ _proto.abort = function abort() {
+ var loader = this.loader;
+
+ if (loader && loader.readyState !== 4) {
+ this.stats.aborted = true;
+ loader.abort();
+ }
+
+ window.clearTimeout(this.requestTimeout);
+ this.requestTimeout = null;
+ window.clearTimeout(this.retryTimeout);
+ this.retryTimeout = null;
+ };
+
+ _proto.load = function load(context, config, callbacks) {
+ this.context = context;
+ this.config = config;
+ this.callbacks = callbacks;
+ this.stats = {
+ trequest: window.performance.now(),
+ retry: 0
+ };
+ this.retryDelay = config.retryDelay;
+ this.loadInternal();
+ };
+
+ _proto.loadInternal = function loadInternal() {
+ var xhr,
+ context = this.context;
+ xhr = this.loader = new window.XMLHttpRequest();
+ var stats = this.stats;
+ stats.tfirst = 0;
+ stats.loaded = 0;
+ var xhrSetup = this.xhrSetup;
+
+ try {
+ if (xhrSetup) {
+ try {
+ xhrSetup(xhr, context.url);
+ } catch (e) {
+ // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
+ // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
+ xhr.open('GET', context.url, true);
+ xhrSetup(xhr, context.url);
+ }
+ }
+
+ if (!xhr.readyState) {
+ xhr.open('GET', context.url, true);
+ }
+ } catch (e) {
+ // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
+ this.callbacks.onError({
+ code: xhr.status,
+ text: e.message
+ }, context, xhr);
+ return;
+ }
+
+ if (context.rangeEnd) {
+ xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
+ }
+
+ xhr.onreadystatechange = this.readystatechange.bind(this);
+ xhr.onprogress = this.loadprogress.bind(this);
+ xhr.responseType = context.responseType; // setup timeout before we perform request
+
+ this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
+ xhr.send();
+ };
+
+ _proto.readystatechange = function readystatechange(event) {
+ var xhr = event.currentTarget,
+ readyState = xhr.readyState,
+ stats = this.stats,
+ context = this.context,
+ config = this.config; // don't proceed if xhr has been aborted
+
+ if (stats.aborted) {
+ return;
+ } // >= HEADERS_RECEIVED
+
+
+ if (readyState >= 2) {
+ // clear xhr timeout and rearm it if readyState less than 4
+ window.clearTimeout(this.requestTimeout);
+
+ if (stats.tfirst === 0) {
+ stats.tfirst = Math.max(window.performance.now(), stats.trequest);
+ }
+
+ if (readyState === 4) {
+ var status = xhr.status; // http status between 200 to 299 are all successful
+
+ if (status >= 200 && status < 300) {
+ stats.tload = Math.max(stats.tfirst, window.performance.now());
+ var data, len;
+
+ if (context.responseType === 'arraybuffer') {
+ data = xhr.response;
+ len = data.byteLength;
+ } else {
+ data = xhr.responseText;
+ len = data.length;
+ }
+
+ stats.loaded = stats.total = len;
+ var response = {
+ url: xhr.responseURL,
+ data: data
+ };
+ this.callbacks.onSuccess(response, stats, context, xhr);
+ } else {
+ // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
+ if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
+ logger["logger"].error(status + " while loading " + context.url);
+ this.callbacks.onError({
+ code: status,
+ text: xhr.statusText
+ }, context, xhr);
+ } else {
+ // retry
+ logger["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // aborts and resets internal state
+
+ this.destroy(); // schedule retry
+
+ this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
+
+ this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
+ stats.retry++;
+ }
+ }
+ } else {
+ // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
+ this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
+ }
+ }
+ };
+
+ _proto.loadtimeout = function loadtimeout() {
+ logger["logger"].warn("timeout while loading " + this.context.url);
+ this.callbacks.onTimeout(this.stats, this.context, null);
+ };
+
+ _proto.loadprogress = function loadprogress(event) {
+ var xhr = event.currentTarget,
+ stats = this.stats;
+ stats.loaded = event.loaded;
+
+ if (event.lengthComputable) {
+ stats.total = event.total;
+ }
+
+ var onProgress = this.callbacks.onProgress;
+
+ if (onProgress) {
+ // third arg is to provide on progress data
+ onProgress(stats, this.context, null, xhr);
+ }
+ };
+
+ return XhrLoader;
+}();
+
+/* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader);
+// CONCATENATED MODULE: ./src/controller/audio-track-controller.js
+function audio_track_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function audio_track_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) audio_track_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) audio_track_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function audio_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+
+
+/**
+ * @class AudioTrackController
+ * @implements {EventHandler}
+ *
+ * Handles main manifest and audio-track metadata loaded,
+ * owns and exposes the selectable audio-tracks data-models.
+ *
+ * Exposes internal interface to select available audio-tracks.
+ *
+ * Handles errors on loading audio-track playlists. Manages fallback mechanism
+ * with redundants tracks (group-IDs).
+ *
+ * Handles level-loading and group-ID switches for video (fallback on video levels),
+ * and eventually adapts the audio-track group-ID to match.
+ *
+ * @fires AUDIO_TRACK_LOADING
+ * @fires AUDIO_TRACK_SWITCHING
+ * @fires AUDIO_TRACKS_UPDATED
+ * @fires ERROR
+ *
+ */
+
+var audio_track_controller_AudioTrackController = /*#__PURE__*/function (_TaskLoop) {
+ audio_track_controller_inheritsLoose(AudioTrackController, _TaskLoop);
+
+ function AudioTrackController(hls) {
+ var _this;
+
+ _this = _TaskLoop.call(this, hls, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_PARSED, events["default"].AUDIO_TRACK_LOADED, events["default"].AUDIO_TRACK_SWITCHED, events["default"].LEVEL_LOADED, events["default"].ERROR) || this;
+ /**
+ * @private
+ * Currently selected index in `tracks`
+ * @member {number} trackId
+ */
+
+ _this._trackId = -1;
+ /**
+ * @private
+ * If should select tracks according to default track attribute
+ * @member {boolean} _selectDefaultTrack
+ */
+
+ _this._selectDefaultTrack = true;
+ /**
+ * @public
+ * All tracks available
+ * @member {AudioTrack[]}
+ */
+
+ _this.tracks = [];
+ /**
+ * @public
+ * List of blacklisted audio track IDs (that have caused failure)
+ * @member {number[]}
+ */
+
+ _this.trackIdBlacklist = Object.create(null);
+ /**
+ * @public
+ * The currently running group ID for audio
+ * (we grab this on manifest-parsed and new level-loaded)
+ * @member {string}
+ */
+
+ _this.audioGroupId = null;
+ return _this;
+ }
+ /**
+ * Reset audio tracks on new manifest loading.
+ */
+
+
+ var _proto = AudioTrackController.prototype;
+
+ _proto.onManifestLoading = function onManifestLoading() {
+ this.tracks = [];
+ this._trackId = -1;
+ this._selectDefaultTrack = true;
+ }
+ /**
+ * Store tracks data from manifest parsed data.
+ *
+ * Trigger AUDIO_TRACKS_UPDATED event.
+ *
+ * @param {*} data
+ */
+ ;
+
+ _proto.onManifestParsed = function onManifestParsed(data) {
+ var tracks = this.tracks = data.audioTracks || [];
+ this.hls.trigger(events["default"].AUDIO_TRACKS_UPDATED, {
+ audioTracks: tracks
+ });
+
+ this._selectAudioGroup(this.hls.nextLoadLevel);
+ }
+ /**
+ * Store track details of loaded track in our data-model.
+ *
+ * Set-up metadata update interval task for live-mode streams.
+ *
+ * @param {*} data
+ */
+ ;
+
+ _proto.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
+ if (data.id >= this.tracks.length) {
+ logger["logger"].warn('Invalid audio track id:', data.id);
+ return;
+ }
+
+ logger["logger"].log("audioTrack " + data.id + " loaded");
+ this.tracks[data.id].details = data.details; // check if current playlist is a live playlist
+ // and if we have already our reload interval setup
+
+ if (data.details.live && !this.hasInterval()) {
+ // if live playlist we will have to reload it periodically
+ // set reload period to playlist target duration
+ var updatePeriodMs = data.details.targetduration * 1000;
+ this.setInterval(updatePeriodMs);
+ }
+
+ if (!data.details.live && this.hasInterval()) {
+ // playlist is not live and timer is scheduled: cancel it
+ this.clearInterval();
+ }
+ }
+ /**
+ * Update the internal group ID to any audio-track we may have set manually
+ * or because of a failure-handling fallback.
+ *
+ * Quality-levels should update to that group ID in this case.
+ *
+ * @param {*} data
+ */
+ ;
+
+ _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
+ var audioGroupId = this.tracks[data.id].groupId;
+
+ if (audioGroupId && this.audioGroupId !== audioGroupId) {
+ this.audioGroupId = audioGroupId;
+ }
+ }
+ /**
+ * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
+ * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
+ *
+ * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
+ * selected one (based on NAME property).
+ *
+ * @param {*} data
+ */
+ ;
+
+ _proto.onLevelLoaded = function onLevelLoaded(data) {
+ this._selectAudioGroup(data.level);
+ }
+ /**
+ * Handle network errors loading audio track manifests
+ * and also pausing on any netwok errors.
+ *
+ * @param {ErrorEventData} data
+ */
+ ;
+
+ _proto.onError = function onError(data) {
+ // Only handle network errors
+ if (data.type !== errors["ErrorTypes"].NETWORK_ERROR) {
+ return;
+ } // If fatal network error, cancel update task
+
+
+ if (data.fatal) {
+ this.clearInterval();
+ } // If not an audio-track loading error don't handle further
+
+
+ if (data.details !== errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR) {
+ return;
+ }
+
+ logger["logger"].warn('Network failure on audio-track id:', data.context.id);
+
+ this._handleLoadError();
+ }
+ /**
+ * @type {AudioTrack[]} Audio-track list we own
+ */
+ ;
+
+ /**
+ * @private
+ * @param {number} newId
+ */
+ _proto._setAudioTrack = function _setAudioTrack(newId) {
+ // noop on same audio track id as already set
+ if (this._trackId === newId && this.tracks[this._trackId].details) {
+ logger["logger"].debug('Same id as current audio-track passed, and track details available -> no-op');
+ return;
+ } // check if level idx is valid
+
+
+ if (newId < 0 || newId >= this.tracks.length) {
+ logger["logger"].warn('Invalid id passed to audio-track controller');
+ return;
+ }
+
+ var audioTrack = this.tracks[newId];
+ logger["logger"].log("Now switching to audio-track index " + newId); // stopping live reloading timer if any
+
+ this.clearInterval();
+ this._trackId = newId;
+ var url = audioTrack.url,
+ type = audioTrack.type,
+ id = audioTrack.id;
+ this.hls.trigger(events["default"].AUDIO_TRACK_SWITCHING, {
+ id: id,
+ type: type,
+ url: url
+ });
+
+ this._loadTrackDetailsIfNeeded(audioTrack);
+ }
+ /**
+ * @override
+ */
+ ;
+
+ _proto.doTick = function doTick() {
+ this._updateTrack(this._trackId);
+ }
+ /**
+ * @param levelId
+ * @private
+ */
+ ;
+
+ _proto._selectAudioGroup = function _selectAudioGroup(levelId) {
+ var levelInfo = this.hls.levels[levelId];
+
+ if (!levelInfo || !levelInfo.audioGroupIds) {
+ return;
+ }
+
+ var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
+
+ if (this.audioGroupId !== audioGroupId) {
+ this.audioGroupId = audioGroupId;
+
+ this._selectInitialAudioTrack();
+ }
+ }
+ /**
+ * Select initial track
+ * @private
+ */
+ ;
+
+ _proto._selectInitialAudioTrack = function _selectInitialAudioTrack() {
+ var _this2 = this;
+
+ var tracks = this.tracks;
+
+ if (!tracks.length) {
+ return;
+ }
+
+ var currentAudioTrack = this.tracks[this._trackId];
+ var name = null;
+
+ if (currentAudioTrack) {
+ name = currentAudioTrack.name;
+ } // Pre-select default tracks if there are any
+
+
+ if (this._selectDefaultTrack) {
+ var defaultTracks = tracks.filter(function (track) {
+ return track.default;
+ });
+
+ if (defaultTracks.length) {
+ tracks = defaultTracks;
+ } else {
+ logger["logger"].warn('No default audio tracks defined');
+ }
+ }
+
+ var trackFound = false;
+
+ var traverseTracks = function traverseTracks() {
+ // Select track with right group ID
+ tracks.forEach(function (track) {
+ if (trackFound) {
+ return;
+ } // We need to match the (pre-)selected group ID
+ // and the NAME of the current track.
+
+
+ if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {
+ // If there was a previous track try to stay with the same `NAME`.
+ // It should be unique across tracks of same group, and consistent through redundant track groups.
+ _this2._setAudioTrack(track.id);
+
+ trackFound = true;
+ }
+ });
+ };
+
+ traverseTracks();
+
+ if (!trackFound) {
+ name = null;
+ traverseTracks();
+ }
+
+ if (!trackFound) {
+ logger["logger"].error("No track found for running audio group-ID: " + this.audioGroupId);
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
+ fatal: true
+ });
+ }
+ }
+ /**
+ * @private
+ * @param {AudioTrack} audioTrack
+ * @returns {boolean}
+ */
+ ;
+
+ _proto._needsTrackLoading = function _needsTrackLoading(audioTrack) {
+ var details = audioTrack.details,
+ url = audioTrack.url;
+
+ if (!details || details.live) {
+ // check if we face an audio track embedded in main playlist (audio track without URI attribute)
+ return !!url;
+ }
+
+ return false;
+ }
+ /**
+ * @private
+ * @param {AudioTrack} audioTrack
+ */
+ ;
+
+ _proto._loadTrackDetailsIfNeeded = function _loadTrackDetailsIfNeeded(audioTrack) {
+ if (this._needsTrackLoading(audioTrack)) {
+ var url = audioTrack.url,
+ id = audioTrack.id; // track not retrieved yet, or live playlist we need to (re)load it
+
+ logger["logger"].log("loading audio-track playlist for id: " + id);
+ this.hls.trigger(events["default"].AUDIO_TRACK_LOADING, {
+ url: url,
+ id: id
+ });
+ }
+ }
+ /**
+ * @private
+ * @param {number} newId
+ */
+ ;
+
+ _proto._updateTrack = function _updateTrack(newId) {
+ // check if level idx is valid
+ if (newId < 0 || newId >= this.tracks.length) {
+ return;
+ } // stopping live reloading timer if any
+
+
+ this.clearInterval();
+ this._trackId = newId;
+ logger["logger"].log("trying to update audio-track " + newId);
+ var audioTrack = this.tracks[newId];
+
+ this._loadTrackDetailsIfNeeded(audioTrack);
+ }
+ /**
+ * @private
+ */
+ ;
+
+ _proto._handleLoadError = function _handleLoadError() {
+ // First, let's black list current track id
+ this.trackIdBlacklist[this._trackId] = true; // Let's try to fall back on a functional audio-track with the same group ID
+
+ var previousId = this._trackId;
+ var _this$tracks$previous = this.tracks[previousId],
+ name = _this$tracks$previous.name,
+ language = _this$tracks$previous.language,
+ groupId = _this$tracks$previous.groupId;
+ logger["logger"].warn("Loading failed on audio track id: " + previousId + ", group-id: " + groupId + ", name/language: \"" + name + "\" / \"" + language + "\""); // Find a non-blacklisted track ID with the same NAME
+ // At least a track that is not blacklisted, thus on another group-ID.
+
+ var newId = previousId;
+
+ for (var i = 0; i < this.tracks.length; i++) {
+ if (this.trackIdBlacklist[i]) {
+ continue;
+ }
+
+ var newTrack = this.tracks[i];
+
+ if (newTrack.name === name) {
+ newId = i;
+ break;
+ }
+ }
+
+ if (newId === previousId) {
+ logger["logger"].warn("No fallback audio-track found for name/language: \"" + name + "\" / \"" + language + "\"");
+ return;
+ }
+
+ logger["logger"].log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
+
+ this._setAudioTrack(newId);
+ };
+
+ audio_track_controller_createClass(AudioTrackController, [{
+ key: "audioTracks",
+ get: function get() {
+ return this.tracks;
+ }
+ /**
+ * @type {number} Index into audio-tracks list of currently selected track.
+ */
+
+ }, {
+ key: "audioTrack",
+ get: function get() {
+ return this._trackId;
+ }
+ /**
+ * Select current track by index
+ */
+ ,
+ set: function set(newId) {
+ this._setAudioTrack(newId); // If audio track is selected from API then don't choose from the manifest default track
+
+
+ this._selectDefaultTrack = false;
+ }
+ }]);
+
+ return AudioTrackController;
+}(TaskLoop);
+
+/* harmony default export */ var audio_track_controller = (audio_track_controller_AudioTrackController);
+// CONCATENATED MODULE: ./src/controller/audio-stream-controller.js
+
+
+
+
+function audio_stream_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function audio_stream_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) audio_stream_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) audio_stream_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function audio_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/*
+ * Audio Stream Controller
+*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var audio_stream_controller_window = window,
+ audio_stream_controller_performance = audio_stream_controller_window.performance;
+var audio_stream_controller_TICK_INTERVAL = 100; // how often to tick in ms
+
+var audio_stream_controller_AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
+ audio_stream_controller_inheritsLoose(AudioStreamController, _BaseStreamController);
+
+ function AudioStreamController(hls, fragmentTracker) {
+ var _this;
+
+ _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].AUDIO_TRACKS_UPDATED, events["default"].AUDIO_TRACK_SWITCHING, events["default"].AUDIO_TRACK_LOADED, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].FRAG_PARSING_INIT_SEGMENT, events["default"].FRAG_PARSING_DATA, events["default"].FRAG_PARSED, events["default"].ERROR, events["default"].BUFFER_RESET, events["default"].BUFFER_CREATED, events["default"].BUFFER_APPENDED, events["default"].BUFFER_FLUSHED, events["default"].INIT_PTS_FOUND) || this;
+ _this.fragmentTracker = fragmentTracker;
+ _this.config = hls.config;
+ _this.audioCodecSwap = false;
+ _this._state = State.STOPPED;
+ _this.initPTS = [];
+ _this.waitingFragment = null;
+ _this.videoTrackCC = null;
+ _this.waitingVideoCC = null;
+ return _this;
+ } // Signal that video PTS was found
+
+
+ var _proto = AudioStreamController.prototype;
+
+ _proto.onInitPtsFound = function onInitPtsFound(data) {
+ var demuxerId = data.id,
+ cc = data.frag.cc,
+ initPTS = data.initPTS;
+
+ if (demuxerId === 'main') {
+ // Always update the new INIT PTS
+ // Can change due level switch
+ this.initPTS[cc] = initPTS;
+ this.videoTrackCC = cc;
+ logger["logger"].log("InitPTS for cc: " + cc + " found from main: " + initPTS); // If we are waiting we need to demux/remux the waiting frag
+ // With the new initPTS
+
+ if (this.state === State.WAITING_INIT_PTS) {
+ this.tick();
+ }
+ }
+ };
+
+ _proto.startLoad = function startLoad(startPosition) {
+ if (this.tracks) {
+ var lastCurrentTime = this.lastCurrentTime;
+ this.stopLoad();
+ this.setInterval(audio_stream_controller_TICK_INTERVAL);
+ this.fragLoadError = 0;
+
+ if (lastCurrentTime > 0 && startPosition === -1) {
+ logger["logger"].log("audio:override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
+ this.state = State.IDLE;
+ } else {
+ this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
+ this.state = State.STARTING;
+ }
+
+ this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
+ this.tick();
+ } else {
+ this.startPosition = startPosition;
+ this.state = State.STOPPED;
+ }
+ };
+
+ _proto.doTick = function doTick() {
+ var pos,
+ track,
+ trackDetails,
+ hls = this.hls,
+ config = hls.config; // logger.log('audioStream:' + this.state);
+
+ switch (this.state) {
+ case State.ERROR: // don't do anything in error state to avoid breaking further ...
+
+ case State.PAUSED: // don't do anything in paused state either ...
+
+ case State.BUFFER_FLUSHING:
+ break;
+
+ case State.STARTING:
+ this.state = State.WAITING_TRACK;
+ this.loadedmetadata = false;
+ break;
+
+ case State.IDLE:
+ var tracks = this.tracks; // audio tracks not received => exit loop
+
+ if (!tracks) {
+ break;
+ } // if video not attached AND
+ // start fragment already requested OR start frag prefetch disable
+ // exit loop
+ // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
+
+
+ if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
+ break;
+ } // determine next candidate fragment to be loaded, based on current position and
+ // end of buffer position
+ // if we have not yet loaded any fragment, start loading from start position
+
+
+ if (this.loadedmetadata) {
+ pos = this.media.currentTime;
+ } else {
+ pos = this.nextLoadPosition;
+
+ if (pos === undefined) {
+ break;
+ }
+ }
+
+ var media = this.mediaBuffer ? this.mediaBuffer : this.media;
+ var videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;
+ var maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;
+ var bufferInfo = BufferHelper.bufferInfo(media, pos, maxBufferHole);
+ var mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, maxBufferHole);
+ var bufferLen = bufferInfo.len;
+ var bufferEnd = bufferInfo.end;
+ var fragPrevious = this.fragPrevious; // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
+ // whichever is smaller.
+ // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
+
+ var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
+ var maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);
+ var audioSwitch = this.audioSwitch;
+ var trackId = this.trackId; // if buffer length is less than maxBufLen try to load a new fragment
+
+ if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
+ trackDetails = tracks[trackId].details; // if track info not retrieved yet, switch state and wait for track retrieval
+
+ if (typeof trackDetails === 'undefined') {
+ this.state = State.WAITING_TRACK;
+ break;
+ }
+
+ if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
+ this.hls.trigger(events["default"].BUFFER_EOS, {
+ type: 'audio'
+ });
+ this.state = State.ENDED;
+ return;
+ } // find fragment index, contiguous with end of buffer position
+
+
+ var fragments = trackDetails.fragments,
+ fragLen = fragments.length,
+ start = fragments[0].start,
+ end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
+ frag; // When switching audio track, reload audio as close as possible to currentTime
+
+ if (audioSwitch) {
+ if (trackDetails.live && !trackDetails.PTSKnown) {
+ logger["logger"].log('switching audiotrack, live stream, unknown PTS,load first fragment');
+ bufferEnd = 0;
+ } else {
+ bufferEnd = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
+
+ if (trackDetails.PTSKnown && pos < start) {
+ // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
+ if (bufferInfo.end > start || bufferInfo.nextStart) {
+ logger["logger"].log('alt audio track ahead of main track, seek to start of alt audio track');
+ this.media.currentTime = start + 0.05;
+ } else {
+ return;
+ }
+ }
+ }
+ }
+
+ if (trackDetails.initSegment && !trackDetails.initSegment.data) {
+ frag = trackDetails.initSegment;
+ } // eslint-disable-line brace-style
+ // if bufferEnd before start of playlist, load first fragment
+ else if (bufferEnd <= start) {
+ frag = fragments[0];
+
+ if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
+ // Ensure we find a fragment which matches the continuity of the video track
+ frag = findFragWithCC(fragments, this.videoTrackCC);
+ }
+
+ if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
+ // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
+ // let's force seek to start
+ var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
+ logger["logger"].log("no alt audio available @currentTime:" + this.media.currentTime + ", seeking @" + (nextBuffered + 0.05));
+ this.media.currentTime = nextBuffered + 0.05;
+ return;
+ }
+ } else {
+ var foundFrag;
+ var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
+ var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
+
+ if (bufferEnd < end) {
+ if (bufferEnd > end - maxFragLookUpTolerance) {
+ maxFragLookUpTolerance = 0;
+ } // Prefer the next fragment if it's within tolerance
+
+
+ if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
+ foundFrag = fragNext;
+ } else {
+ foundFrag = binary_search.search(fragments, function (frag) {
+ return fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, frag);
+ });
+ }
+ } else {
+ // reach end of playlist
+ foundFrag = fragments[fragLen - 1];
+ }
+
+ if (foundFrag) {
+ frag = foundFrag;
+ start = foundFrag.start; // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
+
+ if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
+ if (frag.sn < trackDetails.endSN) {
+ frag = fragments[frag.sn + 1 - trackDetails.startSN];
+
+ if (this.fragmentTracker.getState(frag) !== FragmentState.OK) {
+ logger["logger"].log("SN just loaded, load next one: " + frag.sn);
+ }
+ } else {
+ frag = null;
+ }
+ }
+ }
+ }
+
+ if (frag) {
+ // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
+ if (frag.encrypted) {
+ logger["logger"].log("Loading key for " + frag.sn + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId);
+ this.state = State.KEY_LOADING;
+ hls.trigger(events["default"].KEY_LOADING, {
+ frag: frag
+ });
+ } else {
+ // only load if fragment is not loaded or if in audio switch
+ // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
+ this.fragCurrent = frag;
+
+ if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {
+ logger["logger"].log("Loading " + frag.sn + ", cc: " + frag.cc + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId + ", " + (this.loadedmetadata ? 'currentTime' : 'nextLoadPosition') + ": " + pos + ", bufferEnd: " + bufferEnd.toFixed(3));
+
+ if (frag.sn !== 'initSegment') {
+ this.startFragRequested = true;
+ }
+
+ if (Object(number["isFiniteNumber"])(frag.sn)) {
+ this.nextLoadPosition = frag.start + frag.duration;
+ }
+
+ hls.trigger(events["default"].FRAG_LOADING, {
+ frag: frag
+ });
+ this.state = State.FRAG_LOADING;
+ }
+ }
+ }
+ }
+
+ break;
+
+ case State.WAITING_TRACK:
+ track = this.tracks[this.trackId]; // check if playlist is already loaded
+
+ if (track && track.details) {
+ this.state = State.IDLE;
+ }
+
+ break;
+
+ case State.FRAG_LOADING_WAITING_RETRY:
+ var now = audio_stream_controller_performance.now();
+ var retryDate = this.retryDate;
+ media = this.media;
+ var isSeeking = media && media.seeking; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
+
+ if (!retryDate || now >= retryDate || isSeeking) {
+ logger["logger"].log('audioStreamController: retryDate reached, switch back to IDLE state');
+ this.state = State.IDLE;
+ }
+
+ break;
+
+ case State.WAITING_INIT_PTS:
+ // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
+ var waitingFrag = this.waitingFragment;
+
+ if (waitingFrag) {
+ var waitingFragCC = waitingFrag.frag.cc;
+
+ if (this.initPTS[waitingFragCC] !== undefined) {
+ this.waitingFragment = null;
+ this.state = State.FRAG_LOADING;
+ this.onFragLoaded(waitingFrag);
+ } else if (this.videoTrackCC !== this.waitingVideoCC) {
+ // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
+ logger["logger"].log("Waiting fragment cc (" + waitingFragCC + ") cancelled because video is at cc " + this.videoTrackCC);
+ this.clearWaitingFragment();
+ } else {
+ // Drop waiting fragment if an earlier fragment is needed
+ var _bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, this.media.currentTime, config.maxBufferHole);
+
+ var waitingFragmentAtPosition = fragmentWithinToleranceTest(_bufferInfo.end, config.maxFragLookUpTolerance, waitingFrag.frag);
+
+ if (waitingFragmentAtPosition < 0) {
+ logger["logger"].log("Waiting fragment cc (" + waitingFragCC + ") @ " + waitingFrag.frag.start + " cancelled because another fragment at " + _bufferInfo.end + " is needed");
+ this.clearWaitingFragment();
+ }
+ }
+ } else {
+ this.state = State.IDLE;
+ }
+
+ break;
+
+ case State.STOPPED:
+ case State.FRAG_LOADING:
+ case State.PARSING:
+ case State.PARSED:
+ case State.ENDED:
+ break;
+
+ default:
+ break;
+ }
+ };
+
+ _proto.clearWaitingFragment = function clearWaitingFragment() {
+ var waitingFrag = this.waitingFragment;
+
+ if (waitingFrag) {
+ this.fragmentTracker.removeFragment(waitingFrag.frag);
+ this.waitingFragment = null;
+ this.waitingVideoCC = null;
+ this.state = State.IDLE;
+ }
+ };
+
+ _proto.onMediaAttached = function onMediaAttached(data) {
+ var media = this.media = this.mediaBuffer = data.media;
+ this.onvseeking = this.onMediaSeeking.bind(this);
+ this.onvended = this.onMediaEnded.bind(this);
+ media.addEventListener('seeking', this.onvseeking);
+ media.addEventListener('ended', this.onvended);
+ var config = this.config;
+
+ if (this.tracks && config.autoStartLoad) {
+ this.startLoad(config.startPosition);
+ }
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ var media = this.media;
+
+ if (media && media.ended) {
+ logger["logger"].log('MSE detaching and video ended, reset startPosition');
+ this.startPosition = this.lastCurrentTime = 0;
+ } // remove video listeners
+
+
+ if (media) {
+ media.removeEventListener('seeking', this.onvseeking);
+ media.removeEventListener('ended', this.onvended);
+ this.onvseeking = this.onvseeked = this.onvended = null;
+ }
+
+ this.media = this.mediaBuffer = this.videoBuffer = null;
+ this.loadedmetadata = false;
+ this.fragmentTracker.removeAllFragments();
+ this.stopLoad();
+ };
+
+ _proto.onAudioTracksUpdated = function onAudioTracksUpdated(data) {
+ logger["logger"].log('audio tracks updated');
+ this.tracks = data.audioTracks;
+ };
+
+ _proto.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
+ // if any URL found on new audio track, it is an alternate audio track
+ var altAudio = !!data.url;
+ this.trackId = data.id;
+ this.fragCurrent = null;
+ this.clearWaitingFragment();
+ this.state = State.PAUSED; // destroy useless demuxer when switching audio to main
+
+ if (!altAudio) {
+ if (this.demuxer) {
+ this.demuxer.destroy();
+ this.demuxer = null;
+ }
+ } else {
+ // switching to audio track, start timer if not already started
+ this.setInterval(audio_stream_controller_TICK_INTERVAL);
+ } // should we switch tracks ?
+
+
+ if (altAudio) {
+ this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
+
+ this.state = State.IDLE;
+ }
+
+ this.tick();
+ };
+
+ _proto.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
+ var newDetails = data.details,
+ trackId = data.id,
+ track = this.tracks[trackId],
+ curDetails = track.details,
+ duration = newDetails.totalduration,
+ sliding = 0;
+ logger["logger"].log("track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
+
+ if (newDetails.live || curDetails && curDetails.live) {
+ if (curDetails && newDetails.fragments.length > 0) {
+ // we already have details for that level, merge them
+ mergeDetails(curDetails, newDetails);
+ sliding = newDetails.fragments[0].start; // TODO
+ // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
+
+ if (newDetails.PTSKnown) {
+ logger["logger"].log("live audio playlist sliding:" + sliding.toFixed(3));
+ } else {
+ logger["logger"].log('live audio playlist - outdated PTS, unknown sliding');
+ }
+ } else {
+ newDetails.PTSKnown = false;
+ logger["logger"].log('live audio playlist - first load, unknown sliding');
+ }
+ } else {
+ newDetails.PTSKnown = false;
+ }
+
+ track.details = newDetails; // compute start position
+
+ if (!this.startFragRequested) {
+ // compute start position if set to -1. use it straight away if value is defined
+ if (this.startPosition === -1) {
+ // first, check if start time offset has been set in playlist, if yes, use this value
+ var startTimeOffset = newDetails.startTimeOffset;
+
+ if (Object(number["isFiniteNumber"])(startTimeOffset)) {
+ logger["logger"].log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
+ this.startPosition = startTimeOffset;
+ } else {
+ if (newDetails.live) {
+ this.startPosition = this.computeLivePosition(sliding, newDetails);
+ logger["logger"].log("compute startPosition for audio-track to " + this.startPosition);
+ } else {
+ this.startPosition = 0;
+ }
+ }
+ }
+
+ this.nextLoadPosition = this.startPosition;
+ } // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
+
+
+ if (this.state === State.WAITING_TRACK) {
+ this.state = State.IDLE;
+ } // trigger handler right now
+
+
+ this.tick();
+ };
+
+ _proto.onKeyLoaded = function onKeyLoaded() {
+ if (this.state === State.KEY_LOADING) {
+ this.state = State.IDLE;
+ this.tick();
+ }
+ };
+
+ _proto.onFragLoaded = function onFragLoaded(data) {
+ var fragCurrent = this.fragCurrent,
+ fragLoaded = data.frag;
+
+ if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
+ var track = this.tracks[this.trackId],
+ details = track.details,
+ duration = details.totalduration,
+ trackId = fragCurrent.level,
+ sn = fragCurrent.sn,
+ cc = fragCurrent.cc,
+ audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
+ stats = this.stats = data.stats;
+
+ if (sn === 'initSegment') {
+ this.state = State.IDLE;
+ stats.tparsed = stats.tbuffered = audio_stream_controller_performance.now();
+ details.initSegment.data = data.payload;
+ this.hls.trigger(events["default"].FRAG_BUFFERED, {
+ stats: stats,
+ frag: fragCurrent,
+ id: 'audio'
+ });
+ this.tick();
+ } else {
+ this.state = State.PARSING; // transmux the MPEG-TS data to ISO-BMFF segments
+
+ this.appended = false;
+
+ if (!this.demuxer) {
+ this.demuxer = new demux_demuxer(this.hls, 'audio');
+ } // Check if we have video initPTS
+ // If not we need to wait for it
+
+
+ var initPTS = this.initPTS[cc];
+ var initSegmentData = details.initSegment ? details.initSegment.data : [];
+
+ if (initPTS !== undefined) {
+ this.pendingBuffering = true;
+ logger["logger"].log("Demuxing " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId); // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
+
+ var accurateTimeOffset = false; // details.PTSKnown || !details.live;
+
+ this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
+ } else {
+ logger["logger"].log("Unknown video PTS for cc " + cc + ", waiting for video PTS before demuxing audio frag " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
+ this.waitingFragment = data;
+ this.waitingVideoCC = this.videoTrackCC;
+ this.state = State.WAITING_INIT_PTS;
+ }
+ }
+ }
+
+ this.fragLoadError = 0;
+ };
+
+ _proto.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
+ var tracks = data.tracks,
+ track; // delete any video track found on audio demuxer
+
+ if (tracks.video) {
+ delete tracks.video;
+ } // include levelCodec in audio and video tracks
+
+
+ track = tracks.audio;
+
+ if (track) {
+ track.levelCodec = track.codec;
+ track.id = data.id;
+ this.hls.trigger(events["default"].BUFFER_CODECS, tracks);
+ logger["logger"].log("audio track:audio,container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
+ var initSegment = track.initSegment;
+
+ if (initSegment) {
+ var appendObj = {
+ type: 'audio',
+ data: initSegment,
+ parent: 'audio',
+ content: 'initSegment'
+ };
+
+ if (this.audioSwitch) {
+ this.pendingData = [appendObj];
+ } else {
+ this.appended = true; // arm pending Buffering flag before appending a segment
+
+ this.pendingBuffering = true;
+ this.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
+ }
+ } // trigger handler right now
+
+
+ this.tick();
+ }
+ }
+ };
+
+ _proto.onFragParsingData = function onFragParsingData(data) {
+ var _this2 = this;
+
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
+ var trackId = this.trackId,
+ track = this.tracks[trackId],
+ hls = this.hls;
+
+ if (!Object(number["isFiniteNumber"])(data.endPTS)) {
+ data.endPTS = data.startPTS + fragCurrent.duration;
+ data.endDTS = data.startDTS + fragCurrent.duration;
+ }
+
+ fragCurrent.addElementaryStream(ElementaryStreamTypes.AUDIO);
+ logger["logger"].log("parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb);
+ updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
+ var media = this.media;
+ var appendOnBufferFlush = false; // Only flush audio from old audio tracks when PTS is known on new audio track
+
+ if (this.audioSwitch) {
+ if (media && media.readyState) {
+ var currentTime = media.currentTime;
+ logger["logger"].log('switching audio track : currentTime:' + currentTime);
+
+ if (currentTime >= data.startPTS) {
+ logger["logger"].log('switching audio track : flushing all audio');
+ this.state = State.BUFFER_FLUSHING;
+ hls.trigger(events["default"].BUFFER_FLUSHING, {
+ startOffset: 0,
+ endOffset: Number.POSITIVE_INFINITY,
+ type: 'audio'
+ });
+ appendOnBufferFlush = true; // Lets announce that the initial audio track switch flush occur
+
+ this.audioSwitch = false;
+ hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
+ id: trackId
+ });
+ }
+ } else {
+ // Lets announce that the initial audio track switch flush occur
+ this.audioSwitch = false;
+ hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
+ id: trackId
+ });
+ }
+ }
+
+ var pendingData = this.pendingData;
+
+ if (!pendingData) {
+ logger["logger"].warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
+ hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].MEDIA_ERROR,
+ details: null,
+ fatal: true
+ });
+ return;
+ }
+
+ if (!this.audioSwitch) {
+ [data.data1, data.data2].forEach(function (buffer) {
+ if (buffer && buffer.length) {
+ pendingData.push({
+ type: data.type,
+ data: buffer,
+ parent: 'audio',
+ content: 'data'
+ });
+ }
+ });
+
+ if (!appendOnBufferFlush && pendingData.length) {
+ pendingData.forEach(function (appendObj) {
+ // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
+ // in that case it is useless to append following segments
+ if (_this2.state === State.PARSING) {
+ // arm pending Buffering flag before appending a segment
+ _this2.pendingBuffering = true;
+
+ _this2.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
+ }
+ });
+ this.pendingData = [];
+ this.appended = true;
+ }
+ } // trigger handler right now
+
+
+ this.tick();
+ }
+ };
+
+ _proto.onFragParsed = function onFragParsed(data) {
+ var fragCurrent = this.fragCurrent;
+ var fragNew = data.frag;
+
+ if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
+ this.stats.tparsed = audio_stream_controller_performance.now();
+ this.state = State.PARSED;
+
+ this._checkAppendedParsed();
+ }
+ };
+
+ _proto.onBufferReset = function onBufferReset() {
+ // reset reference to sourcebuffers
+ this.mediaBuffer = this.videoBuffer = null;
+ this.loadedmetadata = false;
+ };
+
+ _proto.onBufferCreated = function onBufferCreated(data) {
+ var audioTrack = data.tracks.audio;
+
+ if (audioTrack) {
+ this.mediaBuffer = audioTrack.buffer;
+ this.loadedmetadata = true;
+ }
+
+ if (data.tracks.video) {
+ this.videoBuffer = data.tracks.video.buffer;
+ }
+ };
+
+ _proto.onBufferAppended = function onBufferAppended(data) {
+ if (data.parent === 'audio') {
+ var state = this.state;
+
+ if (state === State.PARSING || state === State.PARSED) {
+ // check if all buffers have been appended
+ this.pendingBuffering = data.pending > 0;
+
+ this._checkAppendedParsed();
+ }
+ }
+ };
+
+ _proto._checkAppendedParsed = function _checkAppendedParsed() {
+ // trigger handler right now
+ if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
+ var frag = this.fragCurrent,
+ stats = this.stats,
+ hls = this.hls;
+
+ if (frag) {
+ this.fragPrevious = frag;
+ stats.tbuffered = audio_stream_controller_performance.now();
+ hls.trigger(events["default"].FRAG_BUFFERED, {
+ stats: stats,
+ frag: frag,
+ id: 'audio'
+ });
+ var media = this.mediaBuffer ? this.mediaBuffer : this.media;
+
+ if (media) {
+ logger["logger"].log("audio buffered : " + time_ranges.toString(media.buffered));
+ }
+
+ if (this.audioSwitch && this.appended) {
+ this.audioSwitch = false;
+ hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
+ id: this.trackId
+ });
+ }
+
+ this.state = State.IDLE;
+ }
+
+ this.tick();
+ }
+ };
+
+ _proto.onError = function onError(data) {
+ var frag = data.frag; // don't handle frag error not related to audio fragment
+
+ if (frag && frag.type !== 'audio') {
+ return;
+ }
+
+ switch (data.details) {
+ case errors["ErrorDetails"].FRAG_LOAD_ERROR:
+ case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
+ var _frag = data.frag; // don't handle frag error not related to audio fragment
+
+ if (_frag && _frag.type !== 'audio') {
+ break;
+ }
+
+ if (!data.fatal) {
+ var loadError = this.fragLoadError;
+
+ if (loadError) {
+ loadError++;
+ } else {
+ loadError = 1;
+ }
+
+ var config = this.config;
+
+ if (loadError <= config.fragLoadingMaxRetry) {
+ this.fragLoadError = loadError; // exponential backoff capped to config.fragLoadingMaxRetryTimeout
+
+ var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
+ logger["logger"].warn("AudioStreamController: frag loading failed, retry in " + delay + " ms");
+ this.retryDate = audio_stream_controller_performance.now() + delay; // retry loading state
+
+ this.state = State.FRAG_LOADING_WAITING_RETRY;
+ } else {
+ logger["logger"].error("AudioStreamController: " + data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
+
+ data.fatal = true;
+ this.state = State.ERROR;
+ }
+ }
+
+ break;
+
+ case errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
+ case errors["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
+ case errors["ErrorDetails"].KEY_LOAD_ERROR:
+ case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
+ // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
+ if (this.state !== State.ERROR) {
+ // if fatal error, stop processing, otherwise move to IDLE to retry loading
+ this.state = data.fatal ? State.ERROR : State.IDLE;
+ logger["logger"].warn("AudioStreamController: " + data.details + " while loading frag, now switching to " + this.state + " state ...");
+ }
+
+ break;
+
+ case errors["ErrorDetails"].BUFFER_FULL_ERROR:
+ // if in appending state
+ if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {
+ var media = this.mediaBuffer,
+ currentTime = this.media.currentTime,
+ mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5); // reduce max buf len if current position is buffered
+
+ if (mediaBuffered) {
+ var _config = this.config;
+
+ if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
+ // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
+ _config.maxMaxBufferLength /= 2;
+ logger["logger"].warn("AudioStreamController: reduce max buffer length to " + _config.maxMaxBufferLength + "s");
+ }
+
+ this.state = State.IDLE;
+ } else {
+ // current position is not buffered, but browser is still complaining about buffer full error
+ // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
+ // in that case flush the whole audio buffer to recover
+ logger["logger"].warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
+ this.fragCurrent = null; // flush everything
+
+ this.state = State.BUFFER_FLUSHING;
+ this.hls.trigger(events["default"].BUFFER_FLUSHING, {
+ startOffset: 0,
+ endOffset: Number.POSITIVE_INFINITY,
+ type: 'audio'
+ });
+ }
+ }
+
+ break;
+
+ default:
+ break;
+ }
+ };
+
+ _proto.onBufferFlushed = function onBufferFlushed() {
+ var _this3 = this;
+
+ var pendingData = this.pendingData;
+
+ if (pendingData && pendingData.length) {
+ logger["logger"].log('AudioStreamController: appending pending audio data after buffer flushed');
+ pendingData.forEach(function (appendObj) {
+ _this3.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
+ });
+ this.appended = true;
+ this.pendingData = [];
+ this.state = State.PARSED;
+ } else {
+ // move to IDLE once flush complete. this should trigger new fragment loading
+ this.state = State.IDLE; // reset reference to frag
+
+ this.fragPrevious = null;
+ this.tick();
+ }
+ };
+
+ audio_stream_controller_createClass(AudioStreamController, [{
+ key: "state",
+ set: function set(nextState) {
+ if (this.state !== nextState) {
+ var previousState = this.state;
+ this._state = nextState;
+ logger["logger"].log("audio stream:" + previousState + "->" + nextState);
+ }
+ },
+ get: function get() {
+ return this._state;
+ }
+ }]);
+
+ return AudioStreamController;
+}(base_stream_controller_BaseStreamController);
+
+/* harmony default export */ var audio_stream_controller = (audio_stream_controller_AudioStreamController);
+// CONCATENATED MODULE: ./src/utils/vttcue.js
+/**
+ * Copyright 2013 vtt.js Contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/* harmony default export */ var vttcue = ((function () {
+ if (typeof window !== 'undefined' && window.VTTCue) {
+ return window.VTTCue;
+ }
+
+ var autoKeyword = 'auto';
+ var directionSetting = {
+ '': true,
+ lr: true,
+ rl: true
+ };
+ var alignSetting = {
+ start: true,
+ middle: true,
+ end: true,
+ left: true,
+ right: true
+ };
+
+ function findDirectionSetting(value) {
+ if (typeof value !== 'string') {
+ return false;
+ }
+
+ var dir = directionSetting[value.toLowerCase()];
+ return dir ? value.toLowerCase() : false;
+ }
+
+ function findAlignSetting(value) {
+ if (typeof value !== 'string') {
+ return false;
+ }
+
+ var align = alignSetting[value.toLowerCase()];
+ return align ? value.toLowerCase() : false;
+ }
+
+ function extend(obj) {
+ var i = 1;
+
+ for (; i < arguments.length; i++) {
+ var cobj = arguments[i];
+
+ for (var p in cobj) {
+ obj[p] = cobj[p];
+ }
+ }
+
+ return obj;
+ }
+
+ function VTTCue(startTime, endTime, text) {
+ var cue = this;
+ var baseObj = {};
+ baseObj.enumerable = true;
+ /**
+ * Shim implementation specific properties. These properties are not in
+ * the spec.
+ */
+ // Lets us know when the VTTCue's data has changed in such a way that we need
+ // to recompute its display state. This lets us compute its display state
+ // lazily.
+
+ cue.hasBeenReset = false;
+ /**
+ * VTTCue and TextTrackCue properties
+ * http://dev.w3.org/html5/webvtt/#vttcue-interface
+ */
+
+ var _id = '';
+ var _pauseOnExit = false;
+ var _startTime = startTime;
+ var _endTime = endTime;
+ var _text = text;
+ var _region = null;
+ var _vertical = '';
+ var _snapToLines = true;
+ var _line = 'auto';
+ var _lineAlign = 'start';
+ var _position = 50;
+ var _positionAlign = 'middle';
+ var _size = 50;
+ var _align = 'middle';
+ Object.defineProperty(cue, 'id', extend({}, baseObj, {
+ get: function get() {
+ return _id;
+ },
+ set: function set(value) {
+ _id = '' + value;
+ }
+ }));
+ Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
+ get: function get() {
+ return _pauseOnExit;
+ },
+ set: function set(value) {
+ _pauseOnExit = !!value;
+ }
+ }));
+ Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
+ get: function get() {
+ return _startTime;
+ },
+ set: function set(value) {
+ if (typeof value !== 'number') {
+ throw new TypeError('Start time must be set to a number.');
+ }
+
+ _startTime = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
+ get: function get() {
+ return _endTime;
+ },
+ set: function set(value) {
+ if (typeof value !== 'number') {
+ throw new TypeError('End time must be set to a number.');
+ }
+
+ _endTime = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'text', extend({}, baseObj, {
+ get: function get() {
+ return _text;
+ },
+ set: function set(value) {
+ _text = '' + value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'region', extend({}, baseObj, {
+ get: function get() {
+ return _region;
+ },
+ set: function set(value) {
+ _region = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
+ get: function get() {
+ return _vertical;
+ },
+ set: function set(value) {
+ var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
+
+ if (setting === false) {
+ throw new SyntaxError('An invalid or illegal string was specified.');
+ }
+
+ _vertical = setting;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
+ get: function get() {
+ return _snapToLines;
+ },
+ set: function set(value) {
+ _snapToLines = !!value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'line', extend({}, baseObj, {
+ get: function get() {
+ return _line;
+ },
+ set: function set(value) {
+ if (typeof value !== 'number' && value !== autoKeyword) {
+ throw new SyntaxError('An invalid number or illegal string was specified.');
+ }
+
+ _line = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
+ get: function get() {
+ return _lineAlign;
+ },
+ set: function set(value) {
+ var setting = findAlignSetting(value);
+
+ if (!setting) {
+ throw new SyntaxError('An invalid or illegal string was specified.');
+ }
+
+ _lineAlign = setting;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'position', extend({}, baseObj, {
+ get: function get() {
+ return _position;
+ },
+ set: function set(value) {
+ if (value < 0 || value > 100) {
+ throw new Error('Position must be between 0 and 100.');
+ }
+
+ _position = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
+ get: function get() {
+ return _positionAlign;
+ },
+ set: function set(value) {
+ var setting = findAlignSetting(value);
+
+ if (!setting) {
+ throw new SyntaxError('An invalid or illegal string was specified.');
+ }
+
+ _positionAlign = setting;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'size', extend({}, baseObj, {
+ get: function get() {
+ return _size;
+ },
+ set: function set(value) {
+ if (value < 0 || value > 100) {
+ throw new Error('Size must be between 0 and 100.');
+ }
+
+ _size = value;
+ this.hasBeenReset = true;
+ }
+ }));
+ Object.defineProperty(cue, 'align', extend({}, baseObj, {
+ get: function get() {
+ return _align;
+ },
+ set: function set(value) {
+ var setting = findAlignSetting(value);
+
+ if (!setting) {
+ throw new SyntaxError('An invalid or illegal string was specified.');
+ }
+
+ _align = setting;
+ this.hasBeenReset = true;
+ }
+ }));
+ /**
+ * Other <track> spec defined properties
+ */
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
+
+ cue.displayState = void 0;
+ }
+ /**
+ * VTTCue methods
+ */
+
+
+ VTTCue.prototype.getCueAsHTML = function () {
+ // Assume WebVTT.convertCueToDOMTree is on the global.
+ var WebVTT = window.WebVTT;
+ return WebVTT.convertCueToDOMTree(window, this.text);
+ };
+
+ return VTTCue;
+})());
+// CONCATENATED MODULE: ./src/utils/vttparser.js
+/*
+ * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
+ */
+
+
+var StringDecoder = function StringDecoder() {
+ return {
+ decode: function decode(data) {
+ if (!data) {
+ return '';
+ }
+
+ if (typeof data !== 'string') {
+ throw new Error('Error - expected string data.');
+ }
+
+ return decodeURIComponent(encodeURIComponent(data));
+ }
+ };
+};
+
+function VTTParser() {
+ this.window = window;
+ this.state = 'INITIAL';
+ this.buffer = '';
+ this.decoder = new StringDecoder();
+ this.regionList = [];
+} // Try to parse input as a time stamp.
+
+
+function parseTimeStamp(input) {
+ function computeSeconds(h, m, s, f) {
+ return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
+ }
+
+ var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
+
+ if (!m) {
+ return null;
+ }
+
+ if (m[3]) {
+ // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
+ return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
+ } else if (m[1] > 59) {
+ // Timestamp takes the form of [hours]:[minutes].[milliseconds]
+ // First position is hours as it's over 59.
+ return computeSeconds(m[1], m[2], 0, m[4]);
+ } else {
+ // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
+ return computeSeconds(0, m[1], m[2], m[4]);
+ }
+} // A settings object holds key/value pairs and will ignore anything but the first
+// assignment to a specific key.
+
+
+function Settings() {
+ this.values = Object.create(null);
+}
+
+Settings.prototype = {
+ // Only accept the first assignment to any key.
+ set: function set(k, v) {
+ if (!this.get(k) && v !== '') {
+ this.values[k] = v;
+ }
+ },
+ // Return the value for a key, or a default value.
+ // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
+ // a number of possible default values as properties where 'defaultKey' is
+ // the key of the property that will be chosen; otherwise it's assumed to be
+ // a single value.
+ get: function get(k, dflt, defaultKey) {
+ if (defaultKey) {
+ return this.has(k) ? this.values[k] : dflt[defaultKey];
+ }
+
+ return this.has(k) ? this.values[k] : dflt;
+ },
+ // Check whether we have a value for a key.
+ has: function has(k) {
+ return k in this.values;
+ },
+ // Accept a setting if its one of the given alternatives.
+ alt: function alt(k, v, a) {
+ for (var n = 0; n < a.length; ++n) {
+ if (v === a[n]) {
+ this.set(k, v);
+ break;
+ }
+ }
+ },
+ // Accept a setting if its a valid (signed) integer.
+ integer: function integer(k, v) {
+ if (/^-?\d+$/.test(v)) {
+ // integer
+ this.set(k, parseInt(v, 10));
+ }
+ },
+ // Accept a setting if its a valid percentage.
+ percent: function percent(k, v) {
+ var m;
+
+ if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
+ v = parseFloat(v);
+
+ if (v >= 0 && v <= 100) {
+ this.set(k, v);
+ return true;
+ }
+ }
+
+ return false;
+ }
+}; // Helper function to parse input into groups separated by 'groupDelim', and
+// interprete each group as a key/value pair separated by 'keyValueDelim'.
+
+function parseOptions(input, callback, keyValueDelim, groupDelim) {
+ var groups = groupDelim ? input.split(groupDelim) : [input];
+
+ for (var i in groups) {
+ if (typeof groups[i] !== 'string') {
+ continue;
+ }
+
+ var kv = groups[i].split(keyValueDelim);
+
+ if (kv.length !== 2) {
+ continue;
+ }
+
+ var k = kv[0];
+ var v = kv[1];
+ callback(k, v);
+ }
+}
+
+var defaults = new vttcue(0, 0, 0); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
+// Safari doesn't yet support this change, but FF and Chrome do.
+
+var center = defaults.align === 'middle' ? 'middle' : 'center';
+
+function parseCue(input, cue, regionList) {
+ // Remember the original input if we need to throw an error.
+ var oInput = input; // 4.1 WebVTT timestamp
+
+ function consumeTimeStamp() {
+ var ts = parseTimeStamp(input);
+
+ if (ts === null) {
+ throw new Error('Malformed timestamp: ' + oInput);
+ } // Remove time stamp from input.
+
+
+ input = input.replace(/^[^\sa-zA-Z-]+/, '');
+ return ts;
+ } // 4.4.2 WebVTT cue settings
+
+
+ function consumeCueSettings(input, cue) {
+ var settings = new Settings();
+ parseOptions(input, function (k, v) {
+ switch (k) {
+ case 'region':
+ // Find the last region we parsed with the same region id.
+ for (var i = regionList.length - 1; i >= 0; i--) {
+ if (regionList[i].id === v) {
+ settings.set(k, regionList[i].region);
+ break;
+ }
+ }
+
+ break;
+
+ case 'vertical':
+ settings.alt(k, v, ['rl', 'lr']);
+ break;
+
+ case 'line':
+ var vals = v.split(','),
+ vals0 = vals[0];
+ settings.integer(k, vals0);
+
+ if (settings.percent(k, vals0)) {
+ settings.set('snapToLines', false);
+ }
+
+ settings.alt(k, vals0, ['auto']);
+
+ if (vals.length === 2) {
+ settings.alt('lineAlign', vals[1], ['start', center, 'end']);
+ }
+
+ break;
+
+ case 'position':
+ vals = v.split(',');
+ settings.percent(k, vals[0]);
+
+ if (vals.length === 2) {
+ settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
+ }
+
+ break;
+
+ case 'size':
+ settings.percent(k, v);
+ break;
+
+ case 'align':
+ settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
+ break;
+ }
+ }, /:/, /\s/); // Apply default values for any missing fields.
+
+ cue.region = settings.get('region', null);
+ cue.vertical = settings.get('vertical', '');
+ var line = settings.get('line', 'auto');
+
+ if (line === 'auto' && defaults.line === -1) {
+ // set numeric line number for Safari
+ line = -1;
+ }
+
+ cue.line = line;
+ cue.lineAlign = settings.get('lineAlign', 'start');
+ cue.snapToLines = settings.get('snapToLines', true);
+ cue.size = settings.get('size', 100);
+ cue.align = settings.get('align', center);
+ var position = settings.get('position', 'auto');
+
+ if (position === 'auto' && defaults.position === 50) {
+ // set numeric position for Safari
+ position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
+ }
+
+ cue.position = position;
+ }
+
+ function skipWhitespace() {
+ input = input.replace(/^\s+/, '');
+ } // 4.1 WebVTT cue timings.
+
+
+ skipWhitespace();
+ cue.startTime = consumeTimeStamp(); // (1) collect cue start time
+
+ skipWhitespace();
+
+ if (input.substr(0, 3) !== '-->') {
+ // (3) next characters must match '-->'
+ throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
+ }
+
+ input = input.substr(3);
+ skipWhitespace();
+ cue.endTime = consumeTimeStamp(); // (5) collect cue end time
+ // 4.1 WebVTT cue settings list.
+
+ skipWhitespace();
+ consumeCueSettings(input, cue);
+}
+
+function fixLineBreaks(input) {
+ return input.replace(/<br(?: \/)?>/gi, '\n');
+}
+
+VTTParser.prototype = {
+ parse: function parse(data) {
+ var self = this; // If there is no data then we won't decode it, but will just try to parse
+ // whatever is in buffer already. This may occur in circumstances, for
+ // example when flush() is called.
+
+ if (data) {
+ // Try to decode the data that we received.
+ self.buffer += self.decoder.decode(data, {
+ stream: true
+ });
+ }
+
+ function collectNextLine() {
+ var buffer = self.buffer;
+ var pos = 0;
+ buffer = fixLineBreaks(buffer);
+
+ while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
+ ++pos;
+ }
+
+ var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
+
+ if (buffer[pos] === '\r') {
+ ++pos;
+ }
+
+ if (buffer[pos] === '\n') {
+ ++pos;
+ }
+
+ self.buffer = buffer.substr(pos);
+ return line;
+ } // 3.2 WebVTT metadata header syntax
+
+
+ function parseHeader(input) {
+ parseOptions(input, function (k, v) {
+ switch (k) {
+ case 'Region':
+ // 3.3 WebVTT region metadata header syntax
+ // console.log('parse region', v);
+ // parseRegion(v);
+ break;
+ }
+ }, /:/);
+ } // 5.1 WebVTT file parsing.
+
+
+ try {
+ var line;
+
+ if (self.state === 'INITIAL') {
+ // We can't start parsing until we have the first line.
+ if (!/\r\n|\n/.test(self.buffer)) {
+ return this;
+ }
+
+ line = collectNextLine(); // strip of UTF-8 BOM if any
+ // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
+
+ var m = line.match(/^()?WEBVTT([ \t].*)?$/);
+
+ if (!m || !m[0]) {
+ throw new Error('Malformed WebVTT signature.');
+ }
+
+ self.state = 'HEADER';
+ }
+
+ var alreadyCollectedLine = false;
+
+ while (self.buffer) {
+ // We can't parse a line until we have the full line.
+ if (!/\r\n|\n/.test(self.buffer)) {
+ return this;
+ }
+
+ if (!alreadyCollectedLine) {
+ line = collectNextLine();
+ } else {
+ alreadyCollectedLine = false;
+ }
+
+ switch (self.state) {
+ case 'HEADER':
+ // 13-18 - Allow a header (metadata) under the WEBVTT line.
+ if (/:/.test(line)) {
+ parseHeader(line);
+ } else if (!line) {
+ // An empty line terminates the header and starts the body (cues).
+ self.state = 'ID';
+ }
+
+ continue;
+
+ case 'NOTE':
+ // Ignore NOTE blocks.
+ if (!line) {
+ self.state = 'ID';
+ }
+
+ continue;
+
+ case 'ID':
+ // Check for the start of NOTE blocks.
+ if (/^NOTE($|[ \t])/.test(line)) {
+ self.state = 'NOTE';
+ break;
+ } // 19-29 - Allow any number of line terminators, then initialize new cue values.
+
+
+ if (!line) {
+ continue;
+ }
+
+ self.cue = new vttcue(0, 0, '');
+ self.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
+
+ if (line.indexOf('-->') === -1) {
+ self.cue.id = line;
+ continue;
+ }
+
+ // Process line as start of a cue.
+
+ /* falls through */
+
+ case 'CUE':
+ // 40 - Collect cue timings and settings.
+ try {
+ parseCue(line, self.cue, self.regionList);
+ } catch (e) {
+ // In case of an error ignore rest of the cue.
+ self.cue = null;
+ self.state = 'BADCUE';
+ continue;
+ }
+
+ self.state = 'CUETEXT';
+ continue;
+
+ case 'CUETEXT':
+ var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
+ // 35 - If we have the special substring '-->' then report the cue,
+ // but do not collect the line as we need to process the current
+ // one as a new cue.
+
+ if (!line || hasSubstring && (alreadyCollectedLine = true)) {
+ // We are done parsing self cue.
+ if (self.oncue) {
+ self.oncue(self.cue);
+ }
+
+ self.cue = null;
+ self.state = 'ID';
+ continue;
+ }
+
+ if (self.cue.text) {
+ self.cue.text += '\n';
+ }
+
+ self.cue.text += line;
+ continue;
+
+ case 'BADCUE':
+ // BADCUE
+ // 54-62 - Collect and discard the remaining cue.
+ if (!line) {
+ self.state = 'ID';
+ }
+
+ continue;
+ }
+ }
+ } catch (e) {
+ // If we are currently parsing a cue, report what we have.
+ if (self.state === 'CUETEXT' && self.cue && self.oncue) {
+ self.oncue(self.cue);
+ }
+
+ self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
+ // another exception occurred so enter BADCUE state.
+
+ self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
+ }
+
+ return this;
+ },
+ flush: function flush() {
+ var self = this;
+
+ try {
+ // Finish decoding the stream.
+ self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region.
+
+ if (self.cue || self.state === 'HEADER') {
+ self.buffer += '\n\n';
+ self.parse();
+ } // If we've flushed, parsed, and we're still on the INITIAL state then
+ // that means we don't have enough of the stream to parse the first
+ // line.
+
+
+ if (self.state === 'INITIAL') {
+ throw new Error('Malformed WebVTT signature.');
+ }
+ } catch (e) {
+ throw e;
+ }
+
+ if (self.onflush) {
+ self.onflush();
+ }
+
+ return this;
+ }
+};
+
+/* harmony default export */ var vttparser = (VTTParser);
+// CONCATENATED MODULE: ./src/utils/cues.ts
+
+function newCue(track, startTime, endTime, captionScreen) {
+ var result = [];
+ var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
+
+ var cue;
+ var indenting;
+ var indent;
+ var text;
+ var VTTCue = window.VTTCue || TextTrackCue;
+
+ for (var r = 0; r < captionScreen.rows.length; r++) {
+ row = captionScreen.rows[r];
+ indenting = true;
+ indent = 0;
+ text = '';
+
+ if (!row.isEmpty()) {
+ for (var c = 0; c < row.chars.length; c++) {
+ if (row.chars[c].uchar.match(/\s/) && indenting) {
+ indent++;
+ } else {
+ text += row.chars[c].uchar;
+ indenting = false;
+ }
+ } // To be used for cleaning-up orphaned roll-up captions
+
+
+ row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
+
+ if (startTime === endTime) {
+ endTime += 0.0001;
+ }
+
+ cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));
+
+ if (indent >= 16) {
+ indent--;
+ } else {
+ indent++;
+ } // VTTCue.line get's flakey when using controls, so let's now include line 13&14
+ // also, drop line 1 since it's to close to the top
+
+
+ if (navigator.userAgent.match(/Firefox\//)) {
+ cue.line = r + 1;
+ } else {
+ cue.line = r > 7 ? r - 2 : r + 1;
+ }
+
+ cue.align = 'left'; // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
+
+ cue.position = Math.max(0, Math.min(100, 100 * (indent / 32)));
+ result.push(cue);
+
+ if (track) {
+ track.addCue(cue);
+ }
+ }
+ }
+
+ return result;
+}
+// CONCATENATED MODULE: ./src/utils/cea-608-parser.ts
+
+/**
+ *
+ * This code was ported from the dash.js project at:
+ * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
+ * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
+ *
+ * The original copyright appears below:
+ *
+ * The copyright in this software is being made available under the BSD License,
+ * included below. This software may be subject to other third party and contributor
+ * rights, including patent rights, and no such rights are granted under this license.
+ *
+ * Copyright (c) 2015-2016, DASH Industry Forum.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation and/or
+ * other materials provided with the distribution.
+ * 2. Neither the name of Dash Industry Forum nor the names of its
+ * contributors may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
+ */
+
+var specialCea608CharsCodes = {
+ 0x2a: 0xe1,
+ // lowercase a, acute accent
+ 0x5c: 0xe9,
+ // lowercase e, acute accent
+ 0x5e: 0xed,
+ // lowercase i, acute accent
+ 0x5f: 0xf3,
+ // lowercase o, acute accent
+ 0x60: 0xfa,
+ // lowercase u, acute accent
+ 0x7b: 0xe7,
+ // lowercase c with cedilla
+ 0x7c: 0xf7,
+ // division symbol
+ 0x7d: 0xd1,
+ // uppercase N tilde
+ 0x7e: 0xf1,
+ // lowercase n tilde
+ 0x7f: 0x2588,
+ // Full block
+ // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
+ // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
+ // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
+ 0x80: 0xae,
+ // Registered symbol (R)
+ 0x81: 0xb0,
+ // degree sign
+ 0x82: 0xbd,
+ // 1/2 symbol
+ 0x83: 0xbf,
+ // Inverted (open) question mark
+ 0x84: 0x2122,
+ // Trademark symbol (TM)
+ 0x85: 0xa2,
+ // Cents symbol
+ 0x86: 0xa3,
+ // Pounds sterling
+ 0x87: 0x266a,
+ // Music 8'th note
+ 0x88: 0xe0,
+ // lowercase a, grave accent
+ 0x89: 0x20,
+ // transparent space (regular)
+ 0x8a: 0xe8,
+ // lowercase e, grave accent
+ 0x8b: 0xe2,
+ // lowercase a, circumflex accent
+ 0x8c: 0xea,
+ // lowercase e, circumflex accent
+ 0x8d: 0xee,
+ // lowercase i, circumflex accent
+ 0x8e: 0xf4,
+ // lowercase o, circumflex accent
+ 0x8f: 0xfb,
+ // lowercase u, circumflex accent
+ // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
+ // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
+ 0x90: 0xc1,
+ // capital letter A with acute
+ 0x91: 0xc9,
+ // capital letter E with acute
+ 0x92: 0xd3,
+ // capital letter O with acute
+ 0x93: 0xda,
+ // capital letter U with acute
+ 0x94: 0xdc,
+ // capital letter U with diaresis
+ 0x95: 0xfc,
+ // lowercase letter U with diaeresis
+ 0x96: 0x2018,
+ // opening single quote
+ 0x97: 0xa1,
+ // inverted exclamation mark
+ 0x98: 0x2a,
+ // asterisk
+ 0x99: 0x2019,
+ // closing single quote
+ 0x9a: 0x2501,
+ // box drawings heavy horizontal
+ 0x9b: 0xa9,
+ // copyright sign
+ 0x9c: 0x2120,
+ // Service mark
+ 0x9d: 0x2022,
+ // (round) bullet
+ 0x9e: 0x201c,
+ // Left double quotation mark
+ 0x9f: 0x201d,
+ // Right double quotation mark
+ 0xa0: 0xc0,
+ // uppercase A, grave accent
+ 0xa1: 0xc2,
+ // uppercase A, circumflex
+ 0xa2: 0xc7,
+ // uppercase C with cedilla
+ 0xa3: 0xc8,
+ // uppercase E, grave accent
+ 0xa4: 0xca,
+ // uppercase E, circumflex
+ 0xa5: 0xcb,
+ // capital letter E with diaresis
+ 0xa6: 0xeb,
+ // lowercase letter e with diaresis
+ 0xa7: 0xce,
+ // uppercase I, circumflex
+ 0xa8: 0xcf,
+ // uppercase I, with diaresis
+ 0xa9: 0xef,
+ // lowercase i, with diaresis
+ 0xaa: 0xd4,
+ // uppercase O, circumflex
+ 0xab: 0xd9,
+ // uppercase U, grave accent
+ 0xac: 0xf9,
+ // lowercase u, grave accent
+ 0xad: 0xdb,
+ // uppercase U, circumflex
+ 0xae: 0xab,
+ // left-pointing double angle quotation mark
+ 0xaf: 0xbb,
+ // right-pointing double angle quotation mark
+ // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
+ // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
+ 0xb0: 0xc3,
+ // Uppercase A, tilde
+ 0xb1: 0xe3,
+ // Lowercase a, tilde
+ 0xb2: 0xcd,
+ // Uppercase I, acute accent
+ 0xb3: 0xcc,
+ // Uppercase I, grave accent
+ 0xb4: 0xec,
+ // Lowercase i, grave accent
+ 0xb5: 0xd2,
+ // Uppercase O, grave accent
+ 0xb6: 0xf2,
+ // Lowercase o, grave accent
+ 0xb7: 0xd5,
+ // Uppercase O, tilde
+ 0xb8: 0xf5,
+ // Lowercase o, tilde
+ 0xb9: 0x7b,
+ // Open curly brace
+ 0xba: 0x7d,
+ // Closing curly brace
+ 0xbb: 0x5c,
+ // Backslash
+ 0xbc: 0x5e,
+ // Caret
+ 0xbd: 0x5f,
+ // Underscore
+ 0xbe: 0x7c,
+ // Pipe (vertical line)
+ 0xbf: 0x223c,
+ // Tilde operator
+ 0xc0: 0xc4,
+ // Uppercase A, umlaut
+ 0xc1: 0xe4,
+ // Lowercase A, umlaut
+ 0xc2: 0xd6,
+ // Uppercase O, umlaut
+ 0xc3: 0xf6,
+ // Lowercase o, umlaut
+ 0xc4: 0xdf,
+ // Esszett (sharp S)
+ 0xc5: 0xa5,
+ // Yen symbol
+ 0xc6: 0xa4,
+ // Generic currency sign
+ 0xc7: 0x2503,
+ // Box drawings heavy vertical
+ 0xc8: 0xc5,
+ // Uppercase A, ring
+ 0xc9: 0xe5,
+ // Lowercase A, ring
+ 0xca: 0xd8,
+ // Uppercase O, stroke
+ 0xcb: 0xf8,
+ // Lowercase o, strok
+ 0xcc: 0x250f,
+ // Box drawings heavy down and right
+ 0xcd: 0x2513,
+ // Box drawings heavy down and left
+ 0xce: 0x2517,
+ // Box drawings heavy up and right
+ 0xcf: 0x251b // Box drawings heavy up and left
+
+};
+/**
+ * Utils
+ */
+
+var getCharForByte = function getCharForByte(_byte) {
+ var charCode = _byte;
+
+ if (specialCea608CharsCodes.hasOwnProperty(_byte)) {
+ charCode = specialCea608CharsCodes[_byte];
+ }
+
+ return String.fromCharCode(charCode);
+};
+
+var NR_ROWS = 15;
+var NR_COLS = 100; // Tables to look up row from PAC data
+
+var rowsLowCh1 = {
+ 0x11: 1,
+ 0x12: 3,
+ 0x15: 5,
+ 0x16: 7,
+ 0x17: 9,
+ 0x10: 11,
+ 0x13: 12,
+ 0x14: 14
+};
+var rowsHighCh1 = {
+ 0x11: 2,
+ 0x12: 4,
+ 0x15: 6,
+ 0x16: 8,
+ 0x17: 10,
+ 0x13: 13,
+ 0x14: 15
+};
+var rowsLowCh2 = {
+ 0x19: 1,
+ 0x1A: 3,
+ 0x1D: 5,
+ 0x1E: 7,
+ 0x1F: 9,
+ 0x18: 11,
+ 0x1B: 12,
+ 0x1C: 14
+};
+var rowsHighCh2 = {
+ 0x19: 2,
+ 0x1A: 4,
+ 0x1D: 6,
+ 0x1E: 8,
+ 0x1F: 10,
+ 0x1B: 13,
+ 0x1C: 15
+};
+var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
+var VerboseLevel;
+
+(function (VerboseLevel) {
+ VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
+ VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
+ VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
+ VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
+ VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
+ VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
+})(VerboseLevel || (VerboseLevel = {}));
+
+var cea_608_parser_CaptionsLogger = /*#__PURE__*/function () {
+ function CaptionsLogger() {
+ this.time = null;
+ this.verboseLevel = VerboseLevel.ERROR;
+ }
+
+ var _proto = CaptionsLogger.prototype;
+
+ _proto.log = function log(severity, msg) {
+ if (this.verboseLevel >= severity) {
+ logger["logger"].log(this.time + " [" + severity + "] " + msg);
+ }
+ };
+
+ return CaptionsLogger;
+}();
+
+var numArrayToHexArray = function numArrayToHexArray(numArray) {
+ var hexArray = [];
+
+ for (var j = 0; j < numArray.length; j++) {
+ hexArray.push(numArray[j].toString(16));
+ }
+
+ return hexArray;
+};
+
+var PenState = /*#__PURE__*/function () {
+ function PenState(foreground, underline, italics, background, flash) {
+ this.foreground = void 0;
+ this.underline = void 0;
+ this.italics = void 0;
+ this.background = void 0;
+ this.flash = void 0;
+ this.foreground = foreground || 'white';
+ this.underline = underline || false;
+ this.italics = italics || false;
+ this.background = background || 'black';
+ this.flash = flash || false;
+ }
+
+ var _proto2 = PenState.prototype;
+
+ _proto2.reset = function reset() {
+ this.foreground = 'white';
+ this.underline = false;
+ this.italics = false;
+ this.background = 'black';
+ this.flash = false;
+ };
+
+ _proto2.setStyles = function setStyles(styles) {
+ var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
+
+ for (var i = 0; i < attribs.length; i++) {
+ var style = attribs[i];
+
+ if (styles.hasOwnProperty(style)) {
+ this[style] = styles[style];
+ }
+ }
+ };
+
+ _proto2.isDefault = function isDefault() {
+ return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
+ };
+
+ _proto2.equals = function equals(other) {
+ return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
+ };
+
+ _proto2.copy = function copy(newPenState) {
+ this.foreground = newPenState.foreground;
+ this.underline = newPenState.underline;
+ this.italics = newPenState.italics;
+ this.background = newPenState.background;
+ this.flash = newPenState.flash;
+ };
+
+ _proto2.toString = function toString() {
+ return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
+ };
+
+ return PenState;
+}();
+/**
+ * Unicode character with styling and background.
+ * @constructor
+ */
+
+
+var StyledUnicodeChar = /*#__PURE__*/function () {
+ function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
+ this.uchar = void 0;
+ this.penState = void 0;
+ this.uchar = uchar || ' '; // unicode character
+
+ this.penState = new PenState(foreground, underline, italics, background, flash);
+ }
+
+ var _proto3 = StyledUnicodeChar.prototype;
+
+ _proto3.reset = function reset() {
+ this.uchar = ' ';
+ this.penState.reset();
+ };
+
+ _proto3.setChar = function setChar(uchar, newPenState) {
+ this.uchar = uchar;
+ this.penState.copy(newPenState);
+ };
+
+ _proto3.setPenState = function setPenState(newPenState) {
+ this.penState.copy(newPenState);
+ };
+
+ _proto3.equals = function equals(other) {
+ return this.uchar === other.uchar && this.penState.equals(other.penState);
+ };
+
+ _proto3.copy = function copy(newChar) {
+ this.uchar = newChar.uchar;
+ this.penState.copy(newChar.penState);
+ };
+
+ _proto3.isEmpty = function isEmpty() {
+ return this.uchar === ' ' && this.penState.isDefault();
+ };
+
+ return StyledUnicodeChar;
+}();
+/**
+ * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
+ * @constructor
+ */
+
+
+var Row = /*#__PURE__*/function () {
+ function Row(logger) {
+ this.chars = void 0;
+ this.pos = void 0;
+ this.currPenState = void 0;
+ this.cueStartTime = void 0;
+ this.logger = void 0;
+ this.chars = [];
+
+ for (var i = 0; i < NR_COLS; i++) {
+ this.chars.push(new StyledUnicodeChar());
+ }
+
+ this.logger = logger;
+ this.pos = 0;
+ this.currPenState = new PenState();
+ }
+
+ var _proto4 = Row.prototype;
+
+ _proto4.equals = function equals(other) {
+ var equal = true;
+
+ for (var i = 0; i < NR_COLS; i++) {
+ if (!this.chars[i].equals(other.chars[i])) {
+ equal = false;
+ break;
+ }
+ }
+
+ return equal;
+ };
+
+ _proto4.copy = function copy(other) {
+ for (var i = 0; i < NR_COLS; i++) {
+ this.chars[i].copy(other.chars[i]);
+ }
+ };
+
+ _proto4.isEmpty = function isEmpty() {
+ var empty = true;
+
+ for (var i = 0; i < NR_COLS; i++) {
+ if (!this.chars[i].isEmpty()) {
+ empty = false;
+ break;
+ }
+ }
+
+ return empty;
+ }
+ /**
+ * Set the cursor to a valid column.
+ */
+ ;
+
+ _proto4.setCursor = function setCursor(absPos) {
+ if (this.pos !== absPos) {
+ this.pos = absPos;
+ }
+
+ if (this.pos < 0) {
+ this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
+ this.pos = 0;
+ } else if (this.pos > NR_COLS) {
+ this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
+ this.pos = NR_COLS;
+ }
+ }
+ /**
+ * Move the cursor relative to current position.
+ */
+ ;
+
+ _proto4.moveCursor = function moveCursor(relPos) {
+ var newPos = this.pos + relPos;
+
+ if (relPos > 1) {
+ for (var i = this.pos + 1; i < newPos + 1; i++) {
+ this.chars[i].setPenState(this.currPenState);
+ }
+ }
+
+ this.setCursor(newPos);
+ }
+ /**
+ * Backspace, move one step back and clear character.
+ */
+ ;
+
+ _proto4.backSpace = function backSpace() {
+ this.moveCursor(-1);
+ this.chars[this.pos].setChar(' ', this.currPenState);
+ };
+
+ _proto4.insertChar = function insertChar(_byte2) {
+ if (_byte2 >= 0x90) {
+ // Extended char
+ this.backSpace();
+ }
+
+ var _char = getCharForByte(_byte2);
+
+ if (this.pos >= NR_COLS) {
+ this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
+ return;
+ }
+
+ this.chars[this.pos].setChar(_char, this.currPenState);
+ this.moveCursor(1);
+ };
+
+ _proto4.clearFromPos = function clearFromPos(startPos) {
+ var i;
+
+ for (i = startPos; i < NR_COLS; i++) {
+ this.chars[i].reset();
+ }
+ };
+
+ _proto4.clear = function clear() {
+ this.clearFromPos(0);
+ this.pos = 0;
+ this.currPenState.reset();
+ };
+
+ _proto4.clearToEndOfRow = function clearToEndOfRow() {
+ this.clearFromPos(this.pos);
+ };
+
+ _proto4.getTextString = function getTextString() {
+ var chars = [];
+ var empty = true;
+
+ for (var i = 0; i < NR_COLS; i++) {
+ var _char2 = this.chars[i].uchar;
+
+ if (_char2 !== ' ') {
+ empty = false;
+ }
+
+ chars.push(_char2);
+ }
+
+ if (empty) {
+ return '';
+ } else {
+ return chars.join('');
+ }
+ };
+
+ _proto4.setPenStyles = function setPenStyles(styles) {
+ this.currPenState.setStyles(styles);
+ var currChar = this.chars[this.pos];
+ currChar.setPenState(this.currPenState);
+ };
+
+ return Row;
+}();
+/**
+ * Keep a CEA-608 screen of 32x15 styled characters
+ * @constructor
+ */
+
+var CaptionScreen = /*#__PURE__*/function () {
+ function CaptionScreen(logger) {
+ this.rows = void 0;
+ this.currRow = void 0;
+ this.nrRollUpRows = void 0;
+ this.lastOutputScreen = void 0;
+ this.logger = void 0;
+ this.rows = [];
+
+ for (var i = 0; i < NR_ROWS; i++) {
+ this.rows.push(new Row(logger));
+ } // Note that we use zero-based numbering (0-14)
+
+
+ this.logger = logger;
+ this.currRow = NR_ROWS - 1;
+ this.nrRollUpRows = null;
+ this.lastOutputScreen = null;
+ this.reset();
+ }
+
+ var _proto5 = CaptionScreen.prototype;
+
+ _proto5.reset = function reset() {
+ for (var i = 0; i < NR_ROWS; i++) {
+ this.rows[i].clear();
+ }
+
+ this.currRow = NR_ROWS - 1;
+ };
+
+ _proto5.equals = function equals(other) {
+ var equal = true;
+
+ for (var i = 0; i < NR_ROWS; i++) {
+ if (!this.rows[i].equals(other.rows[i])) {
+ equal = false;
+ break;
+ }
+ }
+
+ return equal;
+ };
+
+ _proto5.copy = function copy(other) {
+ for (var i = 0; i < NR_ROWS; i++) {
+ this.rows[i].copy(other.rows[i]);
+ }
+ };
+
+ _proto5.isEmpty = function isEmpty() {
+ var empty = true;
+
+ for (var i = 0; i < NR_ROWS; i++) {
+ if (!this.rows[i].isEmpty()) {
+ empty = false;
+ break;
+ }
+ }
+
+ return empty;
+ };
+
+ _proto5.backSpace = function backSpace() {
+ var row = this.rows[this.currRow];
+ row.backSpace();
+ };
+
+ _proto5.clearToEndOfRow = function clearToEndOfRow() {
+ var row = this.rows[this.currRow];
+ row.clearToEndOfRow();
+ }
+ /**
+ * Insert a character (without styling) in the current row.
+ */
+ ;
+
+ _proto5.insertChar = function insertChar(_char3) {
+ var row = this.rows[this.currRow];
+ row.insertChar(_char3);
+ };
+
+ _proto5.setPen = function setPen(styles) {
+ var row = this.rows[this.currRow];
+ row.setPenStyles(styles);
+ };
+
+ _proto5.moveCursor = function moveCursor(relPos) {
+ var row = this.rows[this.currRow];
+ row.moveCursor(relPos);
+ };
+
+ _proto5.setCursor = function setCursor(absPos) {
+ this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
+ var row = this.rows[this.currRow];
+ row.setCursor(absPos);
+ };
+
+ _proto5.setPAC = function setPAC(pacData) {
+ this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
+ var newRow = pacData.row - 1;
+
+ if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
+ newRow = this.nrRollUpRows - 1;
+ } // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
+
+
+ if (this.nrRollUpRows && this.currRow !== newRow) {
+ // clear all rows first
+ for (var i = 0; i < NR_ROWS; i++) {
+ this.rows[i].clear();
+ } // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
+ // topRowIndex - the start of rows to copy (inclusive index)
+
+
+ var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
+ // We use the cueStartTime value to check this.
+
+ var lastOutputScreen = this.lastOutputScreen;
+
+ if (lastOutputScreen) {
+ var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
+ var time = this.logger.time;
+
+ if (prevLineTime && time !== null && prevLineTime < time) {
+ for (var _i = 0; _i < this.nrRollUpRows; _i++) {
+ this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
+ }
+ }
+ }
+ }
+
+ this.currRow = newRow;
+ var row = this.rows[this.currRow];
+
+ if (pacData.indent !== null) {
+ var indent = pacData.indent;
+ var prevPos = Math.max(indent - 1, 0);
+ row.setCursor(pacData.indent);
+ pacData.color = row.chars[prevPos].penState.foreground;
+ }
+
+ var styles = {
+ foreground: pacData.color,
+ underline: pacData.underline,
+ italics: pacData.italics,
+ background: 'black',
+ flash: false
+ };
+ this.setPen(styles);
+ }
+ /**
+ * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
+ */
+ ;
+
+ _proto5.setBkgData = function setBkgData(bkgData) {
+ this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
+ this.backSpace();
+ this.setPen(bkgData);
+ this.insertChar(0x20); // Space
+ };
+
+ _proto5.setRollUpRows = function setRollUpRows(nrRows) {
+ this.nrRollUpRows = nrRows;
+ };
+
+ _proto5.rollUp = function rollUp() {
+ if (this.nrRollUpRows === null) {
+ this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
+ return; // Not properly setup
+ }
+
+ this.logger.log(VerboseLevel.TEXT, this.getDisplayText());
+ var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
+ var topRow = this.rows.splice(topRowIndex, 1)[0];
+ topRow.clear();
+ this.rows.splice(this.currRow, 0, topRow);
+ this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
+ }
+ /**
+ * Get all non-empty rows with as unicode text.
+ */
+ ;
+
+ _proto5.getDisplayText = function getDisplayText(asOneRow) {
+ asOneRow = asOneRow || false;
+ var displayText = [];
+ var text = '';
+ var rowNr = -1;
+
+ for (var i = 0; i < NR_ROWS; i++) {
+ var rowText = this.rows[i].getTextString();
+
+ if (rowText) {
+ rowNr = i + 1;
+
+ if (asOneRow) {
+ displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
+ } else {
+ displayText.push(rowText.trim());
+ }
+ }
+ }
+
+ if (displayText.length > 0) {
+ if (asOneRow) {
+ text = '[' + displayText.join(' | ') + ']';
+ } else {
+ text = displayText.join('\n');
+ }
+ }
+
+ return text;
+ };
+
+ _proto5.getTextAndFormat = function getTextAndFormat() {
+ return this.rows;
+ };
+
+ return CaptionScreen;
+}(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
+
+var Cea608Channel = /*#__PURE__*/function () {
+ function Cea608Channel(channelNumber, outputFilter, logger) {
+ this.chNr = void 0;
+ this.outputFilter = void 0;
+ this.mode = void 0;
+ this.verbose = void 0;
+ this.displayedMemory = void 0;
+ this.nonDisplayedMemory = void 0;
+ this.lastOutputScreen = void 0;
+ this.currRollUpRow = void 0;
+ this.writeScreen = void 0;
+ this.cueStartTime = void 0;
+ this.logger = void 0;
+ this.chNr = channelNumber;
+ this.outputFilter = outputFilter;
+ this.mode = null;
+ this.verbose = 0;
+ this.displayedMemory = new CaptionScreen(logger);
+ this.nonDisplayedMemory = new CaptionScreen(logger);
+ this.lastOutputScreen = new CaptionScreen(logger);
+ this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
+ this.writeScreen = this.displayedMemory;
+ this.mode = null;
+ this.cueStartTime = null; // Keeps track of where a cue started.
+
+ this.logger = logger;
+ }
+
+ var _proto6 = Cea608Channel.prototype;
+
+ _proto6.reset = function reset() {
+ this.mode = null;
+ this.displayedMemory.reset();
+ this.nonDisplayedMemory.reset();
+ this.lastOutputScreen.reset();
+ this.outputFilter.reset();
+ this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
+ this.writeScreen = this.displayedMemory;
+ this.mode = null;
+ this.cueStartTime = null;
+ };
+
+ _proto6.getHandler = function getHandler() {
+ return this.outputFilter;
+ };
+
+ _proto6.setHandler = function setHandler(newHandler) {
+ this.outputFilter = newHandler;
+ };
+
+ _proto6.setPAC = function setPAC(pacData) {
+ this.writeScreen.setPAC(pacData);
+ };
+
+ _proto6.setBkgData = function setBkgData(bkgData) {
+ this.writeScreen.setBkgData(bkgData);
+ };
+
+ _proto6.setMode = function setMode(newMode) {
+ if (newMode === this.mode) {
+ return;
+ }
+
+ this.mode = newMode;
+ this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);
+
+ if (this.mode === 'MODE_POP-ON') {
+ this.writeScreen = this.nonDisplayedMemory;
+ } else {
+ this.writeScreen = this.displayedMemory;
+ this.writeScreen.reset();
+ }
+
+ if (this.mode !== 'MODE_ROLL-UP') {
+ this.displayedMemory.nrRollUpRows = null;
+ this.nonDisplayedMemory.nrRollUpRows = null;
+ }
+
+ this.mode = newMode;
+ };
+
+ _proto6.insertChars = function insertChars(chars) {
+ for (var i = 0; i < chars.length; i++) {
+ this.writeScreen.insertChar(chars[i]);
+ }
+
+ var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
+ this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
+
+ if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
+ this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
+ this.outputDataUpdate();
+ }
+ };
+
+ _proto6.ccRCL = function ccRCL() {
+ // Resume Caption Loading (switch mode to Pop On)
+ this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
+ this.setMode('MODE_POP-ON');
+ };
+
+ _proto6.ccBS = function ccBS() {
+ // BackSpace
+ this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
+
+ if (this.mode === 'MODE_TEXT') {
+ return;
+ }
+
+ this.writeScreen.backSpace();
+
+ if (this.writeScreen === this.displayedMemory) {
+ this.outputDataUpdate();
+ }
+ };
+
+ _proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
+ };
+
+ _proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
+ };
+
+ _proto6.ccDER = function ccDER() {
+ // Delete to End of Row
+ this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
+ this.writeScreen.clearToEndOfRow();
+ this.outputDataUpdate();
+ };
+
+ _proto6.ccRU = function ccRU(nrRows) {
+ // Roll-Up Captions-2,3,or 4 Rows
+ this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
+ this.writeScreen = this.displayedMemory;
+ this.setMode('MODE_ROLL-UP');
+ this.writeScreen.setRollUpRows(nrRows);
+ };
+
+ _proto6.ccFON = function ccFON() {
+ // Flash On
+ this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
+ this.writeScreen.setPen({
+ flash: true
+ });
+ };
+
+ _proto6.ccRDC = function ccRDC() {
+ // Resume Direct Captioning (switch mode to PaintOn)
+ this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
+ this.setMode('MODE_PAINT-ON');
+ };
+
+ _proto6.ccTR = function ccTR() {
+ // Text Restart in text mode (not supported, however)
+ this.logger.log(VerboseLevel.INFO, 'TR');
+ this.setMode('MODE_TEXT');
+ };
+
+ _proto6.ccRTD = function ccRTD() {
+ // Resume Text Display in Text mode (not supported, however)
+ this.logger.log(VerboseLevel.INFO, 'RTD');
+ this.setMode('MODE_TEXT');
+ };
+
+ _proto6.ccEDM = function ccEDM() {
+ // Erase Displayed Memory
+ this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
+ this.displayedMemory.reset();
+ this.outputDataUpdate(true);
+ };
+
+ _proto6.ccCR = function ccCR() {
+ // Carriage Return
+ this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
+ this.writeScreen.rollUp();
+ this.outputDataUpdate(true);
+ };
+
+ _proto6.ccENM = function ccENM() {
+ // Erase Non-Displayed Memory
+ this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
+ this.nonDisplayedMemory.reset();
+ };
+
+ _proto6.ccEOC = function ccEOC() {
+ // End of Caption (Flip Memories)
+ this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');
+
+ if (this.mode === 'MODE_POP-ON') {
+ var tmp = this.displayedMemory;
+ this.displayedMemory = this.nonDisplayedMemory;
+ this.nonDisplayedMemory = tmp;
+ this.writeScreen = this.nonDisplayedMemory;
+ this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
+ }
+
+ this.outputDataUpdate(true);
+ };
+
+ _proto6.ccTO = function ccTO(nrCols) {
+ // Tab Offset 1,2, or 3 columns
+ this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
+ this.writeScreen.moveCursor(nrCols);
+ };
+
+ _proto6.ccMIDROW = function ccMIDROW(secondByte) {
+ // Parse MIDROW command
+ var styles = {
+ flash: false
+ };
+ styles.underline = secondByte % 2 === 1;
+ styles.italics = secondByte >= 0x2e;
+
+ if (!styles.italics) {
+ var colorIndex = Math.floor(secondByte / 2) - 0x10;
+ var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
+ styles.foreground = colors[colorIndex];
+ } else {
+ styles.foreground = 'white';
+ }
+
+ this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
+ this.writeScreen.setPen(styles);
+ };
+
+ _proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
+ if (dispatch === void 0) {
+ dispatch = false;
+ }
+
+ var time = this.logger.time;
+
+ if (time === null) {
+ return;
+ }
+
+ if (this.outputFilter) {
+ if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
+ // Start of a new cue
+ this.cueStartTime = time;
+ } else {
+ if (!this.displayedMemory.equals(this.lastOutputScreen)) {
+ this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
+
+ if (dispatch && this.outputFilter.dispatchCue) {
+ this.outputFilter.dispatchCue();
+ }
+
+ this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
+ }
+ }
+
+ this.lastOutputScreen.copy(this.displayedMemory);
+ }
+ };
+
+ _proto6.cueSplitAtTime = function cueSplitAtTime(t) {
+ if (this.outputFilter) {
+ if (!this.displayedMemory.isEmpty()) {
+ if (this.outputFilter.newCue) {
+ this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
+ }
+
+ this.cueStartTime = t;
+ }
+ }
+ };
+
+ return Cea608Channel;
+}();
+
+var Cea608Parser = /*#__PURE__*/function () {
+ function Cea608Parser(field, out1, out2) {
+ this.channels = void 0;
+ this.currentChannel = 0;
+ this.cmdHistory = void 0;
+ this.logger = void 0;
+ var logger = new cea_608_parser_CaptionsLogger();
+ this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
+ this.cmdHistory = createCmdHistory();
+ this.logger = logger;
+ }
+
+ var _proto7 = Cea608Parser.prototype;
+
+ _proto7.getHandler = function getHandler(channel) {
+ return this.channels[channel].getHandler();
+ };
+
+ _proto7.setHandler = function setHandler(channel, newHandler) {
+ this.channels[channel].setHandler(newHandler);
+ }
+ /**
+ * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
+ */
+ ;
+
+ _proto7.addData = function addData(time, byteList) {
+ var cmdFound;
+ var a;
+ var b;
+ var charsFound = false;
+ this.logger.time = time;
+
+ for (var i = 0; i < byteList.length; i += 2) {
+ a = byteList[i] & 0x7f;
+ b = byteList[i + 1] & 0x7f;
+
+ if (a === 0 && b === 0) {
+ continue;
+ } else {
+ this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
+ }
+
+ cmdFound = this.parseCmd(a, b);
+
+ if (!cmdFound) {
+ cmdFound = this.parseMidrow(a, b);
+ }
+
+ if (!cmdFound) {
+ cmdFound = this.parsePAC(a, b);
+ }
+
+ if (!cmdFound) {
+ cmdFound = this.parseBackgroundAttributes(a, b);
+ }
+
+ if (!cmdFound) {
+ charsFound = this.parseChars(a, b);
+
+ if (charsFound) {
+ var currChNr = this.currentChannel;
+
+ if (currChNr && currChNr > 0) {
+ var channel = this.channels[currChNr];
+ channel.insertChars(charsFound);
+ } else {
+ this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
+ }
+ }
+ }
+
+ if (!cmdFound && !charsFound) {
+ this.logger.log(VerboseLevel.WARNING, 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
+ }
+ }
+ }
+ /**
+ * Parse Command.
+ * @returns {Boolean} Tells if a command was found
+ */
+ ;
+
+ _proto7.parseCmd = function parseCmd(a, b) {
+ var cmdHistory = this.cmdHistory;
+ var cond1 = (a === 0x14 || a === 0x1C || a === 0x15 || a === 0x1D) && b >= 0x20 && b <= 0x2F;
+ var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && b <= 0x23;
+
+ if (!(cond1 || cond2)) {
+ return false;
+ }
+
+ if (hasCmdRepeated(a, b, cmdHistory)) {
+ setLastCmd(null, null, cmdHistory);
+ this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
+ return true;
+ }
+
+ var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
+ var channel = this.channels[chNr];
+
+ if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) {
+ if (b === 0x20) {
+ channel.ccRCL();
+ } else if (b === 0x21) {
+ channel.ccBS();
+ } else if (b === 0x22) {
+ channel.ccAOF();
+ } else if (b === 0x23) {
+ channel.ccAON();
+ } else if (b === 0x24) {
+ channel.ccDER();
+ } else if (b === 0x25) {
+ channel.ccRU(2);
+ } else if (b === 0x26) {
+ channel.ccRU(3);
+ } else if (b === 0x27) {
+ channel.ccRU(4);
+ } else if (b === 0x28) {
+ channel.ccFON();
+ } else if (b === 0x29) {
+ channel.ccRDC();
+ } else if (b === 0x2A) {
+ channel.ccTR();
+ } else if (b === 0x2B) {
+ channel.ccRTD();
+ } else if (b === 0x2C) {
+ channel.ccEDM();
+ } else if (b === 0x2D) {
+ channel.ccCR();
+ } else if (b === 0x2E) {
+ channel.ccENM();
+ } else if (b === 0x2F) {
+ channel.ccEOC();
+ }
+ } else {
+ // a == 0x17 || a == 0x1F
+ channel.ccTO(b - 0x20);
+ }
+
+ setLastCmd(a, b, cmdHistory);
+ this.currentChannel = chNr;
+ return true;
+ }
+ /**
+ * Parse midrow styling command
+ * @returns {Boolean}
+ */
+ ;
+
+ _proto7.parseMidrow = function parseMidrow(a, b) {
+ var chNr = 0;
+
+ if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
+ if (a === 0x11) {
+ chNr = 1;
+ } else {
+ chNr = 2;
+ }
+
+ if (chNr !== this.currentChannel) {
+ this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
+ return false;
+ }
+
+ var channel = this.channels[chNr];
+
+ if (!channel) {
+ return false;
+ }
+
+ channel.ccMIDROW(b);
+ this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Parse Preable Access Codes (Table 53).
+ * @returns {Boolean} Tells if PAC found
+ */
+ ;
+
+ _proto7.parsePAC = function parsePAC(a, b) {
+ var row;
+ var cmdHistory = this.cmdHistory;
+ var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;
+ var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5F;
+
+ if (!(case1 || case2)) {
+ return false;
+ }
+
+ if (hasCmdRepeated(a, b, cmdHistory)) {
+ setLastCmd(null, null, cmdHistory);
+ return true; // Repeated commands are dropped (once)
+ }
+
+ var chNr = a <= 0x17 ? 1 : 2;
+
+ if (b >= 0x40 && b <= 0x5F) {
+ row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
+ } else {
+ // 0x60 <= b <= 0x7F
+ row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
+ }
+
+ var channel = this.channels[chNr];
+
+ if (!channel) {
+ return false;
+ }
+
+ channel.setPAC(this.interpretPAC(row, b));
+ setLastCmd(a, b, cmdHistory);
+ this.currentChannel = chNr;
+ return true;
+ }
+ /**
+ * Interpret the second byte of the pac, and return the information.
+ * @returns {Object} pacData with style parameters.
+ */
+ ;
+
+ _proto7.interpretPAC = function interpretPAC(row, _byte3) {
+ var pacIndex = _byte3;
+ var pacData = {
+ color: null,
+ italics: false,
+ indent: null,
+ underline: false,
+ row: row
+ };
+
+ if (_byte3 > 0x5F) {
+ pacIndex = _byte3 - 0x60;
+ } else {
+ pacIndex = _byte3 - 0x40;
+ }
+
+ pacData.underline = (pacIndex & 1) === 1;
+
+ if (pacIndex <= 0xd) {
+ pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
+ } else if (pacIndex <= 0xf) {
+ pacData.italics = true;
+ pacData.color = 'white';
+ } else {
+ pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
+ }
+
+ return pacData; // Note that row has zero offset. The spec uses 1.
+ }
+ /**
+ * Parse characters.
+ * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
+ */
+ ;
+
+ _proto7.parseChars = function parseChars(a, b) {
+ var channelNr;
+ var charCodes = null;
+ var charCode1 = null;
+
+ if (a >= 0x19) {
+ channelNr = 2;
+ charCode1 = a - 8;
+ } else {
+ channelNr = 1;
+ charCode1 = a;
+ }
+
+ if (charCode1 >= 0x11 && charCode1 <= 0x13) {
+ // Special character
+ var oneCode = b;
+
+ if (charCode1 === 0x11) {
+ oneCode = b + 0x50;
+ } else if (charCode1 === 0x12) {
+ oneCode = b + 0x70;
+ } else {
+ oneCode = b + 0x90;
+ }
+
+ this.logger.log(VerboseLevel.INFO, 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
+ charCodes = [oneCode];
+ } else if (a >= 0x20 && a <= 0x7f) {
+ charCodes = b === 0 ? [a] : [a, b];
+ }
+
+ if (charCodes) {
+ var hexCodes = numArrayToHexArray(charCodes);
+ this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));
+ setLastCmd(a, b, this.cmdHistory);
+ }
+
+ return charCodes;
+ }
+ /**
+ * Parse extended background attributes as well as new foreground color black.
+ * @returns {Boolean} Tells if background attributes are found
+ */
+ ;
+
+ _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
+ var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
+ var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
+
+ if (!(case1 || case2)) {
+ return false;
+ }
+
+ var index;
+ var bkgData = {};
+
+ if (a === 0x10 || a === 0x18) {
+ index = Math.floor((b - 0x20) / 2);
+ bkgData.background = backgroundColors[index];
+
+ if (b % 2 === 1) {
+ bkgData.background = bkgData.background + '_semi';
+ }
+ } else if (b === 0x2d) {
+ bkgData.background = 'transparent';
+ } else {
+ bkgData.foreground = 'black';
+
+ if (b === 0x2f) {
+ bkgData.underline = true;
+ }
+ }
+
+ var chNr = a <= 0x17 ? 1 : 2;
+ var channel = this.channels[chNr];
+ channel.setBkgData(bkgData);
+ setLastCmd(a, b, this.cmdHistory);
+ return true;
+ }
+ /**
+ * Reset state of parser and its channels.
+ */
+ ;
+
+ _proto7.reset = function reset() {
+ for (var i = 0; i < Object.keys(this.channels).length; i++) {
+ var channel = this.channels[i];
+
+ if (channel) {
+ channel.reset();
+ }
+ }
+
+ this.cmdHistory = createCmdHistory();
+ }
+ /**
+ * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
+ */
+ ;
+
+ _proto7.cueSplitAtTime = function cueSplitAtTime(t) {
+ for (var i = 0; i < this.channels.length; i++) {
+ var channel = this.channels[i];
+
+ if (channel) {
+ channel.cueSplitAtTime(t);
+ }
+ }
+ };
+
+ return Cea608Parser;
+}();
+
+function setLastCmd(a, b, cmdHistory) {
+ cmdHistory.a = a;
+ cmdHistory.b = b;
+}
+
+function hasCmdRepeated(a, b, cmdHistory) {
+ return cmdHistory.a === a && cmdHistory.b === b;
+}
+
+function createCmdHistory() {
+ return {
+ a: null,
+ b: null
+ };
+}
+
+/* harmony default export */ var cea_608_parser = (Cea608Parser);
+// CONCATENATED MODULE: ./src/utils/output-filter.ts
+var OutputFilter = /*#__PURE__*/function () {
+ function OutputFilter(timelineController, trackName) {
+ this.timelineController = void 0;
+ this.cueRanges = [];
+ this.trackName = void 0;
+ this.startTime = null;
+ this.endTime = null;
+ this.screen = null;
+ this.timelineController = timelineController;
+ this.trackName = trackName;
+ }
+
+ var _proto = OutputFilter.prototype;
+
+ _proto.dispatchCue = function dispatchCue() {
+ if (this.startTime === null) {
+ return;
+ }
+
+ this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
+ this.startTime = null;
+ };
+
+ _proto.newCue = function newCue(startTime, endTime, screen) {
+ if (this.startTime === null || this.startTime > startTime) {
+ this.startTime = startTime;
+ }
+
+ this.endTime = endTime;
+ this.screen = screen;
+ this.timelineController.createCaptionsTrack(this.trackName);
+ };
+
+ _proto.reset = function reset() {
+ this.cueRanges = [];
+ };
+
+ return OutputFilter;
+}();
+
+
+// CONCATENATED MODULE: ./src/utils/webvtt-parser.js
+
+
+
+
+
+ // String.prototype.startsWith is not supported in IE11
+
+var startsWith = function startsWith(inputString, searchString, position) {
+ return inputString.substr(position || 0, searchString.length) === searchString;
+};
+
+var webvtt_parser_cueString2millis = function cueString2millis(timeString) {
+ var ts = parseInt(timeString.substr(-3));
+ var secs = parseInt(timeString.substr(-6, 2));
+ var mins = parseInt(timeString.substr(-9, 2));
+ var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
+
+ if (!Object(number["isFiniteNumber"])(ts) || !Object(number["isFiniteNumber"])(secs) || !Object(number["isFiniteNumber"])(mins) || !Object(number["isFiniteNumber"])(hours)) {
+ throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
+ }
+
+ ts += 1000 * secs;
+ ts += 60 * 1000 * mins;
+ ts += 60 * 60 * 1000 * hours;
+ return ts;
+}; // From https://github.com/darkskyapp/string-hash
+
+
+var hash = function hash(text) {
+ var hash = 5381;
+ var i = text.length;
+
+ while (i) {
+ hash = hash * 33 ^ text.charCodeAt(--i);
+ }
+
+ return (hash >>> 0).toString();
+};
+
+var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
+ var currCC = vttCCs[cc];
+ var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
+ // Offset = current discontinuity time
+
+ if (!prevCC || !prevCC.new && currCC.new) {
+ vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
+ currCC.new = false;
+ return;
+ } // There have been discontinuities since cues were last parsed.
+ // Offset = time elapsed
+
+
+ while (prevCC && prevCC.new) {
+ vttCCs.ccOffset += currCC.start - prevCC.start;
+ currCC.new = false;
+ currCC = prevCC;
+ prevCC = vttCCs[currCC.prevCC];
+ }
+
+ vttCCs.presentationOffset = presentationTime;
+};
+
+var WebVTTParser = {
+ parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
+ // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
+ var re = /\r\n|\n\r|\n|\r/g; // Uint8Array.prototype.reduce is not implemented in IE11
+
+ var vttLines = Object(id3["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
+ var cueTime = '00:00.000';
+ var mpegTs = 0;
+ var localTime = 0;
+ var presentationTime = 0;
+ var cues = [];
+ var parsingError;
+ var inHeader = true;
+ var timestampMap = false; // let VTTCue = VTTCue || window.TextTrackCue;
+ // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
+
+ var parser = new vttparser();
+
+ parser.oncue = function (cue) {
+ // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
+ var currCC = vttCCs[cc];
+ var cueOffset = vttCCs.ccOffset; // Update offsets for new discontinuities
+
+ if (currCC && currCC.new) {
+ if (localTime !== undefined) {
+ // When local time is provided, offset = discontinuity start time - local time
+ cueOffset = vttCCs.ccOffset = currCC.start;
+ } else {
+ calculateOffset(vttCCs, cc, presentationTime);
+ }
+ }
+
+ if (presentationTime) {
+ // If we have MPEGTS, offset = presentation time + discontinuity offset
+ cueOffset = presentationTime - vttCCs.presentationOffset;
+ }
+
+ if (timestampMap) {
+ cue.startTime += cueOffset - localTime;
+ cue.endTime += cueOffset - localTime;
+ } // Create a unique hash id for a cue based on start/end times and text.
+ // This helps timeline-controller to avoid showing repeated captions.
+
+
+ cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text); // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
+
+ cue.text = decodeURIComponent(encodeURIComponent(cue.text));
+
+ if (cue.endTime > 0) {
+ cues.push(cue);
+ }
+ };
+
+ parser.onparsingerror = function (e) {
+ parsingError = e;
+ };
+
+ parser.onflush = function () {
+ if (parsingError && errorCallBack) {
+ errorCallBack(parsingError);
+ return;
+ }
+
+ callBack(cues);
+ }; // Go through contents line by line.
+
+
+ vttLines.forEach(function (line) {
+ if (inHeader) {
+ // Look for X-TIMESTAMP-MAP in header.
+ if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
+ // Once found, no more are allowed anyway, so stop searching.
+ inHeader = false;
+ timestampMap = true; // Extract LOCAL and MPEGTS.
+
+ line.substr(16).split(',').forEach(function (timestamp) {
+ if (startsWith(timestamp, 'LOCAL:')) {
+ cueTime = timestamp.substr(6);
+ } else if (startsWith(timestamp, 'MPEGTS:')) {
+ mpegTs = parseInt(timestamp.substr(7));
+ }
+ });
+
+ try {
+ // Calculate subtitle offset in milliseconds.
+ if (syncPTS + (vttCCs[cc].start * 90000 || 0) < 0) {
+ syncPTS += 8589934592;
+ } // Adjust MPEGTS by sync PTS.
+
+
+ mpegTs -= syncPTS; // Convert cue time to seconds
+
+ localTime = webvtt_parser_cueString2millis(cueTime) / 1000; // Convert MPEGTS to seconds from 90kHz.
+
+ presentationTime = mpegTs / 90000;
+ } catch (e) {
+ timestampMap = false;
+ parsingError = e;
+ } // Return without parsing X-TIMESTAMP-MAP line.
+
+
+ return;
+ } else if (line === '') {
+ inHeader = false;
+ }
+ } // Parse line by default.
+
+
+ parser.parse(line + '\n');
+ });
+ parser.flush();
+ }
+};
+/* harmony default export */ var webvtt_parser = (WebVTTParser);
+// CONCATENATED MODULE: ./src/controller/timeline-controller.ts
+
+
+
+function timeline_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function timeline_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+
+
+
+
+
+
+var timeline_controller_TimelineController = /*#__PURE__*/function (_EventHandler) {
+ timeline_controller_inheritsLoose(TimelineController, _EventHandler);
+
+ function TimelineController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING, events["default"].MEDIA_DETACHING, events["default"].FRAG_PARSING_USERDATA, events["default"].FRAG_DECRYPTED, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_LOADED, events["default"].FRAG_LOADED, events["default"].INIT_PTS_FOUND) || this;
+ _this.media = null;
+ _this.config = void 0;
+ _this.enabled = true;
+ _this.Cues = void 0;
+ _this.textTracks = [];
+ _this.tracks = [];
+ _this.initPTS = [];
+ _this.unparsedVttFrags = [];
+ _this.captionsTracks = {};
+ _this.nonNativeCaptionsTracks = {};
+ _this.captionsProperties = void 0;
+ _this.cea608Parser1 = void 0;
+ _this.cea608Parser2 = void 0;
+ _this.lastSn = -1;
+ _this.prevCC = -1;
+ _this.vttCCs = newVTTCCs();
+ _this.hls = hls;
+ _this.config = hls.config;
+ _this.Cues = hls.config.cueHandler;
+ _this.captionsProperties = {
+ textTrack1: {
+ label: _this.config.captionsTextTrack1Label,
+ languageCode: _this.config.captionsTextTrack1LanguageCode
+ },
+ textTrack2: {
+ label: _this.config.captionsTextTrack2Label,
+ languageCode: _this.config.captionsTextTrack2LanguageCode
+ },
+ textTrack3: {
+ label: _this.config.captionsTextTrack3Label,
+ languageCode: _this.config.captionsTextTrack3LanguageCode
+ },
+ textTrack4: {
+ label: _this.config.captionsTextTrack4Label,
+ languageCode: _this.config.captionsTextTrack4LanguageCode
+ }
+ };
+
+ if (_this.config.enableCEA708Captions) {
+ var channel1 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack1');
+ var channel2 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack2');
+ var channel3 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack3');
+ var channel4 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack4');
+ _this.cea608Parser1 = new cea_608_parser(1, channel1, channel2);
+ _this.cea608Parser2 = new cea_608_parser(3, channel3, channel4);
+ }
+
+ return _this;
+ }
+
+ var _proto = TimelineController.prototype;
+
+ _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
+ // skip cues which overlap more than 50% with previously parsed time ranges
+ var merged = false;
+
+ for (var i = cueRanges.length; i--;) {
+ var cueRange = cueRanges[i];
+ var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
+
+ if (overlap >= 0) {
+ cueRange[0] = Math.min(cueRange[0], startTime);
+ cueRange[1] = Math.max(cueRange[1], endTime);
+ merged = true;
+
+ if (overlap / (endTime - startTime) > 0.5) {
+ return;
+ }
+ }
+ }
+
+ if (!merged) {
+ cueRanges.push([startTime, endTime]);
+ }
+
+ if (this.config.renderTextTracksNatively) {
+ this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
+ } else {
+ var cues = this.Cues.newCue(null, startTime, endTime, screen);
+ this.hls.trigger(events["default"].CUES_PARSED, {
+ type: 'captions',
+ cues: cues,
+ track: trackName
+ });
+ }
+ } // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
+ ;
+
+ _proto.onInitPtsFound = function onInitPtsFound(data) {
+ var _this2 = this;
+
+ var frag = data.frag,
+ id = data.id,
+ initPTS = data.initPTS;
+ var unparsedVttFrags = this.unparsedVttFrags;
+
+ if (id === 'main') {
+ this.initPTS[frag.cc] = initPTS;
+ } // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
+ // Parse any unparsed fragments upon receiving the initial PTS.
+
+
+ if (unparsedVttFrags.length) {
+ this.unparsedVttFrags = [];
+ unparsedVttFrags.forEach(function (frag) {
+ _this2.onFragLoaded(frag);
+ });
+ }
+ };
+
+ _proto.getExistingTrack = function getExistingTrack(trackName) {
+ var media = this.media;
+
+ if (media) {
+ for (var i = 0; i < media.textTracks.length; i++) {
+ var textTrack = media.textTracks[i];
+
+ if (textTrack[trackName]) {
+ return textTrack;
+ }
+ }
+ }
+
+ return null;
+ };
+
+ _proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
+ if (this.config.renderTextTracksNatively) {
+ this.createNativeTrack(trackName);
+ } else {
+ this.createNonNativeTrack(trackName);
+ }
+ };
+
+ _proto.createNativeTrack = function createNativeTrack(trackName) {
+ if (this.captionsTracks[trackName]) {
+ return;
+ }
+
+ var captionsProperties = this.captionsProperties,
+ captionsTracks = this.captionsTracks,
+ media = this.media;
+ var _captionsProperties$t = captionsProperties[trackName],
+ label = _captionsProperties$t.label,
+ languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
+
+ var existingTrack = this.getExistingTrack(trackName);
+
+ if (!existingTrack) {
+ var textTrack = this.createTextTrack('captions', label, languageCode);
+
+ if (textTrack) {
+ // Set a special property on the track so we know it's managed by Hls.js
+ textTrack[trackName] = true;
+ captionsTracks[trackName] = textTrack;
+ }
+ } else {
+ captionsTracks[trackName] = existingTrack;
+ clearCurrentCues(captionsTracks[trackName]);
+ sendAddTrackEvent(captionsTracks[trackName], media);
+ }
+ };
+
+ _proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
+ if (this.nonNativeCaptionsTracks[trackName]) {
+ return;
+ } // Create a list of a single track for the provider to consume
+
+
+ var trackProperties = this.captionsProperties[trackName];
+
+ if (!trackProperties) {
+ return;
+ }
+
+ var label = trackProperties.label;
+ var track = {
+ _id: trackName,
+ label: label,
+ kind: 'captions',
+ default: trackProperties.media ? !!trackProperties.media.default : false,
+ closedCaptions: trackProperties.media
+ };
+ this.nonNativeCaptionsTracks[trackName] = track;
+ this.hls.trigger(events["default"].NON_NATIVE_TEXT_TRACKS_FOUND, {
+ tracks: [track]
+ });
+ };
+
+ _proto.createTextTrack = function createTextTrack(kind, label, lang) {
+ var media = this.media;
+
+ if (!media) {
+ return;
+ }
+
+ return media.addTextTrack(kind, label, lang);
+ };
+
+ _proto.destroy = function destroy() {
+ _EventHandler.prototype.destroy.call(this);
+ };
+
+ _proto.onMediaAttaching = function onMediaAttaching(data) {
+ this.media = data.media;
+
+ this._cleanTracks();
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ var captionsTracks = this.captionsTracks;
+ Object.keys(captionsTracks).forEach(function (trackName) {
+ clearCurrentCues(captionsTracks[trackName]);
+ delete captionsTracks[trackName];
+ });
+ this.nonNativeCaptionsTracks = {};
+ };
+
+ _proto.onManifestLoading = function onManifestLoading() {
+ this.lastSn = -1; // Detect discontiguity in fragment parsing
+
+ this.prevCC = -1;
+ this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
+
+ this._cleanTracks();
+
+ this.tracks = [];
+ this.captionsTracks = {};
+ this.nonNativeCaptionsTracks = {};
+ };
+
+ _proto._cleanTracks = function _cleanTracks() {
+ // clear outdated subtitles
+ var media = this.media;
+
+ if (!media) {
+ return;
+ }
+
+ var textTracks = media.textTracks;
+
+ if (textTracks) {
+ for (var i = 0; i < textTracks.length; i++) {
+ clearCurrentCues(textTracks[i]);
+ }
+ }
+ };
+
+ _proto.onManifestLoaded = function onManifestLoaded(data) {
+ var _this3 = this;
+
+ this.textTracks = [];
+ this.unparsedVttFrags = this.unparsedVttFrags || [];
+ this.initPTS = [];
+
+ if (this.cea608Parser1 && this.cea608Parser2) {
+ this.cea608Parser1.reset();
+ this.cea608Parser2.reset();
+ }
+
+ if (this.config.enableWebVTT) {
+ var tracks = data.subtitles || [];
+ var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
+ this.tracks = data.subtitles || [];
+
+ if (this.config.renderTextTracksNatively) {
+ var inUseTracks = this.media ? this.media.textTracks : [];
+ this.tracks.forEach(function (track, index) {
+ var textTrack;
+
+ if (index < inUseTracks.length) {
+ var inUseTrack = null;
+
+ for (var i = 0; i < inUseTracks.length; i++) {
+ if (canReuseVttTextTrack(inUseTracks[i], track)) {
+ inUseTrack = inUseTracks[i];
+ break;
+ }
+ } // Reuse tracks with the same label, but do not reuse 608/708 tracks
+
+
+ if (inUseTrack) {
+ textTrack = inUseTrack;
+ }
+ }
+
+ if (!textTrack) {
+ textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
+ }
+
+ if (track.default) {
+ textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';
+ } else {
+ textTrack.mode = 'disabled';
+ }
+
+ _this3.textTracks.push(textTrack);
+ });
+ } else if (!sameTracks && this.tracks && this.tracks.length) {
+ // Create a list of tracks for the provider to consume
+ var tracksList = this.tracks.map(function (track) {
+ return {
+ label: track.name,
+ kind: track.type.toLowerCase(),
+ default: track.default,
+ subtitleTrack: track
+ };
+ });
+ this.hls.trigger(events["default"].NON_NATIVE_TEXT_TRACKS_FOUND, {
+ tracks: tracksList
+ });
+ }
+ }
+
+ if (this.config.enableCEA708Captions && data.captions) {
+ data.captions.forEach(function (captionsTrack) {
+ var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
+
+ if (!instreamIdMatch) {
+ return;
+ }
+
+ var trackName = "textTrack" + instreamIdMatch[1];
+ var trackProperties = _this3.captionsProperties[trackName];
+
+ if (!trackProperties) {
+ return;
+ }
+
+ trackProperties.label = captionsTrack.name;
+
+ if (captionsTrack.lang) {
+ // optional attribute
+ trackProperties.languageCode = captionsTrack.lang;
+ }
+
+ trackProperties.media = captionsTrack;
+ });
+ }
+ };
+
+ _proto.onFragLoaded = function onFragLoaded(data) {
+ var frag = data.frag,
+ payload = data.payload;
+ var cea608Parser1 = this.cea608Parser1,
+ cea608Parser2 = this.cea608Parser2,
+ initPTS = this.initPTS,
+ lastSn = this.lastSn,
+ unparsedVttFrags = this.unparsedVttFrags;
+
+ if (frag.type === 'main') {
+ var sn = frag.sn; // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
+
+ if (frag.sn !== lastSn + 1) {
+ if (cea608Parser1 && cea608Parser2) {
+ cea608Parser1.reset();
+ cea608Parser2.reset();
+ }
+ }
+
+ this.lastSn = sn;
+ } // eslint-disable-line brace-style
+ // If fragment is subtitle type, parse as WebVTT.
+ else if (frag.type === 'subtitle') {
+ if (payload.byteLength) {
+ // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
+ if (!Object(number["isFiniteNumber"])(initPTS[frag.cc])) {
+ unparsedVttFrags.push(data);
+
+ if (initPTS.length) {
+ // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
+ this.hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
+ success: false,
+ frag: frag
+ });
+ }
+
+ return;
+ }
+
+ var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
+
+ if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
+ this._parseVTTs(frag, payload);
+ }
+ } else {
+ // In case there is no payload, finish unsuccessfully.
+ this.hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
+ success: false,
+ frag: frag
+ });
+ }
+ }
+ };
+
+ _proto._parseVTTs = function _parseVTTs(frag, payload) {
+ var _this4 = this;
+
+ var hls = this.hls,
+ prevCC = this.prevCC,
+ textTracks = this.textTracks,
+ vttCCs = this.vttCCs;
+
+ if (!vttCCs[frag.cc]) {
+ vttCCs[frag.cc] = {
+ start: frag.start,
+ prevCC: prevCC,
+ new: true
+ };
+ this.prevCC = frag.cc;
+ } // Parse the WebVTT file contents.
+
+
+ webvtt_parser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
+ if (_this4.config.renderTextTracksNatively) {
+ var currentTrack = textTracks[frag.level]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
+ // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
+ // and trying to access getCueById method of cues will throw an exception
+ // Because we check if the mode is diabled, we can force check `cues` below. They can't be null.
+
+ if (currentTrack.mode === 'disabled') {
+ hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
+ success: false,
+ frag: frag
+ });
+ return;
+ } // Add cues and trigger event with success true.
+
+
+ cues.forEach(function (cue) {
+ // Sometimes there are cue overlaps on segmented vtts so the same
+ // cue can appear more than once in different vtt files.
+ // This avoid showing duplicated cues with same timecode and text.
+ if (!currentTrack.cues.getCueById(cue.id)) {
+ try {
+ currentTrack.addCue(cue);
+
+ if (!currentTrack.cues.getCueById(cue.id)) {
+ throw new Error("addCue is failed for: " + cue);
+ }
+ } catch (err) {
+ logger["logger"].debug("Failed occurred on adding cues: " + err);
+ var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
+ textTrackCue.id = cue.id;
+ currentTrack.addCue(textTrackCue);
+ }
+ }
+ });
+ } else {
+ var trackId = _this4.tracks[frag.level].default ? 'default' : 'subtitles' + frag.level;
+ hls.trigger(events["default"].CUES_PARSED, {
+ type: 'subtitles',
+ cues: cues,
+ track: trackId
+ });
+ }
+
+ hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
+ success: true,
+ frag: frag
+ });
+ }, function (e) {
+ // Something went wrong while parsing. Trigger event with success false.
+ logger["logger"].log("Failed to parse VTT cue: " + e);
+ hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
+ success: false,
+ frag: frag
+ });
+ });
+ };
+
+ _proto.onFragDecrypted = function onFragDecrypted(data) {
+ var frag = data.frag,
+ payload = data.payload;
+
+ if (frag.type === 'subtitle') {
+ if (!Object(number["isFiniteNumber"])(this.initPTS[frag.cc])) {
+ this.unparsedVttFrags.push(data);
+ return;
+ }
+
+ this._parseVTTs(frag, payload);
+ }
+ };
+
+ _proto.onFragParsingUserdata = function onFragParsingUserdata(data) {
+ var cea608Parser1 = this.cea608Parser1,
+ cea608Parser2 = this.cea608Parser2;
+
+ if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
+ return;
+ } // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
+ // It will create the proper timestamps based on the PTS value
+
+
+ for (var i = 0; i < data.samples.length; i++) {
+ var ccBytes = data.samples[i].bytes;
+
+ if (ccBytes) {
+ var ccdatas = this.extractCea608Data(ccBytes);
+ cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
+ cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
+ }
+ }
+ };
+
+ _proto.extractCea608Data = function extractCea608Data(byteArray) {
+ var count = byteArray[0] & 31;
+ var position = 2;
+ var actualCCBytes = [[], []];
+
+ for (var j = 0; j < count; j++) {
+ var tmpByte = byteArray[position++];
+ var ccbyte1 = 0x7F & byteArray[position++];
+ var ccbyte2 = 0x7F & byteArray[position++];
+ var ccValid = (4 & tmpByte) !== 0;
+ var ccType = 3 & tmpByte;
+
+ if (ccbyte1 === 0 && ccbyte2 === 0) {
+ continue;
+ }
+
+ if (ccValid) {
+ if (ccType === 0 || ccType === 1) {
+ actualCCBytes[ccType].push(ccbyte1);
+ actualCCBytes[ccType].push(ccbyte2);
+ }
+ }
+ }
+
+ return actualCCBytes;
+ };
+
+ return TimelineController;
+}(event_handler);
+
+function canReuseVttTextTrack(inUseTrack, manifestTrack) {
+ return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
+}
+
+function intersection(x1, x2, y1, y2) {
+ return Math.min(x2, y2) - Math.max(x1, y1);
+}
+
+function newVTTCCs() {
+ return {
+ ccOffset: 0,
+ presentationOffset: 0,
+ 0: {
+ start: 0,
+ prevCC: -1,
+ new: false
+ }
+ };
+}
+
+/* harmony default export */ var timeline_controller = (timeline_controller_TimelineController);
+// CONCATENATED MODULE: ./src/controller/subtitle-track-controller.js
+
+
+
+
+function subtitle_track_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function subtitle_track_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) subtitle_track_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) subtitle_track_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function subtitle_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+
+
+
+
+var subtitle_track_controller_SubtitleTrackController = /*#__PURE__*/function (_EventHandler) {
+ subtitle_track_controller_inheritsLoose(SubtitleTrackController, _EventHandler);
+
+ function SubtitleTrackController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_LOADED, events["default"].SUBTITLE_TRACK_LOADED) || this;
+ _this.tracks = [];
+ _this.trackId = -1;
+ _this.media = null;
+ _this.stopped = true;
+ /**
+ * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
+ */
+
+ _this.subtitleDisplay = true;
+ /**
+ * Keeps reference to a default track id when media has not been attached yet
+ * @member {number}
+ */
+
+ _this.queuedDefaultTrack = null;
+ return _this;
+ }
+
+ var _proto = SubtitleTrackController.prototype;
+
+ _proto.destroy = function destroy() {
+ event_handler.prototype.destroy.call(this);
+ } // Listen for subtitle track change, then extract the current track ID.
+ ;
+
+ _proto.onMediaAttached = function onMediaAttached(data) {
+ var _this2 = this;
+
+ this.media = data.media;
+
+ if (!this.media) {
+ return;
+ }
+
+ if (Object(number["isFiniteNumber"])(this.queuedDefaultTrack)) {
+ this.subtitleTrack = this.queuedDefaultTrack;
+ this.queuedDefaultTrack = null;
+ }
+
+ this.trackChangeListener = this._onTextTracksChanged.bind(this);
+ this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
+
+ if (this.useTextTrackPolling) {
+ this.subtitlePollingInterval = setInterval(function () {
+ _this2.trackChangeListener();
+ }, 500);
+ } else {
+ this.media.textTracks.addEventListener('change', this.trackChangeListener);
+ }
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ if (!this.media) {
+ return;
+ }
+
+ if (this.useTextTrackPolling) {
+ clearInterval(this.subtitlePollingInterval);
+ } else {
+ this.media.textTracks.removeEventListener('change', this.trackChangeListener);
+ }
+
+ if (Object(number["isFiniteNumber"])(this.subtitleTrack)) {
+ this.queuedDefaultTrack = this.subtitleTrack;
+ }
+
+ var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
+
+ textTracks.forEach(function (track) {
+ clearCurrentCues(track);
+ }); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
+
+ this.subtitleTrack = -1;
+ this.media = null;
+ } // Fired whenever a new manifest is loaded.
+ ;
+
+ _proto.onManifestLoaded = function onManifestLoaded(data) {
+ var _this3 = this;
+
+ var tracks = data.subtitles || [];
+ this.tracks = tracks;
+ this.hls.trigger(events["default"].SUBTITLE_TRACKS_UPDATED, {
+ subtitleTracks: tracks
+ }); // loop through available subtitle tracks and autoselect default if needed
+ // TODO: improve selection logic to handle forced, etc
+
+ tracks.forEach(function (track) {
+ if (track.default) {
+ // setting this.subtitleTrack will trigger internal logic
+ // if media has not been attached yet, it will fail
+ // we keep a reference to the default track id
+ // and we'll set subtitleTrack when onMediaAttached is triggered
+ if (_this3.media) {
+ _this3.subtitleTrack = track.id;
+ } else {
+ _this3.queuedDefaultTrack = track.id;
+ }
+ }
+ });
+ };
+
+ _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {
+ var _this4 = this;
+
+ var id = data.id,
+ details = data.details;
+ var trackId = this.trackId,
+ tracks = this.tracks;
+ var currentTrack = tracks[trackId];
+
+ if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
+ this._clearReloadTimer();
+
+ return;
+ }
+
+ logger["logger"].log("subtitle track " + id + " loaded");
+
+ if (details.live) {
+ var reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);
+ logger["logger"].log("Reloading live subtitle playlist in " + reloadInterval + "ms");
+ this.timer = setTimeout(function () {
+ _this4._loadCurrentTrack();
+ }, reloadInterval);
+ } else {
+ this._clearReloadTimer();
+ }
+ };
+
+ _proto.startLoad = function startLoad() {
+ this.stopped = false;
+
+ this._loadCurrentTrack();
+ };
+
+ _proto.stopLoad = function stopLoad() {
+ this.stopped = true;
+
+ this._clearReloadTimer();
+ }
+ /** get alternate subtitle tracks list from playlist **/
+ ;
+
+ _proto._clearReloadTimer = function _clearReloadTimer() {
+ if (this.timer) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ };
+
+ _proto._loadCurrentTrack = function _loadCurrentTrack() {
+ var trackId = this.trackId,
+ tracks = this.tracks,
+ hls = this.hls;
+ var currentTrack = tracks[trackId];
+
+ if (trackId < 0 || !currentTrack || currentTrack.details && !currentTrack.details.live) {
+ return;
+ }
+
+ logger["logger"].log("Loading subtitle track " + trackId);
+ hls.trigger(events["default"].SUBTITLE_TRACK_LOADING, {
+ url: currentTrack.url,
+ id: trackId
+ });
+ }
+ /**
+ * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
+ * This operates on the DOM textTracks.
+ * A value of -1 will disable all subtitle tracks.
+ * @param newId - The id of the next track to enable
+ * @private
+ */
+ ;
+
+ _proto._toggleTrackModes = function _toggleTrackModes(newId) {
+ var media = this.media,
+ subtitleDisplay = this.subtitleDisplay,
+ trackId = this.trackId;
+
+ if (!media) {
+ return;
+ }
+
+ var textTracks = filterSubtitleTracks(media.textTracks);
+
+ if (newId === -1) {
+ [].slice.call(textTracks).forEach(function (track) {
+ track.mode = 'disabled';
+ });
+ } else {
+ var oldTrack = textTracks[trackId];
+
+ if (oldTrack) {
+ oldTrack.mode = 'disabled';
+ }
+ }
+
+ var nextTrack = textTracks[newId];
+
+ if (nextTrack) {
+ nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
+ }
+ }
+ /**
+ * This method is responsible for validating the subtitle index and periodically reloading if live.
+ * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
+ * @param newId - The id of the subtitle track to activate.
+ */
+ ;
+
+ _proto._setSubtitleTrackInternal = function _setSubtitleTrackInternal(newId) {
+ var hls = this.hls,
+ tracks = this.tracks;
+
+ if (!Object(number["isFiniteNumber"])(newId) || newId < -1 || newId >= tracks.length) {
+ return;
+ }
+
+ this.trackId = newId;
+ logger["logger"].log("Switching to subtitle track " + newId);
+ hls.trigger(events["default"].SUBTITLE_TRACK_SWITCH, {
+ id: newId
+ });
+
+ this._loadCurrentTrack();
+ };
+
+ _proto._onTextTracksChanged = function _onTextTracksChanged() {
+ // Media is undefined when switching streams via loadSource()
+ if (!this.media || !this.hls.config.renderTextTracksNatively) {
+ return;
+ }
+
+ var trackId = -1;
+ var tracks = filterSubtitleTracks(this.media.textTracks);
+
+ for (var id = 0; id < tracks.length; id++) {
+ if (tracks[id].mode === 'hidden') {
+ // Do not break in case there is a following track with showing.
+ trackId = id;
+ } else if (tracks[id].mode === 'showing') {
+ trackId = id;
+ break;
+ }
+ } // Setting current subtitleTrack will invoke code.
+
+
+ this.subtitleTrack = trackId;
+ };
+
+ subtitle_track_controller_createClass(SubtitleTrackController, [{
+ key: "subtitleTracks",
+ get: function get() {
+ return this.tracks;
+ }
+ /** get index of the selected subtitle track (index in subtitle track lists) **/
+
+ }, {
+ key: "subtitleTrack",
+ get: function get() {
+ return this.trackId;
+ }
+ /** select a subtitle track, based on its index in subtitle track lists**/
+ ,
+ set: function set(subtitleTrackId) {
+ if (this.trackId !== subtitleTrackId) {
+ this._toggleTrackModes(subtitleTrackId);
+
+ this._setSubtitleTrackInternal(subtitleTrackId);
+ }
+ }
+ }]);
+
+ return SubtitleTrackController;
+}(event_handler);
+
+function filterSubtitleTracks(textTrackList) {
+ var tracks = [];
+
+ for (var i = 0; i < textTrackList.length; i++) {
+ var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
+
+ if (track.kind === 'subtitles' && track.label) {
+ tracks.push(textTrackList[i]);
+ }
+ }
+
+ return tracks;
+}
+
+/* harmony default export */ var subtitle_track_controller = (subtitle_track_controller_SubtitleTrackController);
+// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
+var decrypter = __webpack_require__("./src/crypt/decrypter.js");
+
+// CONCATENATED MODULE: ./src/controller/subtitle-stream-controller.js
+function subtitle_stream_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function subtitle_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/**
+ * @class SubtitleStreamController
+ */
+
+
+
+
+
+
+
+
+var subtitle_stream_controller_window = window,
+ subtitle_stream_controller_performance = subtitle_stream_controller_window.performance;
+var subtitle_stream_controller_TICK_INTERVAL = 500; // how often to tick in ms
+
+var subtitle_stream_controller_SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
+ subtitle_stream_controller_inheritsLoose(SubtitleStreamController, _BaseStreamController);
+
+ function SubtitleStreamController(hls, fragmentTracker) {
+ var _this;
+
+ _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].ERROR, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].SUBTITLE_TRACKS_UPDATED, events["default"].SUBTITLE_TRACK_SWITCH, events["default"].SUBTITLE_TRACK_LOADED, events["default"].SUBTITLE_FRAG_PROCESSED, events["default"].LEVEL_UPDATED) || this;
+ _this.fragmentTracker = fragmentTracker;
+ _this.config = hls.config;
+ _this.state = State.STOPPED;
+ _this.tracks = [];
+ _this.tracksBuffered = [];
+ _this.currentTrackId = -1;
+ _this.decrypter = new decrypter["default"](hls, hls.config); // lastAVStart stores the time in seconds for the start time of a level load
+
+ _this.lastAVStart = 0;
+ _this._onMediaSeeking = _this.onMediaSeeking.bind(subtitle_stream_controller_assertThisInitialized(_this));
+ return _this;
+ }
+
+ var _proto = SubtitleStreamController.prototype;
+
+ _proto.startLoad = function startLoad() {
+ this.stopLoad();
+ this.state = State.IDLE; // Check if we already have a track with necessary details to load fragments
+
+ var currentTrack = this.tracks[this.currentTrackId];
+
+ if (currentTrack && currentTrack.details) {
+ this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
+ this.tick();
+ }
+ };
+
+ _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) {
+ var frag = data.frag,
+ success = data.success;
+ this.fragPrevious = frag;
+ this.state = State.IDLE;
+
+ if (!success) {
+ return;
+ }
+
+ var buffered = this.tracksBuffered[this.currentTrackId];
+
+ if (!buffered) {
+ return;
+ } // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
+ // so we can re-use the logic used to detect how much have been buffered
+
+
+ var timeRange;
+ var fragStart = frag.start;
+
+ for (var i = 0; i < buffered.length; i++) {
+ if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
+ timeRange = buffered[i];
+ break;
+ }
+ }
+
+ var fragEnd = frag.start + frag.duration;
+
+ if (timeRange) {
+ timeRange.end = fragEnd;
+ } else {
+ timeRange = {
+ start: fragStart,
+ end: fragEnd
+ };
+ buffered.push(timeRange);
+ }
+ };
+
+ _proto.onMediaAttached = function onMediaAttached(_ref) {
+ var media = _ref.media;
+ this.media = media;
+ media.addEventListener('seeking', this._onMediaSeeking);
+ this.state = State.IDLE;
+ };
+
+ _proto.onMediaDetaching = function onMediaDetaching() {
+ var _this2 = this;
+
+ if (!this.media) {
+ return;
+ }
+
+ this.media.removeEventListener('seeking', this._onMediaSeeking);
+ this.fragmentTracker.removeAllFragments();
+ this.currentTrackId = -1;
+ this.tracks.forEach(function (track) {
+ _this2.tracksBuffered[track.id] = [];
+ });
+ this.media = null;
+ this.state = State.STOPPED;
+ } // If something goes wrong, proceed to next frag, if we were processing one.
+ ;
+
+ _proto.onError = function onError(data) {
+ var frag = data.frag; // don't handle error not related to subtitle fragment
+
+ if (!frag || frag.type !== 'subtitle') {
+ return;
+ }
+
+ if (this.fragCurrent && this.fragCurrent.loader) {
+ this.fragCurrent.loader.abort();
+ }
+
+ this.state = State.IDLE;
+ } // Got all new subtitle tracks.
+ ;
+
+ _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) {
+ var _this3 = this;
+
+ logger["logger"].log('subtitle tracks updated');
+ this.tracksBuffered = [];
+ this.tracks = data.subtitleTracks;
+ this.tracks.forEach(function (track) {
+ _this3.tracksBuffered[track.id] = [];
+ });
+ };
+
+ _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) {
+ this.currentTrackId = data.id;
+
+ if (!this.tracks || !this.tracks.length || this.currentTrackId === -1) {
+ this.clearInterval();
+ return;
+ } // Check if track has the necessary details to load fragments
+
+
+ var currentTrack = this.tracks[this.currentTrackId];
+
+ if (currentTrack && currentTrack.details) {
+ this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
+ }
+ } // Got a new set of subtitle fragments.
+ ;
+
+ _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {
+ var id = data.id,
+ details = data.details;
+ var currentTrackId = this.currentTrackId,
+ tracks = this.tracks;
+ var currentTrack = tracks[currentTrackId];
+
+ if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
+ return;
+ }
+
+ if (details.live) {
+ mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);
+ }
+
+ currentTrack.details = details;
+ this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
+ };
+
+ _proto.onKeyLoaded = function onKeyLoaded() {
+ if (this.state === State.KEY_LOADING) {
+ this.state = State.IDLE;
+ }
+ };
+
+ _proto.onFragLoaded = function onFragLoaded(data) {
+ var fragCurrent = this.fragCurrent;
+ var decryptData = data.frag.decryptdata;
+ var fragLoaded = data.frag;
+ var hls = this.hls;
+
+ if (this.state === State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
+ // check to see if the payload needs to be decrypted
+ if (data.payload.byteLength > 0 && decryptData && decryptData.key && decryptData.method === 'AES-128') {
+ var startTime = subtitle_stream_controller_performance.now(); // decrypt the subtitles
+
+ this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
+ var endTime = subtitle_stream_controller_performance.now();
+ hls.trigger(events["default"].FRAG_DECRYPTED, {
+ frag: fragLoaded,
+ payload: decryptedData,
+ stats: {
+ tstart: startTime,
+ tdecrypt: endTime
+ }
+ });
+ });
+ }
+ }
+ };
+
+ _proto.onLevelUpdated = function onLevelUpdated(_ref2) {
+ var details = _ref2.details;
+ var frags = details.fragments;
+ this.lastAVStart = frags.length ? frags[0].start : 0;
+ };
+
+ _proto.doTick = function doTick() {
+ if (!this.media) {
+ this.state = State.IDLE;
+ return;
+ }
+
+ switch (this.state) {
+ case State.IDLE:
+ {
+ var config = this.config,
+ currentTrackId = this.currentTrackId,
+ fragmentTracker = this.fragmentTracker,
+ media = this.media,
+ tracks = this.tracks;
+
+ if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
+ break;
+ }
+
+ var maxBufferHole = config.maxBufferHole,
+ maxFragLookUpTolerance = config.maxFragLookUpTolerance;
+ var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
+ var bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
+ var bufferEnd = bufferedInfo.end,
+ bufferLen = bufferedInfo.len;
+ var trackDetails = tracks[currentTrackId].details;
+ var fragments = trackDetails.fragments;
+ var fragLen = fragments.length;
+ var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
+
+ if (bufferLen > maxConfigBuffer) {
+ return;
+ }
+
+ var foundFrag;
+ var fragPrevious = this.fragPrevious;
+
+ if (bufferEnd < end) {
+ if (fragPrevious && trackDetails.hasProgramDateTime) {
+ foundFrag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
+ }
+
+ if (!foundFrag) {
+ foundFrag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
+ }
+ } else {
+ foundFrag = fragments[fragLen - 1];
+ }
+
+ if (foundFrag && foundFrag.encrypted) {
+ logger["logger"].log("Loading key for " + foundFrag.sn);
+ this.state = State.KEY_LOADING;
+ this.hls.trigger(events["default"].KEY_LOADING, {
+ frag: foundFrag
+ });
+ } else if (foundFrag && fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
+ // only load if fragment is not loaded
+ this.fragCurrent = foundFrag;
+ this.state = State.FRAG_LOADING;
+ this.hls.trigger(events["default"].FRAG_LOADING, {
+ frag: foundFrag
+ });
+ }
+ }
+ }
+ };
+
+ _proto.stopLoad = function stopLoad() {
+ this.lastAVStart = 0;
+ this.fragPrevious = null;
+
+ _BaseStreamController.prototype.stopLoad.call(this);
+ };
+
+ _proto._getBuffered = function _getBuffered() {
+ return this.tracksBuffered[this.currentTrackId] || [];
+ };
+
+ _proto.onMediaSeeking = function onMediaSeeking() {
+ if (this.fragCurrent) {
+ var currentTime = this.media ? this.media.currentTime : 0;
+ var tolerance = this.config.maxFragLookUpTolerance;
+ var fragStartOffset = this.fragCurrent.start - tolerance;
+ var fragEndOffset = this.fragCurrent.start + this.fragCurrent.duration + tolerance; // check if position will be out of currently loaded frag range after seeking : if out, cancel frag load, if in, don't do anything
+
+ if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
+ if (this.fragCurrent.loader) {
+ this.fragCurrent.loader.abort();
+ }
+
+ this.fragmentTracker.removeFragment(this.fragCurrent);
+ this.fragCurrent = null;
+ this.fragPrevious = null; // switch to IDLE state to load new fragment
+
+ this.state = State.IDLE; // speed up things
+
+ this.tick();
+ }
+ }
+ };
+
+ return SubtitleStreamController;
+}(base_stream_controller_BaseStreamController);
+// CONCATENATED MODULE: ./src/utils/mediakeys-helper.ts
+/**
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
+ */
+var KeySystems;
+
+(function (KeySystems) {
+ KeySystems["WIDEVINE"] = "com.widevine.alpha";
+ KeySystems["PLAYREADY"] = "com.microsoft.playready";
+})(KeySystems || (KeySystems = {}));
+
+var requestMediaKeySystemAccess = function () {
+ if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
+ return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
+ } else {
+ return null;
+ }
+}();
+
+
+// CONCATENATED MODULE: ./src/controller/eme-controller.ts
+function eme_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function eme_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) eme_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) eme_controller_defineProperties(Constructor, staticProps); return Constructor; }
+
+function eme_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+/**
+ * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
+ *
+ * DRM support for Hls.js
+ */
+
+
+
+
+
+var MAX_LICENSE_REQUEST_FAILURES = 3;
+/**
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
+ * @param {Array<string>} audioCodecs List of required audio codecs to support
+ * @param {Array<string>} videoCodecs List of required video codecs to support
+ * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
+ * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
+ */
+
+var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
+ /* jshint ignore:line */
+ var baseConfig = {
+ // initDataTypes: ['keyids', 'mp4'],
+ // label: "",
+ // persistentState: "not-allowed", // or "required" ?
+ // distinctiveIdentifier: "not-allowed", // or "required" ?
+ // sessionTypes: ['temporary'],
+ audioCapabilities: [],
+ // { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
+ videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
+
+ };
+ audioCodecs.forEach(function (codec) {
+ baseConfig.audioCapabilities.push({
+ contentType: "audio/mp4; codecs=\"" + codec + "\"",
+ robustness: drmSystemOptions.audioRobustness || ''
+ });
+ });
+ videoCodecs.forEach(function (codec) {
+ baseConfig.videoCapabilities.push({
+ contentType: "video/mp4; codecs=\"" + codec + "\"",
+ robustness: drmSystemOptions.videoRobustness || ''
+ });
+ });
+ return [baseConfig];
+};
+/**
+ * The idea here is to handle key-system (and their respective platforms) specific configuration differences
+ * in order to work with the local requestMediaKeySystemAccess method.
+ *
+ * We can also rule-out platform-related key-system support at this point by throwing an error.
+ *
+ * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
+ * @param {Array<string>} audioCodecs List of required audio codecs to support
+ * @param {Array<string>} videoCodecs List of required video codecs to support
+ * @throws will throw an error if a unknown key system is passed
+ * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
+ */
+
+
+var eme_controller_getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
+ switch (keySystem) {
+ case KeySystems.WIDEVINE:
+ return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
+
+ default:
+ throw new Error("Unknown key-system: " + keySystem);
+ }
+};
+
+/**
+ * Controller to deal with encrypted media extensions (EME)
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
+ *
+ * @class
+ * @constructor
+ */
+var eme_controller_EMEController = /*#__PURE__*/function (_EventHandler) {
+ eme_controller_inheritsLoose(EMEController, _EventHandler);
+
+ /**
+ * @constructs
+ * @param {Hls} hls Our Hls.js instance
+ */
+ function EMEController(hls) {
+ var _this;
+
+ _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHED, events["default"].MANIFEST_PARSED) || this;
+ _this._widevineLicenseUrl = void 0;
+ _this._licenseXhrSetup = void 0;
+ _this._emeEnabled = void 0;
+ _this._requestMediaKeySystemAccess = void 0;
+ _this._drmSystemOptions = void 0;
+ _this._config = void 0;
+ _this._mediaKeysList = [];
+ _this._media = null;
+ _this._hasSetMediaKeys = false;
+ _this._requestLicenseFailureCount = 0;
+ _this.mediaKeysPromise = null;
+
+ _this._onMediaEncrypted = function (e) {
+ logger["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
+
+ if (!_this.mediaKeysPromise) {
+ logger["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
+
+ _this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
+ fatal: true
+ });
+
+ return;
+ }
+
+ var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
+ if (!_this._media) {
+ return;
+ }
+
+ _this._attemptSetMediaKeys(mediaKeys);
+
+ _this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
+ }; // Could use `Promise.finally` but some Promise polyfills are missing it
+
+
+ _this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
+ };
+
+ _this._config = hls.config;
+ _this._widevineLicenseUrl = _this._config.widevineLicenseUrl;
+ _this._licenseXhrSetup = _this._config.licenseXhrSetup;
+ _this._emeEnabled = _this._config.emeEnabled;
+ _this._requestMediaKeySystemAccess = _this._config.requestMediaKeySystemAccessFunc;
+ _this._drmSystemOptions = hls.config.drmSystemOptions;
+ return _this;
+ }
+ /**
+ * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
+ * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
+ * @throws if a unsupported keysystem is passed
+ */
+
+
+ var _proto = EMEController.prototype;
+
+ _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
+ switch (keySystem) {
+ case KeySystems.WIDEVINE:
+ if (!this._widevineLicenseUrl) {
+ break;
+ }
+
+ return this._widevineLicenseUrl;
+ }
+
+ throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
+ }
+ /**
+ * Requests access object and adds it to our list upon success
+ * @private
+ * @param {string} keySystem System ID (see `KeySystems`)
+ * @param {Array<string>} audioCodecs List of required audio codecs to support
+ * @param {Array<string>} videoCodecs List of required video codecs to support
+ * @throws When a unsupported KeySystem is passed
+ */
+ ;
+
+ _proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
+ var _this2 = this;
+
+ // This can throw, but is caught in event handler callpath
+ var mediaKeySystemConfigs = eme_controller_getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
+ logger["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
+
+ var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
+ this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
+ return _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
+ });
+ keySystemAccessPromise.catch(function (err) {
+ logger["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
+ });
+ };
+
+ /**
+ * Handles obtaining access to a key-system
+ * @private
+ * @param {string} keySystem
+ * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
+ */
+ _proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
+ var _this3 = this;
+
+ logger["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
+ var mediaKeysListItem = {
+ mediaKeysSessionInitialized: false,
+ mediaKeySystemAccess: mediaKeySystemAccess,
+ mediaKeySystemDomain: keySystem
+ };
+
+ this._mediaKeysList.push(mediaKeysListItem);
+
+ var mediaKeysPromise = Promise.resolve().then(function () {
+ return mediaKeySystemAccess.createMediaKeys();
+ }).then(function (mediaKeys) {
+ mediaKeysListItem.mediaKeys = mediaKeys;
+ logger["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
+
+ _this3._onMediaKeysCreated();
+
+ return mediaKeys;
+ });
+ mediaKeysPromise.catch(function (err) {
+ logger["logger"].error('Failed to create media-keys:', err);
+ });
+ return mediaKeysPromise;
+ }
+ /**
+ * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
+ * for all existing keys where no session exists yet.
+ *
+ * @private
+ */
+ ;
+
+ _proto._onMediaKeysCreated = function _onMediaKeysCreated() {
+ var _this4 = this;
+
+ // check for all key-list items if a session exists, otherwise, create one
+ this._mediaKeysList.forEach(function (mediaKeysListItem) {
+ if (!mediaKeysListItem.mediaKeysSession) {
+ // mediaKeys is definitely initialized here
+ mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
+
+ _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
+ }
+ });
+ }
+ /**
+ * @private
+ * @param {*} keySession
+ */
+ ;
+
+ _proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
+ var _this5 = this;
+
+ logger["logger"].log("New key-system session " + keySession.sessionId);
+ keySession.addEventListener('message', function (event) {
+ _this5._onKeySessionMessage(keySession, event.message);
+ }, false);
+ }
+ /**
+ * @private
+ * @param {MediaKeySession} keySession
+ * @param {ArrayBuffer} message
+ */
+ ;
+
+ _proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
+ logger["logger"].log('Got EME message event, creating license request');
+
+ this._requestLicense(message, function (data) {
+ logger["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
+ keySession.update(data);
+ });
+ }
+ /**
+ * @private
+ * @param e {MediaEncryptedEvent}
+ */
+ ;
+
+ /**
+ * @private
+ */
+ _proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
+ if (!this._media) {
+ throw new Error('Attempted to set mediaKeys without first attaching a media element');
+ }
+
+ if (!this._hasSetMediaKeys) {
+ // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
+ var keysListItem = this._mediaKeysList[0];
+
+ if (!keysListItem || !keysListItem.mediaKeys) {
+ logger["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
+ fatal: true
+ });
+ return;
+ }
+
+ logger["logger"].log('Setting keys for encrypted media');
+
+ this._media.setMediaKeys(keysListItem.mediaKeys);
+
+ this._hasSetMediaKeys = true;
+ }
+ }
+ /**
+ * @private
+ */
+ ;
+
+ _proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
+ var _this6 = this;
+
+ // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
+ var keysListItem = this._mediaKeysList[0];
+
+ if (!keysListItem) {
+ logger["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
+ fatal: true
+ });
+ return;
+ }
+
+ if (keysListItem.mediaKeysSessionInitialized) {
+ logger["logger"].warn('Key-Session already initialized but requested again');
+ return;
+ }
+
+ var keySession = keysListItem.mediaKeysSession;
+
+ if (!keySession) {
+ logger["logger"].error('Fatal: Media is encrypted but no key-session existing');
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
+ fatal: true
+ });
+ return;
+ } // initData is null if the media is not CORS-same-origin
+
+
+ if (!initData) {
+ logger["logger"].warn('Fatal: initData required for generating a key session is null');
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
+ fatal: true
+ });
+ return;
+ }
+
+ logger["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
+ keysListItem.mediaKeysSessionInitialized = true;
+ keySession.generateRequest(initDataType, initData).then(function () {
+ logger["logger"].debug('Key-session generation succeeded');
+ }).catch(function (err) {
+ logger["logger"].error('Error generating key-session request:', err);
+
+ _this6.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
+ fatal: false
+ });
+ });
+ }
+ /**
+ * @private
+ * @param {string} url License server URL
+ * @param {ArrayBuffer} keyMessage Message data issued by key-system
+ * @param {function} callback Called when XHR has succeeded
+ * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
+ * @throws if XMLHttpRequest construction failed
+ */
+ ;
+
+ _proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
+ var xhr = new XMLHttpRequest();
+ var licenseXhrSetup = this._licenseXhrSetup;
+
+ try {
+ if (licenseXhrSetup) {
+ try {
+ licenseXhrSetup(xhr, url);
+ } catch (e) {
+ // let's try to open before running setup
+ xhr.open('POST', url, true);
+ licenseXhrSetup(xhr, url);
+ }
+ } // if licenseXhrSetup did not yet call open, let's do it now
+
+
+ if (!xhr.readyState) {
+ xhr.open('POST', url, true);
+ }
+ } catch (e) {
+ // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
+ throw new Error("issue setting up KeySystem license XHR " + e);
+ } // Because we set responseType to ArrayBuffer here, callback is typed as handling only array buffers
+
+
+ xhr.responseType = 'arraybuffer';
+ xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
+ return xhr;
+ }
+ /**
+ * @private
+ * @param {XMLHttpRequest} xhr
+ * @param {string} url License server URL
+ * @param {ArrayBuffer} keyMessage Message data issued by key-system
+ * @param {function} callback Called when XHR has succeeded
+ */
+ ;
+
+ _proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
+ switch (xhr.readyState) {
+ case 4:
+ if (xhr.status === 200) {
+ this._requestLicenseFailureCount = 0;
+ logger["logger"].log('License request succeeded');
+
+ if (xhr.responseType !== 'arraybuffer') {
+ logger["logger"].warn('xhr response type was not set to the expected arraybuffer for license request');
+ }
+
+ callback(xhr.response);
+ } else {
+ logger["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
+ this._requestLicenseFailureCount++;
+
+ if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
+ fatal: true
+ });
+ return;
+ }
+
+ var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
+ logger["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
+
+ this._requestLicense(keyMessage, callback);
+ }
+
+ break;
+ }
+ }
+ /**
+ * @private
+ * @param {MediaKeysListItem} keysListItem
+ * @param {ArrayBuffer} keyMessage
+ * @returns {ArrayBuffer} Challenge data posted to license server
+ * @throws if KeySystem is unsupported
+ */
+ ;
+
+ _proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
+ switch (keysListItem.mediaKeySystemDomain) {
+ // case KeySystems.PLAYREADY:
+ // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
+
+ /*
+ if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
+ // For PlayReady CDMs, we need to dig the Challenge out of the XML.
+ var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
+ if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
+ challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
+ } else {
+ throw 'Cannot find <Challenge> in key message';
+ }
+ var headerNames = keyMessageXml.getElementsByTagName('name');
+ var headerValues = keyMessageXml.getElementsByTagName('value');
+ if (headerNames.length !== headerValues.length) {
+ throw 'Mismatched header <name>/<value> pair in key message';
+ }
+ for (var i = 0; i < headerNames.length; i++) {
+ xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
+ }
+ }
+ break;
+ */
+ case KeySystems.WIDEVINE:
+ // For Widevine CDMs, the challenge is the keyMessage.
+ return keyMessage;
+ }
+
+ throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
+ }
+ /**
+ * @private
+ * @param keyMessage
+ * @param callback
+ */
+ ;
+
+ _proto._requestLicense = function _requestLicense(keyMessage, callback) {
+ logger["logger"].log('Requesting content license for key-system');
+ var keysListItem = this._mediaKeysList[0];
+
+ if (!keysListItem) {
+ logger["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
+ fatal: true
+ });
+ return;
+ }
+
+ try {
+ var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
+
+ var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
+
+ logger["logger"].log("Sending license request to URL: " + _url);
+
+ var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
+
+ _xhr.send(challenge);
+ } catch (e) {
+ logger["logger"].error("Failure requesting DRM license: " + e);
+ this.hls.trigger(events["default"].ERROR, {
+ type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
+ details: errors["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
+ fatal: true
+ });
+ }
+ };
+
+ _proto.onMediaAttached = function onMediaAttached(data) {
+ if (!this._emeEnabled) {
+ return;
+ }
+
+ var media = data.media; // keep reference of media
+
+ this._media = media;
+ media.addEventListener('encrypted', this._onMediaEncrypted);
+ };
+
+ _proto.onMediaDetached = function onMediaDetached() {
+ var media = this._media;
+ var mediaKeysList = this._mediaKeysList;
+
+ if (!media) {
+ return;
+ }
+
+ media.removeEventListener('encrypted', this._onMediaEncrypted);
+ this._media = null;
+ this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
+
+ Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
+ if (mediaKeysListItem.mediaKeysSession) {
+ return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
+ // generated no key requests will throw an error.
+ });
+ }
+ })).then(function () {
+ return media.setMediaKeys(null);
+ }).catch(function () {// Ignore any failures while removing media keys from the video element.
+ });
+ } // TODO: Use manifest types here when they are defined
+ ;
+
+ _proto.onManifestParsed = function onManifestParsed(data) {
+ if (!this._emeEnabled) {
+ return;
+ }
+
+ var audioCodecs = data.levels.map(function (level) {
+ return level.audioCodec;
+ });
+ var videoCodecs = data.levels.map(function (level) {
+ return level.videoCodec;
+ });
+
+ this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
+ };
+
+ eme_controller_createClass(EMEController, [{
+ key: "requestMediaKeySystemAccess",
+ get: function get() {
+ if (!this._requestMediaKeySystemAccess) {
+ throw new Error('No requestMediaKeySystemAccess function configured');
+ }
+
+ return this._requestMediaKeySystemAccess;
+ }
+ }]);
+
+ return EMEController;
+}(event_handler);
+
+/* harmony default export */ var eme_controller = (eme_controller_EMEController);
+// CONCATENATED MODULE: ./src/config.ts
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+/**
+ * HLS config
+ */
+
+
+
+
+ // import FetchLoader from './utils/fetch-loader';
+
+
+
+
+
+
+
+
+
+// If possible, keep hlsDefaultConfig shallow
+// It is cloned whenever a new Hls instance is created, by keeping the config
+// shallow the properties are cloned, and we don't end up manipulating the default
+var hlsDefaultConfig = _objectSpread(_objectSpread({
+ autoStartLoad: true,
+ // used by stream-controller
+ startPosition: -1,
+ // used by stream-controller
+ defaultAudioCodec: void 0,
+ // used by stream-controller
+ debug: false,
+ // used by logger
+ capLevelOnFPSDrop: false,
+ // used by fps-controller
+ capLevelToPlayerSize: false,
+ // used by cap-level-controller
+ initialLiveManifestSize: 1,
+ // used by stream-controller
+ maxBufferLength: 30,
+ // used by stream-controller
+ maxBufferSize: 60 * 1000 * 1000,
+ // used by stream-controller
+ maxBufferHole: 0.5,
+ // used by stream-controller
+ lowBufferWatchdogPeriod: 0.5,
+ // used by stream-controller
+ highBufferWatchdogPeriod: 3,
+ // used by stream-controller
+ nudgeOffset: 0.1,
+ // used by stream-controller
+ nudgeMaxRetry: 3,
+ // used by stream-controller
+ maxFragLookUpTolerance: 0.25,
+ // used by stream-controller
+ liveSyncDurationCount: 3,
+ // used by stream-controller
+ liveMaxLatencyDurationCount: Infinity,
+ // used by stream-controller
+ liveSyncDuration: void 0,
+ // used by stream-controller
+ liveMaxLatencyDuration: void 0,
+ // used by stream-controller
+ liveDurationInfinity: false,
+ // used by buffer-controller
+ liveBackBufferLength: Infinity,
+ // used by buffer-controller
+ maxMaxBufferLength: 600,
+ // used by stream-controller
+ enableWorker: true,
+ // used by demuxer
+ enableSoftwareAES: true,
+ // used by decrypter
+ manifestLoadingTimeOut: 10000,
+ // used by playlist-loader
+ manifestLoadingMaxRetry: 1,
+ // used by playlist-loader
+ manifestLoadingRetryDelay: 1000,
+ // used by playlist-loader
+ manifestLoadingMaxRetryTimeout: 64000,
+ // used by playlist-loader
+ startLevel: void 0,
+ // used by level-controller
+ levelLoadingTimeOut: 10000,
+ // used by playlist-loader
+ levelLoadingMaxRetry: 4,
+ // used by playlist-loader
+ levelLoadingRetryDelay: 1000,
+ // used by playlist-loader
+ levelLoadingMaxRetryTimeout: 64000,
+ // used by playlist-loader
+ fragLoadingTimeOut: 20000,
+ // used by fragment-loader
+ fragLoadingMaxRetry: 6,
+ // used by fragment-loader
+ fragLoadingRetryDelay: 1000,
+ // used by fragment-loader
+ fragLoadingMaxRetryTimeout: 64000,
+ // used by fragment-loader
+ startFragPrefetch: false,
+ // used by stream-controller
+ fpsDroppedMonitoringPeriod: 5000,
+ // used by fps-controller
+ fpsDroppedMonitoringThreshold: 0.2,
+ // used by fps-controller
+ appendErrorMaxRetry: 3,
+ // used by buffer-controller
+ loader: xhr_loader,
+ // loader: FetchLoader,
+ fLoader: void 0,
+ // used by fragment-loader
+ pLoader: void 0,
+ // used by playlist-loader
+ xhrSetup: void 0,
+ // used by xhr-loader
+ licenseXhrSetup: void 0,
+ // used by eme-controller
+ // fetchSetup: void 0,
+ abrController: abr_controller,
+ bufferController: buffer_controller,
+ capLevelController: cap_level_controller,
+ fpsController: fps_controller,
+ stretchShortVideoTrack: false,
+ // used by mp4-remuxer
+ maxAudioFramesDrift: 1,
+ // used by mp4-remuxer
+ forceKeyFrameOnDiscontinuity: true,
+ // used by ts-demuxer
+ abrEwmaFastLive: 3,
+ // used by abr-controller
+ abrEwmaSlowLive: 9,
+ // used by abr-controller
+ abrEwmaFastVoD: 3,
+ // used by abr-controller
+ abrEwmaSlowVoD: 9,
+ // used by abr-controller
+ abrEwmaDefaultEstimate: 5e5,
+ // 500 kbps // used by abr-controller
+ abrBandWidthFactor: 0.95,
+ // used by abr-controller
+ abrBandWidthUpFactor: 0.7,
+ // used by abr-controller
+ abrMaxWithRealBitrate: false,
+ // used by abr-controller
+ maxStarvationDelay: 4,
+ // used by abr-controller
+ maxLoadingDelay: 4,
+ // used by abr-controller
+ minAutoBitrate: 0,
+ // used by hls
+ emeEnabled: false,
+ // used by eme-controller
+ widevineLicenseUrl: void 0,
+ // used by eme-controller
+ drmSystemOptions: {},
+ // used by eme-controller
+ requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
+ // used by eme-controller
+ testBandwidth: true
+}, timelineConfig()), {}, {
+ subtitleStreamController: true ? subtitle_stream_controller_SubtitleStreamController : undefined,
+ subtitleTrackController: true ? subtitle_track_controller : undefined,
+ timelineController: true ? timeline_controller : undefined,
+ audioStreamController: true ? audio_stream_controller : undefined,
+ audioTrackController: true ? audio_track_controller : undefined,
+ emeController: true ? eme_controller : undefined
+});
+
+function timelineConfig() {
+ return {
+ cueHandler: cues_namespaceObject,
+ // used by timeline-controller
+ enableCEA708Captions: true,
+ // used by timeline-controller
+ enableWebVTT: true,
+ // used by timeline-controller
+ captionsTextTrack1Label: 'English',
+ // used by timeline-controller
+ captionsTextTrack1LanguageCode: 'en',
+ // used by timeline-controller
+ captionsTextTrack2Label: 'Spanish',
+ // used by timeline-controller
+ captionsTextTrack2LanguageCode: 'es',
+ // used by timeline-controller
+ captionsTextTrack3Label: 'Unknown CC',
+ // used by timeline-controller
+ captionsTextTrack3LanguageCode: '',
+ // used by timeline-controller
+ captionsTextTrack4Label: 'Unknown CC',
+ // used by timeline-controller
+ captionsTextTrack4LanguageCode: '',
+ // used by timeline-controller
+ renderTextTracksNatively: true
+ };
+}
+// CONCATENATED MODULE: ./src/hls.ts
+function hls_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function hls_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { hls_ownKeys(Object(source), true).forEach(function (key) { hls_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { hls_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function hls_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+function hls_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function hls_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function hls_createClass(Constructor, protoProps, staticProps) { if (protoProps) hls_defineProperties(Constructor.prototype, protoProps); if (staticProps) hls_defineProperties(Constructor, staticProps); return Constructor; }
+
+function hls_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/**
+ * @module Hls
+ * @class
+ * @constructor
+ */
+
+var hls_Hls = /*#__PURE__*/function (_Observer) {
+ hls_inheritsLoose(Hls, _Observer);
+
+ /**
+ * @type {boolean}
+ */
+ Hls.isSupported = function isSupported() {
+ return is_supported_isSupported();
+ }
+ /**
+ * @type {HlsEvents}
+ */
+ ;
+
+ hls_createClass(Hls, null, [{
+ key: "version",
+
+ /**
+ * @type {string}
+ */
+ get: function get() {
+ return "0.14.17";
+ }
+ }, {
+ key: "Events",
+ get: function get() {
+ return events["default"];
+ }
+ /**
+ * @type {HlsErrorTypes}
+ */
+
+ }, {
+ key: "ErrorTypes",
+ get: function get() {
+ return errors["ErrorTypes"];
+ }
+ /**
+ * @type {HlsErrorDetails}
+ */
+
+ }, {
+ key: "ErrorDetails",
+ get: function get() {
+ return errors["ErrorDetails"];
+ }
+ /**
+ * @type {HlsConfig}
+ */
+
+ }, {
+ key: "DefaultConfig",
+ get: function get() {
+ if (!Hls.defaultConfig) {
+ return hlsDefaultConfig;
+ }
+
+ return Hls.defaultConfig;
+ }
+ /**
+ * @type {HlsConfig}
+ */
+ ,
+ set: function set(defaultConfig) {
+ Hls.defaultConfig = defaultConfig;
+ }
+ /**
+ * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
+ *
+ * @constructs Hls
+ * @param {HlsConfig} config
+ */
+
+ }]);
+
+ function Hls(userConfig) {
+ var _this;
+
+ if (userConfig === void 0) {
+ userConfig = {};
+ }
+
+ _this = _Observer.call(this) || this;
+ _this.config = void 0;
+ _this._autoLevelCapping = void 0;
+ _this.abrController = void 0;
+ _this.capLevelController = void 0;
+ _this.levelController = void 0;
+ _this.streamController = void 0;
+ _this.networkControllers = void 0;
+ _this.audioTrackController = void 0;
+ _this.subtitleTrackController = void 0;
+ _this.emeController = void 0;
+ _this.coreComponents = void 0;
+ _this.media = null;
+ _this.url = null;
+ var defaultConfig = Hls.DefaultConfig;
+
+ if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
+ throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
+ } // Shallow clone
+
+
+ _this.config = hls_objectSpread(hls_objectSpread({}, defaultConfig), userConfig);
+
+ var _assertThisInitialize = hls_assertThisInitialized(_this),
+ config = _assertThisInitialize.config;
+
+ if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
+ throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
+ }
+
+ if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {
+ throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
+ }
+
+ Object(logger["enableLogs"])(config.debug);
+ _this._autoLevelCapping = -1; // core controllers and network loaders
+
+ /**
+ * @member {AbrController} abrController
+ */
+
+ var abrController = _this.abrController = new config.abrController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
+
+ var bufferController = new config.bufferController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
+
+ var capLevelController = _this.capLevelController = new config.capLevelController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
+
+ var fpsController = new config.fpsController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
+
+ var playListLoader = new playlist_loader(hls_assertThisInitialized(_this));
+ var fragmentLoader = new fragment_loader(hls_assertThisInitialized(_this));
+ var keyLoader = new key_loader(hls_assertThisInitialized(_this));
+ var id3TrackController = new id3_track_controller(hls_assertThisInitialized(_this)); // network controllers
+
+ /**
+ * @member {LevelController} levelController
+ */
+
+ var levelController = _this.levelController = new level_controller_LevelController(hls_assertThisInitialized(_this)); // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
+
+ var fragmentTracker = new fragment_tracker_FragmentTracker(hls_assertThisInitialized(_this));
+ /**
+ * @member {StreamController} streamController
+ */
+
+ var streamController = _this.streamController = new stream_controller(hls_assertThisInitialized(_this), fragmentTracker);
+ var networkControllers = [levelController, streamController]; // optional audio stream controller
+
+ /**
+ * @var {ICoreComponent | Controller}
+ */
+
+ var Controller = config.audioStreamController;
+
+ if (Controller) {
+ networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
+ }
+ /**
+ * @member {INetworkController[]} networkControllers
+ */
+
+
+ _this.networkControllers = networkControllers;
+ /**
+ * @var {ICoreComponent[]}
+ */
+
+ var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; // optional audio track and subtitle controller
+
+ Controller = config.audioTrackController;
+
+ if (Controller) {
+ var audioTrackController = new Controller(hls_assertThisInitialized(_this));
+ /**
+ * @member {AudioTrackController} audioTrackController
+ */
+
+ _this.audioTrackController = audioTrackController;
+ coreComponents.push(audioTrackController);
+ }
+
+ Controller = config.subtitleTrackController;
+
+ if (Controller) {
+ var subtitleTrackController = new Controller(hls_assertThisInitialized(_this));
+ /**
+ * @member {SubtitleTrackController} subtitleTrackController
+ */
+
+ _this.subtitleTrackController = subtitleTrackController;
+ networkControllers.push(subtitleTrackController);
+ }
+
+ Controller = config.emeController;
+
+ if (Controller) {
+ var emeController = new Controller(hls_assertThisInitialized(_this));
+ /**
+ * @member {EMEController} emeController
+ */
+
+ _this.emeController = emeController;
+ coreComponents.push(emeController);
+ } // optional subtitle controllers
+
+
+ Controller = config.subtitleStreamController;
+
+ if (Controller) {
+ networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
+ }
+
+ Controller = config.timelineController;
+
+ if (Controller) {
+ coreComponents.push(new Controller(hls_assertThisInitialized(_this)));
+ }
+ /**
+ * @member {ICoreComponent[]}
+ */
+
+
+ _this.coreComponents = coreComponents;
+ return _this;
+ }
+ /**
+ * Dispose of the instance
+ */
+
+
+ var _proto = Hls.prototype;
+
+ _proto.destroy = function destroy() {
+ logger["logger"].log('destroy');
+ this.trigger(events["default"].DESTROYING);
+ this.detachMedia();
+ this.coreComponents.concat(this.networkControllers).forEach(function (component) {
+ component.destroy();
+ });
+ this.url = null;
+ this.removeAllListeners();
+ this._autoLevelCapping = -1;
+ }
+ /**
+ * Attach a media element
+ * @param {HTMLMediaElement} media
+ */
+ ;
+
+ _proto.attachMedia = function attachMedia(media) {
+ logger["logger"].log('attachMedia');
+ this.media = media;
+ this.trigger(events["default"].MEDIA_ATTACHING, {
+ media: media
+ });
+ }
+ /**
+ * Detach from the media
+ */
+ ;
+
+ _proto.detachMedia = function detachMedia() {
+ logger["logger"].log('detachMedia');
+ this.trigger(events["default"].MEDIA_DETACHING);
+ this.media = null;
+ }
+ /**
+ * Set the source URL. Can be relative or absolute.
+ * @param {string} url
+ */
+ ;
+
+ _proto.loadSource = function loadSource(url) {
+ url = url_toolkit["buildAbsoluteURL"](window.location.href, url, {
+ alwaysNormalize: true
+ });
+ logger["logger"].log("loadSource:" + url);
+ this.url = url; // when attaching to a source URL, trigger a playlist load
+
+ this.trigger(events["default"].MANIFEST_LOADING, {
+ url: url
+ });
+ }
+ /**
+ * Start loading data from the stream source.
+ * Depending on default config, client starts loading automatically when a source is set.
+ *
+ * @param {number} startPosition Set the start position to stream from
+ * @default -1 None (from earliest point)
+ */
+ ;
+
+ _proto.startLoad = function startLoad(startPosition) {
+ if (startPosition === void 0) {
+ startPosition = -1;
+ }
+
+ logger["logger"].log("startLoad(" + startPosition + ")");
+ this.networkControllers.forEach(function (controller) {
+ controller.startLoad(startPosition);
+ });
+ }
+ /**
+ * Stop loading of any stream data.
+ */
+ ;
+
+ _proto.stopLoad = function stopLoad() {
+ logger["logger"].log('stopLoad');
+ this.networkControllers.forEach(function (controller) {
+ controller.stopLoad();
+ });
+ }
+ /**
+ * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
+ */
+ ;
+
+ _proto.swapAudioCodec = function swapAudioCodec() {
+ logger["logger"].log('swapAudioCodec');
+ this.streamController.swapAudioCodec();
+ }
+ /**
+ * When the media-element fails, this allows to detach and then re-attach it
+ * as one call (convenience method).
+ *
+ * Automatic recovery of media-errors by this process is configurable.
+ */
+ ;
+
+ _proto.recoverMediaError = function recoverMediaError() {
+ logger["logger"].log('recoverMediaError');
+ var media = this.media;
+ this.detachMedia();
+
+ if (media) {
+ this.attachMedia(media);
+ }
+ }
+ /**
+ * Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.
+ * This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user
+ * or hls.js can choose from.
+ *
+ * @param levelIndex {number} The quality level index to of the level to remove
+ * @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.
+ */
+ ;
+
+ _proto.removeLevel = function removeLevel(levelIndex, urlId) {
+ if (urlId === void 0) {
+ urlId = 0;
+ }
+
+ this.levelController.removeLevel(levelIndex, urlId);
+ }
+ /**
+ * @type {QualityLevel[]}
+ */
+ // todo(typescript-levelController)
+ ;
+
+ hls_createClass(Hls, [{
+ key: "levels",
+ get: function get() {
+ return this.levelController.levels;
+ }
+ /**
+ * Index of quality level currently played
+ * @type {number}
+ */
+
+ }, {
+ key: "currentLevel",
+ get: function get() {
+ return this.streamController.currentLevel;
+ }
+ /**
+ * Set quality level index immediately .
+ * This will flush the current buffer to replace the quality asap.
+ * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
+ * @param newLevel {number} -1 for automatic level selection
+ */
+ ,
+ set: function set(newLevel) {
+ logger["logger"].log("set currentLevel:" + newLevel);
+ this.loadLevel = newLevel;
+ this.streamController.immediateLevelSwitch();
+ }
+ /**
+ * Index of next quality level loaded as scheduled by stream controller.
+ * @type {number}
+ */
+
+ }, {
+ key: "nextLevel",
+ get: function get() {
+ return this.streamController.nextLevel;
+ }
+ /**
+ * Set quality level index for next loaded data.
+ * This will switch the video quality asap, without interrupting playback.
+ * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
+ * @type {number} -1 for automatic level selection
+ */
+ ,
+ set: function set(newLevel) {
+ logger["logger"].log("set nextLevel:" + newLevel);
+ this.levelController.manualLevel = newLevel;
+ this.streamController.nextLevelSwitch();
+ }
+ /**
+ * Return the quality level of the currently or last (of none is loaded currently) segment
+ * @type {number}
+ */
+
+ }, {
+ key: "loadLevel",
+ get: function get() {
+ return this.levelController.level;
+ }
+ /**
+ * Set quality level index for next loaded data in a conservative way.
+ * This will switch the quality without flushing, but interrupt current loading.
+ * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
+ * @type {number} newLevel -1 for automatic level selection
+ */
+ ,
+ set: function set(newLevel) {
+ logger["logger"].log("set loadLevel:" + newLevel);
+ this.levelController.manualLevel = newLevel;
+ }
+ /**
+ * get next quality level loaded
+ * @type {number}
+ */
+
+ }, {
+ key: "nextLoadLevel",
+ get: function get() {
+ return this.levelController.nextLoadLevel;
+ }
+ /**
+ * Set quality level of next loaded segment in a fully "non-destructive" way.
+ * Same as `loadLevel` but will wait for next switch (until current loading is done).
+ * @type {number} level
+ */
+ ,
+ set: function set(level) {
+ this.levelController.nextLoadLevel = level;
+ }
+ /**
+ * Return "first level": like a default level, if not set,
+ * falls back to index of first level referenced in manifest
+ * @type {number}
+ */
+
+ }, {
+ key: "firstLevel",
+ get: function get() {
+ return Math.max(this.levelController.firstLevel, this.minAutoLevel);
+ }
+ /**
+ * Sets "first-level", see getter.
+ * @type {number}
+ */
+ ,
+ set: function set(newLevel) {
+ logger["logger"].log("set firstLevel:" + newLevel);
+ this.levelController.firstLevel = newLevel;
+ }
+ /**
+ * Return start level (level of first fragment that will be played back)
+ * if not overrided by user, first level appearing in manifest will be used as start level
+ * if -1 : automatic start level selection, playback will start from level matching download bandwidth
+ * (determined from download of first segment)
+ * @type {number}
+ */
+
+ }, {
+ key: "startLevel",
+ get: function get() {
+ return this.levelController.startLevel;
+ }
+ /**
+ * set start level (level of first fragment that will be played back)
+ * if not overrided by user, first level appearing in manifest will be used as start level
+ * if -1 : automatic start level selection, playback will start from level matching download bandwidth
+ * (determined from download of first segment)
+ * @type {number} newLevel
+ */
+ ,
+ set: function set(newLevel) {
+ logger["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
+
+ if (newLevel !== -1) {
+ newLevel = Math.max(newLevel, this.minAutoLevel);
+ }
+
+ this.levelController.startLevel = newLevel;
+ }
+ /**
+ * set dynamically set capLevelToPlayerSize against (`CapLevelController`)
+ *
+ * @type {boolean}
+ */
+
+ }, {
+ key: "capLevelToPlayerSize",
+ set: function set(shouldStartCapping) {
+ var newCapLevelToPlayerSize = !!shouldStartCapping;
+
+ if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
+ if (newCapLevelToPlayerSize) {
+ this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
+ } else {
+ this.capLevelController.stopCapping();
+ this.autoLevelCapping = -1;
+ this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
+ }
+
+ this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
+ }
+ }
+ /**
+ * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
+ * @type {number}
+ */
+
+ }, {
+ key: "autoLevelCapping",
+ get: function get() {
+ return this._autoLevelCapping;
+ }
+ /**
+ * get bandwidth estimate
+ * @type {number}
+ */
+ ,
+
+ /**
+ * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
+ * @type {number}
+ */
+ set: function set(newLevel) {
+ logger["logger"].log("set autoLevelCapping:" + newLevel);
+ this._autoLevelCapping = newLevel;
+ }
+ /**
+ * True when automatic level selection enabled
+ * @type {boolean}
+ */
+
+ }, {
+ key: "bandwidthEstimate",
+ get: function get() {
+ var bwEstimator = this.abrController._bwEstimator;
+ return bwEstimator ? bwEstimator.getEstimate() : NaN;
+ }
+ }, {
+ key: "autoLevelEnabled",
+ get: function get() {
+ return this.levelController.manualLevel === -1;
+ }
+ /**
+ * Level set manually (if any)
+ * @type {number}
+ */
+
+ }, {
+ key: "manualLevel",
+ get: function get() {
+ return this.levelController.manualLevel;
+ }
+ /**
+ * min level selectable in auto mode according to config.minAutoBitrate
+ * @type {number}
+ */
+
+ }, {
+ key: "minAutoLevel",
+ get: function get() {
+ var levels = this.levels,
+ minAutoBitrate = this.config.minAutoBitrate;
+ var len = levels ? levels.length : 0;
+
+ for (var i = 0; i < len; i++) {
+ var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
+
+ if (levelNextBitrate > minAutoBitrate) {
+ return i;
+ }
+ }
+
+ return 0;
+ }
+ /**
+ * max level selectable in auto mode according to autoLevelCapping
+ * @type {number}
+ */
+
+ }, {
+ key: "maxAutoLevel",
+ get: function get() {
+ var levels = this.levels,
+ autoLevelCapping = this.autoLevelCapping;
+ var maxAutoLevel;
+
+ if (autoLevelCapping === -1 && levels && levels.length) {
+ maxAutoLevel = levels.length - 1;
+ } else {
+ maxAutoLevel = autoLevelCapping;
+ }
+
+ return maxAutoLevel;
+ }
+ /**
+ * next automatically selected quality level
+ * @type {number}
+ */
+
+ }, {
+ key: "nextAutoLevel",
+ get: function get() {
+ // ensure next auto level is between min and max auto level
+ return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
+ }
+ /**
+ * this setter is used to force next auto level.
+ * this is useful to force a switch down in auto mode:
+ * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
+ * forced value is valid for one fragment. upon succesful frag loading at forced level,
+ * this value will be resetted to -1 by ABR controller.
+ * @type {number}
+ */
+ ,
+ set: function set(nextLevel) {
+ this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
+ }
+ /**
+ * @type {AudioTrack[]}
+ */
+ // todo(typescript-audioTrackController)
+
+ }, {
+ key: "audioTracks",
+ get: function get() {
+ var audioTrackController = this.audioTrackController;
+ return audioTrackController ? audioTrackController.audioTracks : [];
+ }
+ /**
+ * index of the selected audio track (index in audio track lists)
+ * @type {number}
+ */
+
+ }, {
+ key: "audioTrack",
+ get: function get() {
+ var audioTrackController = this.audioTrackController;
+ return audioTrackController ? audioTrackController.audioTrack : -1;
+ }
+ /**
+ * selects an audio track, based on its index in audio track lists
+ * @type {number}
+ */
+ ,
+ set: function set(audioTrackId) {
+ var audioTrackController = this.audioTrackController;
+
+ if (audioTrackController) {
+ audioTrackController.audioTrack = audioTrackId;
+ }
+ }
+ /**
+ * @type {Seconds}
+ */
+
+ }, {
+ key: "liveSyncPosition",
+ get: function get() {
+ return this.streamController.liveSyncPosition;
+ }
+ /**
+ * get alternate subtitle tracks list from playlist
+ * @type {SubtitleTrack[]}
+ */
+ // todo(typescript-subtitleTrackController)
+
+ }, {
+ key: "subtitleTracks",
+ get: function get() {
+ var subtitleTrackController = this.subtitleTrackController;
+ return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
+ }
+ /**
+ * index of the selected subtitle track (index in subtitle track lists)
+ * @type {number}
+ */
+
+ }, {
+ key: "subtitleTrack",
+ get: function get() {
+ var subtitleTrackController = this.subtitleTrackController;
+ return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
+ }
+ /**
+ * select an subtitle track, based on its index in subtitle track lists
+ * @type {number}
+ */
+ ,
+ set: function set(subtitleTrackId) {
+ var subtitleTrackController = this.subtitleTrackController;
+
+ if (subtitleTrackController) {
+ subtitleTrackController.subtitleTrack = subtitleTrackId;
+ }
+ }
+ /**
+ * @type {boolean}
+ */
+
+ }, {
+ key: "subtitleDisplay",
+ get: function get() {
+ var subtitleTrackController = this.subtitleTrackController;
+ return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
+ }
+ /**
+ * Enable/disable subtitle display rendering
+ * @type {boolean}
+ */
+ ,
+ set: function set(value) {
+ var subtitleTrackController = this.subtitleTrackController;
+
+ if (subtitleTrackController) {
+ subtitleTrackController.subtitleDisplay = value;
+ }
+ }
+ }]);
+
+ return Hls;
+}(Observer);
+
+hls_Hls.defaultConfig = void 0;
+
+
+/***/ }),
+
+/***/ "./src/polyfills/number.js":
+/*!*********************************!*\
+ !*** ./src/polyfills/number.js ***!
+ \*********************************/
+/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
+var isFiniteNumber = Number.isFinite || function (value) {
+ return typeof value === 'number' && isFinite(value);
+};
+var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
+
+/***/ }),
+
+/***/ "./src/utils/get-self-scope.js":
+/*!*************************************!*\
+ !*** ./src/utils/get-self-scope.js ***!
+ \*************************************/
+/*! exports provided: getSelfScope */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelfScope", function() { return getSelfScope; });
+function getSelfScope() {
+ // see https://stackoverflow.com/a/11237259/589493
+ if (typeof window === 'undefined') {
+ /* eslint-disable-next-line no-undef */
+ return self;
+ } else {
+ return window;
+ }
+}
+
+/***/ }),
+
+/***/ "./src/utils/logger.js":
+/*!*****************************!*\
+ !*** ./src/utils/logger.js ***!
+ \*****************************/
+/*! exports provided: enableLogs, logger */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
+/* harmony import */ var _get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./get-self-scope */ "./src/utils/get-self-scope.js");
+
+
+function noop() {}
+
+var fakeLogger = {
+ trace: noop,
+ debug: noop,
+ log: noop,
+ warn: noop,
+ info: noop,
+ error: noop
+};
+var exportedLogger = fakeLogger; // let lastCallTime;
+// function formatMsgWithTimeInfo(type, msg) {
+// const now = Date.now();
+// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
+// lastCallTime = now;
+// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
+// return msg;
+// }
+
+function formatMsg(type, msg) {
+ msg = '[' + type + '] > ' + msg;
+ return msg;
+}
+
+var global = Object(_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])();
+
+function consolePrintFn(type) {
+ var func = global.console[type];
+
+ if (func) {
+ return function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ if (args[0]) {
+ args[0] = formatMsg(type, args[0]);
+ }
+
+ func.apply(global.console, args);
+ };
+ }
+
+ return noop;
+}
+
+function exportLoggerFunctions(debugConfig) {
+ for (var _len2 = arguments.length, functions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ functions[_key2 - 1] = arguments[_key2];
+ }
+
+ functions.forEach(function (type) {
+ exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
+ });
+}
+
+var enableLogs = function enableLogs(debugConfig) {
+ // check that console is available
+ if (global.console && debugConfig === true || typeof debugConfig === 'object') {
+ exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
+ // 'trace',
+ 'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
+ // fallback to default if needed
+
+ try {
+ exportedLogger.log();
+ } catch (e) {
+ exportedLogger = fakeLogger;
+ }
+ } else {
+ exportedLogger = fakeLogger;
+ }
+};
+var logger = exportedLogger;
+
+/***/ })
+
+/******/ })["default"];
+});
+//# sourceMappingURL=hls.js.map \ No newline at end of file
diff --git a/op25/gr-op25_repeater/www/www-static/index.html b/op25/gr-op25_repeater/www/www-static/index.html
new file mode 100644
index 0000000..2b8bbba
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/index.html
@@ -0,0 +1,897 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2020, 2021, 2022 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ UPDATED: 04-Mar-2022
+
+ -->
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <title>OP25</title>
+ <link rel="stylesheet" type="text/css" id="mainStyle" href="main.css">
+ <script src="jquery.js"></script>
+ <script src="main.js"></script>
+ <script src="config.js"></script> <!-- online config stuff -->
+ <script src="editor.js"></script>
+ <script src="jquery.alerts.js"></script>
+ </head>
+ <body onload="javascript:do_onload();">
+ <div class="row"> <!-- START OF 2 COLUMN LAYOUT -->
+ <div class="column" style="width: 740px;"> <!-- START FIRST COLUMN -->
+ <div class="main">
+ <form method="post" action="#" id="form_scan">
+ <!-- nav bar -->
+ <div class="nav-bar" id="nav-bar">
+ <ul class="nav-ul">
+ <li id="li1" class="nav-li"><input id="b1" class="nav-button" type="button" name="B1" value="Home" onclick="this.blur(); javascript:f_select('status');"></li>
+ <li id="li2" class="nav-li"><input id="b2" class="nav-button" type="button" name="B2" value="Config" onclick="this.blur(); javascript:f_select('settings');"></li>
+ <li id="li3" class="nav-li"><input id="b3" class="nav-button" type="button" name="B3" value="RX" onclick="this.blur(); javascript:f_select('rx');"></li>
+ <li id="lix" class="nav-li"><input id="bx" class="nav-button" type="button" name="Bx" value="Logs" onclick="$('#btnLogs').trigger('click');"></li>
+ <li id="li4" class="nav-li"><input id="b4" class="nav-button" type="button" name="B4" value="Help" onclick="this.blur(); javascript:f_select('help');"></li>
+ <li id="li5" class="nav-li"><input id="b5" class="nav-button" type="button" name="B5" value="View" onclick="this.blur(); javascript:toggleCSS();"></li>
+ <li id="li6" class="nav-li"><input id="b6" class="nav-button" type="button" name="B6" value="Popout" onclick="this.blur(); javascript:this.blur(); popOut();"></li>
+ <li id="li7" class="nav-li"><input id="b7" class="nav-button" type="button" name="B7" value="About" onclick="this.blur(); javascript:f_select('about');"></li>
+ <li id="li8"> </li>
+
+ </ul>
+ </div>
+ <!-- end div nav-bar -->
+ </form>
+ <div id="div_debug" style="display: block;"></div>
+ <!-- end div_debug -->
+ <div id="div_help" class="help" style="display:none;">
+ <P>
+ <h2>Keyboard Shortcuts</h2>
+ G - Go To <br>
+ L - Lockout<br>
+ H - Hold<br>
+ S - Skip/Scan<br>
+ V - View (light/dark toggle)<br>
+ R - RX Screen<br>
+ J - Home Screen<br>
+ M - Minify<br>
+ P - Show / Hide Plots<br>
+ B - Make display text BOLD<br>
+ N - Make display text NORMAL<br>
+ 1 - Show / Hide Call History<br>
+ 2 - Show / Hide Events<br>
+ 3 - Show / Hide Logs Block<br>
+ 4 - Show / Hide Channel ID Band Plan<br>
+ <br>
+ <h2>Setup and Monitor a Trunked System</h2>
+ Before proceeding you will need to know the control channel frequency or frequencies for your system and the system NAC code. Also needed is the frequency correction (PPM) value for your SDR.
+ <ul>
+ <li>Select "Configuration" from the top nav bar</li>
+ <li>Select "sample_trunked" from the list of available configurations; then click "Edit"</li>
+ <li>
+ The various Frequency parameters are used as follows:
+ <ul>
+ <li>The Channel frequency is the same as the "center frequency". If the entire P25 system being monitored fits within the sampling band (as defined by the device sampling rate), choose a frequency that is halfway between the lowest and highest system frequencies and enter it here. OP25 will use a "software LO" to achieve tuning within this band. If the value is zero or if the desired frequency when retuning is outside the sampling band, OP25 will change the SDR hardware receive frequency each time a frequency change is needed.</li>
+ <li>The Device frequency is ignored in trunked operation, but must be set to a non-zero number. TODO: fix this.</li>
+ <li>Under "Trunking Info" the "CC Freq's" should be set to a list of control channel frequencies. If your system has more than one control channel you should enter them as a comma separated list. Some systems with multiple control channels seem to favor a certain frequency; if so you can speed up acquisition by entering such channel(s) first in the list.</li>
+ </ul>
+ <li>Enter the frequency correction value of the SDR device in the "PPM" field. If your SDR is GPSDO stabilized, you can enter zero here; all others must contend with setting a proper correction value.</li>
+ <li>Enter the name of your system in the channel "Name" input.</li>
+ <li>Enter the system NAC.</li>
+ <li>Be sure to check the "P2 TDMA" box if your system utilizes P25 Phase 2/TDMA.</li>
+ <li>Choose and enter a name for the new configuration file and click "Save".</li>
+ <li>The displayed list of configurations should update, showing the new configuration.</li>
+ <li>After selecting the configuration from the list, click "Start" to launch the receiver app (rx.py) in the background*</li>
+ </ul>
+ *The "Start" and "Stop" options are only usable when OP25 has been started in the backend as "http.py", not as "rx.py" or "multi_rx.py".
+ <h3>NOTES</h3>
+ <ul>
+ <li>Configuration files are saved in the <span class="tt">op25/gr-op25_repeater/www/config</span> directory, as JSON.</li>
+ <li>If you aleady have installed OP25 with a TSV configuration file, to import the TSV config files check the box to include TSV files and click "Refresh". TSV files are searched for in the <span class="tt">op25/gr-op25_repeater/apps</span> directory.</li>
+ <li>The current version does not allow configurations with more than one channel unless all the channels share the same value for the "Trunked" parameter. That is, the configuration must define either none of the channels as trunked or all of the channels as trunked. The selected backend used in these two cases is multi_rx.py or rx.py, respectively.</li>
+ <li>You can define more than one trunked (P25) system by adding an additional channel for each one. The list of currently-active channels can be managed from the HTTP console "Home" page.</li>
+ <li>Please refer to <a href="https://osmocom.org/projects/gr-osmosdr/wiki" target="_blank">this page</a> for details about specifying the Device Args parameter values for your SDR device.</li>
+ <li>After creating and verifying a configuration you can arrange for that configuration to be automatically started whenever <span class="tt">http.py</span> is (re)started. When starting <span class="tt">http.py</span>, use the <span class="tt">-c <em>Name</em></span> parameter to give the name of the configuration to be started. <span class="tt"><em>Name</em></span> should not contain any prefixes or suffixes,</li>
+ </ul>
+ </div>
+ <!-- end div_help -->
+ <div id="div_about" class="copyright-text" style="display:none;">
+ <br>
+ <table class="aboutTable">
+ <tr>
+ <td>
+ <span class="copyright-text">
+ This program comes with ABSOLUTELY NO WARRANTY.<br>
+ OP25 is free software, and you are welcome to redistribute it<br>
+ under certain conditions. For further details refer to the "License"
+ link (below).
+ </span>
+ <br><br>
+ <table style="border-collapse: collapse;">
+ <tr>
+ <td>Copyright:</td>
+ <td>&copy; 2017&dash;2022 Max H. Parke KA1RBI</td>
+ </tr>
+ <tr>
+ <td>License:</td>
+ <td><a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank">https://www.gnu.org/licenses/gpl-3.0.en.html</a></td>
+ </tr>
+ <tr>
+ <td>Mailing list:</td>
+ <td><a href="https://lists.osmocom.org/mailman/listinfo/op25-dev" target="_blank">https://lists.osmocom.org/mailman/listinfo/op25-dev</a></td>
+ </tr>
+ <tr>
+ <td>Download:</td>
+ <td><span class="tt">git clone https://git.osmocom.org/op25</span></td>
+ </tr>
+ <tr>
+ <td>Website:</td>
+ <td><a href="http://op25.osmocom.org" target="_blank">http://op25.osmocom.org</a></td>
+ </tr>
+ <tr>
+ <td>UI Updated:</td>
+ <td><span id="uiupdated"></span></td>
+ </table>
+ </td>
+ <td>
+ <div class="aboutMsg"> <br><br><br><br><br><br><br><br><br><br><br><br><br><br>&nbsp; </div>
+ </td>
+ </table>
+ </div>
+ <!-- end div_about -->
+ </div>
+ <!-- end div class=main -->
+ <br>
+ <div id="div_status" style="display: none;">
+ <div id="controlsDisplay" class="controlsDisplay">
+ <div id="controls" class="controls">
+ <div>
+ <input type="button" class="control-button" name="skip" value="SCAN" onclick="javascript:this.blur(); f_scan_button(&quot;skip&quot;);">
+ </div>
+ <div>
+ <input type="button" class="control-button" name="hold" value="HOLD" onclick="javascript:this.blur(); f_scan_button(&quot;hold&quot;);">
+ </div>
+ <div>
+ <input type="button" class="control-button" name="lockout" value="LOCKOUT" onclick="javascript:this.blur(); f_scan_button(&quot;lockout&quot;);">
+ </div>
+ <div>
+ <input type="button" class="control-button" name="popout" value="GO TO" onclick="javascript:f_goto_button(&quot;goto&quot;);">
+ </div>
+ </div>
+ <div class="statDisplay">
+ <div id="div_s2" class="s2" style="display: none;">
+ <!-- frequency, system, tg display -->
+ </div>
+ </div>
+ <div class="sysMsg">
+ <!-- hold / last command box w/ logo-->
+ <div id="holdIndicator" class="label-hold" style="display: none;"><br>TG HOLD ON</div>
+ <div id="lastCommand" class="label-lc"> &nbsp; </div>
+ <div id="stx" class="label-lc"> &nbsp; </div>
+ <br>
+ </div>
+ </div>
+
+ <div id="div_presets" style="display: none;">
+ <button id="btnPreset1" onclick="this.blur(); doPreset(1);" style="width: 98px;" class="psbutton">Preset 1</button>
+ <button id="btnPreset2" onclick="this.blur(); doPreset(2);" style="width: 98px;" class="psbutton">Preset 2</button>
+ <button id="btnPreset3" onclick="this.blur(); doPreset(3);" style="width: 98px;" class="psbutton">Preset 3</button>
+ <button id="btnPreset4" onclick="this.blur(); doPreset(4);" style="width: 98px;" class="psbutton">Preset 4</button>
+ <button id="btnPreset5" onclick="this.blur(); doPreset(5);" style="width: 98px;" class="psbutton">Preset 5</button>
+ <button id="btnPreset6" onclick="this.blur(); doPreset(6);" style="width: 98px;" class="psbutton">Preset 6</button>
+ <button id="btnPreset7" onclick="this.blur(); doPreset(7);" style="width: 98px;" class="psbutton">Preset 7</button>
+ </div>
+
+ <div id="preload" style="display: none;"><img src="loading.gif" style="height: 20px;" id="loading-pre" alt="loading"></div>
+ <div id="babysitter" style="text-align: center; width: 720px;">
+ <span class="label"><br>OP25 EventSource not present. Waiting for data. Status: <span id="estat">OK</span><br><br><img src="loading.gif" style="height: 20px;" alt="loading"></span>
+ </div>
+
+
+ <!-- for testing / debug -->
+ <div id="div_s1" class="s1">
+ <!-- system freq and adjacent sites -->
+ <div style="text-align: center;"><span class="label"><br>Waiting for data... <img src="loading.gif" style="height: 20px;" alt="loading"></span></div>
+ </div>
+ <br>
+ <div id="div_images" class="s1">
+ <table class="plot" id="plot">
+ <!-- <table id="plot_table"> -->
+ <tr>
+ <td>
+ <img src="1x1.png" id="img0" style="display:none;" alt="plot">
+ </td>
+ <td>
+ <img src="1x1.png" id="img1" style="display:none;" alt="plot">
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <img src="1x1.png" id="img2" style="display:none;" alt="plot">
+ </td>
+ <td>
+ <img src="1x1.png" id="img3" style="display:none;" alt="plot">
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <img src="1x1.png" id="img4" style="display:none;" alt="plot">
+ </td>
+ <td>
+ <img src="1x1.png" id="img5" style="display:none;" alt="plot">
+ </td>
+ </tr>
+ </table>
+ </div>
+ <!-- end div_images -->
+ </div>
+ <!-- end div_status -->
+ <div id="div_plot" style="display: none;"></div>
+ <!-- end div_plot -->
+ <div id="div_settings" class="div_settings" style="display: none;">
+ <!-- Main Display Settings -->
+ <table class="dsettings">
+ <th colspan="3">Display Settings</th>
+ <tr>
+ <td style="border-right: 0px solid;">UI Display Mode Toggle</td>
+ <td style="width: 85px; border-left: 0px solid;">
+ <!-- <button id="displayMode" onclick="this.blur(); toggleCSS();">Light / Dark</button> -->
+ <select name="selDispMode" id="selDispMode" onchange="sdmodeChange();" style="width: 75px;">
+ <option value="dark">Dark</option>
+ <option value="light">Light</option>
+ </select>
+ <script> sdmode();</script>
+ </td>
+ <td>
+ <input type="checkbox" id="show_adj" checked><label for="show_adj"> <span></span> Show Adjacent Sites on RX Screen</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;">System Font Size</td>
+ <td style="border-left: 0px solid;">
+ <select name="valSystemFont" id="valSystemFont" titl="Default: 24" style="width: 75px;">
+ <option value="28">28</option>
+ <option value="26">26</option>
+ <option value="24" selected>24</option>
+ <option value="20">20</option>
+ <option value="18">18</option>
+ <option value="16">16</option>
+ <option value="14">14</option>
+ <option value="12">12</option>
+ </select>
+ </td>
+ <td title="462.0 vs. 462.00000 462.125 vs. 462.12500">
+ <input type="checkbox" id="trailing_zeros" checked><label for="trailing_zeros"> <span></span> Show Trailing Zeros on Frequencies </label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;">Talkgroup Font Size</td>
+ <td style="border-left: 0px solid;">
+ <select name="valTagFont" id="valTagFont" titl="Default: 24" style="width: 75px;">
+ <option value="28">28</option>
+ <option value="26">26</option>
+ <option value="24" selected>24</option>
+ <option value="20">20</option>
+ <option value="18">18</option>
+ <option value="16">16</option>
+ <option value="14">14</option>
+ <option value="12">12</option>
+ </select>
+ </td>
+ <td>
+ <input type="checkbox" id="color_main_tag"> <label for="color_main_tag"><span></span> Use TG Colors in Main Display - Talkgroup</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;">Main Display Font Style</td>
+ <td style="border-left: 0px solid;">
+ <select name="valFontStyle" id="valFontStyle" style="width: 75px;">
+ <option value="normal">Normal</option>
+ <option value="bold" selected>Bold</option>
+ </select>
+ </td>
+ <td>
+ <input type="checkbox" id="color_main_sys"><label for="color_main_sys"><span></span> Use TG Colors in Main Display - System</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;"> Animation Speed (0 = off) </td>
+ <td style="border-left: 0px solid;" title="In milliseconds. Default = 0">
+ <select name="ani_speed" id="ani_speed" style="width: 75px;" >
+ <option value="0" selected>0</option>
+ <option value="250">250 ms</option>
+ <option value="500">500 ms</option>
+ <option value="1000">1000 ms</option>
+ </select>
+ </td>
+ <td>
+ <input type="checkbox" id="showBandPlan"> <label for="showBandPlan"><span></span> Show Band Plan on RX Screen</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;"> <label for="unk_default"> <span></span> Color Code for Unknown Talkgroups</label> </td>
+ <td style="border-left: 0px solid;" colspan="1" title="Unkown talkgroups are talkgoups which are not in the talkgroup TSV file.">
+ <select name="unk_default" id="unk_default" style="width: 75px;" >
+ <option value="0">0</option>
+ <!-- 1-99 added in the js -->
+ </select>
+ </td>
+ <td>
+ <input type="checkbox" id="hide_enc"><label for="hide_enc"> <span></span> Exclude Encrypted Calls from History Log</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;" title="Default = 50">Max Display String Length: </td>
+ <td style="border-left: 0px solid;">
+ <select name="valTruncate" id="valTagFont" titl="Default: 50" style="width: 75px;">
+ <option value="20">20</option>
+ <option value="25">25</option>
+ <option value="35">35</option>
+ <option value="50" selected>50</option>
+ <option value="60">60</option>
+ <option value="75">75</option>
+ <option value="100">100</option>
+ </select>
+
+ </td>
+ <td>
+ <input type="checkbox" id="showSlot"> <label for="showSlot"><span></span> Show Timeslots in Call History Log</label>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;">
+ <input type="checkbox" id="showEnc"> <label for="showEnc"><span></span> Show Encryption Information in Main Display</label>
+ </td>
+
+ <td style="border-left: 0px solid;">
+ &nbsp;
+ </td>
+ </td>
+ <td>
+ <input type="checkbox" id="showLast"> <label for="showLast"><span></span> Show Last Seen Time in Frequency Table</label>
+ </td>
+ </tr>
+
+ <tr>
+ <td style="border-right: 0px solid;">
+ <input type="checkbox" id="showSourceId"> <label for="showSourceId"><span title="Show subscriber ID in Main Display when source tag is not present."></span> Show Source ID if source tag not present.</label>
+ </td>
+ <td style="border-left: 0px solid;">&nbsp;</td>
+ <td>
+ <input type="checkbox" id="colSlot2"> <label for="colSlot2"><span title="Collapses Slot 2 in Active Frequency Table after 2 minutes of inactivity."></span> Collapse Slot 2 Display After 2 min.</label>
+ </td>
+ </tr>
+
+ <tr>
+ <td colspan="3">
+ <input type="checkbox" id="smartcolors"> <label for="smartcolors"><span></span>Use SmartColors -
+ searches the talkgroup name for each item in the box below and applies the color on match.
+ Separate each item by a space. Example: <b>pd police swat so sheriff</b>. Color code in TSV file has priority over SmartColors. SmartColors evaluated 1 through 4.</label><br><br>
+ <span class="c1">SmartColor 1: </span><input type="text" id="sc1" value="police pd sheriff so swat"> <br><br>
+ <span class="c2">SmartColor 2: </span><input type="text" id="sc2" value="fd fire"> <br><br>
+ <span class="c3">SmartColor 3: </span><input type="text" id="sc3" value="ac amr ccco"> <br><br>
+ <span class="c4">SmartColor 4: </span><input type="text" id="sc4" value=""> <br><br>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3">
+ <table style="width: 100%; border: 0px;">
+ <th colspan="6">UI Colors</th>
+ <tr>
+ <td style="text-align: center;"><a href="tsv-edit.html?mode=color&css=dark" target="_blank"><button title="Display and edit talkgroup tag and source tag color codes." onclick="this.blur();">Tag Colors Editor</button></a>
+ </td>
+ <td style="text-align: center;">
+ Accent 1 <br>
+ <input type="color" title="Top accent color in main display." class="accColor" id="acc1">
+ </td>
+ <td style="text-align: center;">
+ Accent 2 <br>
+ <input type="color" title="Bottom accent color in main display." class="accColor" id="acc2">
+ </td>
+ <td style="text-align: center;">
+ Values <br>
+ <input type="color" title="Data values" class="valColor" id="valColor">
+ </td>
+ <td style="text-align: center;">
+ System / TG <br>
+ <input type="color" title="Default color for system/talkgroup display (when TG Colors options above are not used)." class="sysColor" id="sysColor">
+ </td>
+ <td style="text-align: center;">
+ Buttons <br>
+ <input type="color" title="Button label font color" class="btnColor" id="btnColor">
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+
+ <tr> <!-- Presets -->
+
+ <td colspan="3">
+ <span class="label"><b>Go To Presets</b></span><br><br>
+ <input type="checkbox" id="usePresets" onclick="presetTable();" checked><label for="usePresets"> <span></span> Use Go To Preset Controls</label> <br>
+
+ <div id="configPresets">
+ <br>
+ <table width="100%">
+ <tr><th>Preset</th><th>TGID</th><th>Button Tag</th><th>Color</th></tr>
+
+ <tr><td> 1 </td> <td> <input type="text" id="preset-tg1" value="1111"> </td> <td> <input type="text" id="preset-tag1" value="Preset 1"> </td><td> <input type="color" class="accColor" id="psc1" value="#00FFFF"> </td></tr>
+ <tr><td> 2 </td> <td> <input type="text" id="preset-tg2" value="2222"> </td> <td> <input type="text" id="preset-tag2" value="Preset 2"> </td><td> <input type="color" class="accColor" id="psc2" value="#00FFFF"> </td></tr>
+ <tr><td> 3 </td> <td> <input type="text" id="preset-tg3" value="3333"> </td> <td> <input type="text" id="preset-tag3" value="Preset 3"> </td><td> <input type="color" class="accColor" id="psc3" value="#00FFFF"> </td></tr>
+ <tr><td> 4 </td> <td> <input type="text" id="preset-tg4" value="4444"> </td> <td> <input type="text" id="preset-tag4" value="Preset 4"> </td><td> <input type="color" class="accColor" id="psc4" value="#00FFFF"> </td></tr>
+ <tr><td> 5 </td> <td> <input type="text" id="preset-tg5" value="5555"> </td> <td> <input type="text" id="preset-tag5" value="Preset 5"> </td><td> <input type="color" class="accColor" id="psc5" value="#00FFFF"> </td></tr>
+ <tr><td> 6 </td> <td> <input type="text" id="preset-tg6" value="6666"> </td> <td> <input type="text" id="preset-tag6" value="Preset 6"> </td><td> <input type="color" class="accColor" id="psc6" value="#00FFFF"> </td></tr>
+ <tr><td> 7 </td> <td> <input type="text" id="preset-tg7" value="7777"> </td> <td> <input type="text" id="preset-tag7" value="Preset 7"> </td><td> <input type="color" class="accColor" id="psc7" value="#00FFFF"> </td></tr>
+ </table>
+ </div>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3">
+ <span class="label">
+ <b>Log events in browser: </b><br><br>
+ <input type="checkbox" id="log_cc" checked><label for="log_cc"> <span></span> Control Channel Event</label> <br>
+ &nbsp;&nbsp;&nbsp; Log these:
+ <input type="checkbox" id="je_joins" checked> <label for="je_joins"> <span></span> Joins (28, 2b)</label>
+ &nbsp;&nbsp;&nbsp;
+ <input type="checkbox" id="je_log" checked> <label for="je_log"> <span></span> Login (2c), Logout (2f)</label>
+ &nbsp;&nbsp;&nbsp;
+ <input type="checkbox" id="je_calls" checked> <label for="je_calls"> <span></span> Calls (00)</label>
+ &nbsp;&nbsp;&nbsp;
+ <input type="checkbox" id="je_deny" checked> <label for="je_deny"> <span></span> Denials (27. 2b)</label>
+ <br>
+ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+ <input type="checkbox" id="je_extfunc" checked> <label for="je_extfunc"> <span></span> Extended Functions (24)</label>
+ <br>
+ <input type="checkbox" id="log_cf"> <label for="log_cf"> <span></span> Change Frequency</label> <br>
+ <input type="checkbox" id="log_tu"> <label for="log_tu"> <span></span> Trunk Update </label><br>
+ <input type="checkbox" id="log_rx"> <label for="log_rx"> <span></span> RX Update</label><br> <!-- default = unchecked, rx update doesn't tell us much -->
+ </span>
+ </td>
+ </tr>
+ <tr>
+ <td style="border-right: 0px solid;">
+ Number of Rows in Browser Log Tables
+ </td>
+ <td style="border-left: 0px solid;">
+ <select name="log_len" id="log_len" title="Default: 2,000" style="width: 75px;">
+ <option value="250">250</option>
+ <option value="500">500</option>
+ <option value="1000">1,000</option>
+ <option value="2000" selected>2,000</option>
+ <option value="2500">2,500</option>
+ <option value="5000">5,000</option>
+ <option value="10000">10,000</option>
+ <option value="25000">25,000</option>
+ </select>
+
+ </td>
+ <td> </td>
+ </tr>
+ <tr>
+ <td colspan="3">
+ OP25 Logs IP: <input type="text" id="oplogip" style="width: 150px;">
+ &nbsp;&nbsp;&nbsp;
+ Port: <input type="text" id="oplogport" style="width: 50px;">
+ &nbsp;&nbsp;&nbsp;
+ <input type="text" id="oplogUrl" style="width: 200px;" title="OP25 Logs URL - Requires the OP25 Flask App"> <button id="btnLogs" onclick="this.blur(); navOplog();">Go</button>
+
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3" style="text-align:center;">
+ <button style = "width: 170px; height: 36px;" id="saveSettings" onclick="this.blur(); saveDisplaySettings();">Save Settings</button>
+ &nbsp;&nbsp;
+ <button style = "width: 170px; height: 36px;" id="loadSettings" onclick="this.blur(); beginJsonSettings();">Load Saved Settings</button>
+ </td>
+ </table>
+ <!-- End Main Display Settings -->
+
+
+<!-- Hide config settings stuff until we figure out what to do with it. -->
+ <div style="display: none;">
+ <form method="post" action="#" id="form_settings">
+ <p>
+ <div id="cfg_list_area" class="cfg_list"></div>
+ <p>
+ <input type="button" class="plain-button" name="load" value="Edit" onclick="javascript:f_load();"><span class="label"> - Open configuration editor (any previous unsaved work will be lost)</span><br>
+ <input type="button" class="plain-button" name="list" value="Refresh" onclick="javascript:f_list();"><span class="label"> - Reload selection list</span>
+ <input type=checkbox id="include_tsv" name="include_tsv"> <span class="label">Include old-style trunking TSV files</span>
+ <br>
+ <input type="button" class="plain-button" name="start" value="Start" onclick="javascript:f_start();"><span class="label"> - Run flowgraph using selected configuration</span><br>
+ <input type="button" class="plain-button" name="stop" value="Stop" onclick="javascript:f_stop();"><span class="label"> - End running flowgraph</span><br>
+ <br>
+ <div id="answer_area"></div>
+ <div id="edit_settings" style="display: none">
+ <hr>
+ <br>
+ <input type="button" name="save" value="Save" onclick="javascript:f_save();">
+ - Store configuration. Name:
+ <input type="text" id="config_name" name="config_name" value="">
+ <br>
+ <div id="div_rx_opts">
+ <table border=1 id="rxopt-table" style="display: none">
+ <tr>
+ <th colspan=2 class="boxtitle-th"><span class="boxtitle">Backend Options [rx.py]</span></th>
+ <th colspan=2>
+ <input type="button" name="show" value="Show" onclick="javascript:show_advanced(this)">advanced options
+ </th>
+ </tr>
+ <tr>
+ <th>enable built-in udp audio player</th>
+ <th>voice codec</th>
+ <th>fine tuning</th>
+ <th>Wireshark host</th>
+ </tr>
+ <tr id="rxrow" class="rxrow">
+ <td><input type=checkbox name="udp-player" ></td>
+ <td><input type=checkbox name="vocoder" ></td>
+ <td><input type=text name="fine-tune" value="0"></td>
+ <td><input type=text name="wireshark-host" value="127.0.0.1"></td>
+ </tr>
+ <tr id="advrow" class="advrow" style="display: none">
+ <td colspan=5>
+ <table border=1>
+ <tr>
+ <th>Costas alpha</th>
+ <td><input type=text name="costas-alpha" value="0.04"></td>
+ </tr>
+ <tr>
+ <th>number of demods</th>
+ <td><input type=text name="logfile-workers" value="None"></td>
+ </tr>
+ <tr>
+ <th>spectrum decimation</th>
+ <td><input type=text name="decim-amt" value="1"></td>
+ </tr>
+ <tr>
+ <th>Gardner gain</th>
+ <td><input type=text name="gain-mu" value="0.025"></td>
+ </tr>
+ <tr>
+ <th>ifile seek</th>
+ <td><input type=text name="seek" value="0"></td>
+ </tr>
+ <tr>
+ <th>complex file input</th>
+ <td><input type=text name="ifile" value="None"></td>
+ </tr>
+ <tr>
+ <th>antenna</th>
+ <td><input type=text name="antenna" value=""></td>
+ </tr>
+ <tr>
+ <th>USRP offset / audio IF</th>
+ <td><input type=text name="calibration" value="0.0"></td>
+ </tr>
+ <tr>
+ <th>symbol dump file</th>
+ <td><input type=text name="raw-symbols" value="None"></td>
+ </tr>
+ <tr>
+ <th>audio output dev</th>
+ <td><input type=text name="audio-output" value="default"></td>
+ </tr>
+ <tr>
+ <th>input file</th>
+ <td><input type=text name="input" value="None"></td>
+ </tr>
+ <tr>
+ <th>Wireshark output</th>
+ <td><input type=checkbox name="wireshark" ></td>
+ </tr>
+ <tr>
+ <th>gain settings</th>
+ <td><input type=text name="gains" value="None"></td>
+ </tr>
+ <tr>
+ <th>USRP / audio gain</th>
+ <td><input type=text name="gain" value="None"></td>
+ </tr>
+ <tr>
+ <th>excess BW</th>
+ <td><input type=text name="excess-bw" value="0.2"></td>
+ </tr>
+ <tr>
+ <th>pcm inp device</th>
+ <td><input type=text name="audio-input" value=""></td>
+ </tr>
+ <tr>
+ <th>soundcard IF</th>
+ <td><input type=checkbox name="audio-if" ></td>
+ </tr>
+ <tr>
+ <th>tone detect algo</th>
+ <td><input type=checkbox name="tone-detect" ></td>
+ </tr>
+ <tr>
+ <th>hamlib model</th>
+ <td><input type=text name="hamlib-model" value="None"></td>
+ </tr>
+ <tr>
+ <th>direct audio inp</th>
+ <td><input type=checkbox name="audio" ></td>
+ </tr>
+ <tr>
+ <th>startup pause</th>
+ <td><input type=checkbox name="pause" ></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+ </div>
+ <p>
+ <table id="devtable" border=1>
+ <tr>
+ <th colspan=8 class="boxtitle-th"><span class="boxtitle">Devices</span></th>
+ <th colspan=2>
+ <input type="button" name="new" value="Add New" onclick="javascript:f_command(this, &quot;new&quot;);">
+ </th>
+ </tr>
+ <tr>
+ <th>Active</th>
+ <th>Name</th>
+ <th>Device Args</th>
+ <th>Frequency (MHz)</th>
+ <th>Gains</th>
+ <th>Offset</th>
+ <th>PPM</th>
+ <th>Sample Rate</th>
+ <th>&nbsp;</th>
+ </tr>
+ <tr id="devrow" class="dynrow" style="display: none">
+ <td><input type="checkbox" name="active" checked></td>
+ <td><input type="text" name="name" value="Device1"></td>
+ <td><input type="text" name="args" value="rtl"></td>
+ <td><input type="text" name="frequency" value="500.0"></td>
+ <td><input type="text" name="gains" value="lna:45"></td>
+ <td><input type="text" name="offset" value="0"></td>
+ <td><input type="text" name="ppm" value="0"></td>
+ <td><input type="text" name="rate" value="1000000"></td>
+ <td>
+ <input type="button" name="clone" value="CLONE" onclick="javascript:f_command(this, &quot;clone&quot;);">
+ <br>
+ <input type="button" name="delete" value="DELETE" onclick="javascript:f_command(this, &quot;delete&quot;);">
+ </td>
+ </tr>
+ </table>
+ <p>
+ <table id="chtable" border=1>
+ <tr>
+ <th colspan=7 class="boxtitle-th"><span class="boxtitle">Channel Details</span></th>
+ <th colspan=3>
+ <input type="button" name="new" value="Add New" onclick="javascript:f_command(this, &quot;new&quot;);">
+ </th>
+ </tr>
+ <tr>
+ <th>Active</th>
+ <th>Trunked</th>
+ <th>Name</th>
+ <th>Frequency (MHz)</th>
+ <th>Demod Type</th>
+ <th>Filter Type</th>
+ <th>Plot Type(s)</th>
+ <th>Destination</th>
+ <th>IF Rate</th>
+ <th>&alpha;</th>
+ <th>&nbsp;</th>
+ </tr>
+ <tr id="chrow" class="dynrow" style="display: none">
+ <td><input type="checkbox" name="active" checked></td>
+ <td><input type="checkbox" name="trunked" onchange="javascript:f_trunked(this)"></td>
+ <td><input type="text" name="name" value="Channel1"></td>
+ <td><input type="text" name="frequency" value="500.0"></td>
+ <td>
+ <select name="demod_type">
+ <option value="cqpsk">CQPSK</option>
+ <option value="fsk4">FSK4</option>
+ </select>
+ </td>
+ <td>
+ <select name="filter_type">
+ <option value="rc">RC (P25)</option>
+ <option value="rrc">RRC (YSF/DMR)</option>
+ <option value="gmsk">GMSK</option>
+ </select>
+ </td>
+ <td>
+ <select name="plot" multiple size=1>
+ <option value="None" selected>None</option>
+ <option value="constellation">Constellation</option>
+ <option value="symbol">Symbol</option>
+ <option value="fft">FFT</option>
+ <option value="datascope">Datascope</option>
+ </select>
+ </td>
+ <td><input type="text" name="destination" value="udp://127.0.0.1:23456"></td>
+ <td><input type="text" name="if_rate" value="24000"></td>
+ <td><input type="text" name="excess_bw" value="0"></td>
+ <td>
+ <input type="button" name="clone" value="CLONE" onclick="javascript:f_command(this, &quot;clone&quot;);">
+ <br>
+ <input type="button" name="delete" value="DELETE" onclick="javascript:f_command(this, &quot;delete&quot;);">
+ </td>
+ </tr>
+ <tr id="trrow" class="dynrow" style="display: none">
+ <td colspan=3>&nbsp;</td>
+ <td colspan=6>
+ <div>
+ <table class="trtable" border=1>
+ <tr>
+ <th colspan=2 class="boxtitle-th"><span class="boxtitle">Trunking Info</span></th>
+ <th>NAC</th>
+ <th>P2 TDMA</th>
+ <th>CC Freq's</th>
+ <th>White List</th>
+ <th>Black List</th>
+ <th>TGID Tags</th>
+ </tr>
+ <tr class="trunk-info">
+ <td colspan=2>&nbsp;</td>
+ <td><input type="text" name="nac" value="None"></td>
+ <td><input type="checkbox" name="phase2_tdma"></td>
+ <td><input type="text" name="cclist" value="0"></td>
+ <td><input type="text" name="whitelist" value="None"></td>
+ <td><input type="text" name="blacklist" value="None"></td>
+ <td><input type="button" name="tgid-tags" value="Show" onclick="javascript:f_tags(this);"></td>
+ </tr>
+ </table>
+ <table class="tgtable" border=1 style="display: none">
+ <tr>
+ <th colspan=2 class="boxtitle-th"><span class="boxtitle">Tags</span></th>
+ <th>TG ID</th>
+ <th>TG Text</th>
+ <th colspan=2>&nbsp;</th>
+ <th>
+ <input type=button name="add_tag" value="New" onclick="javascript:f_command(this, &quot;new&quot;);"
+ </th>
+ </tr>
+ <tr class="tgrow" style="display: none">
+ <td colspan=2>&nbsp;</td>
+ <td><input type="text" name="tg_id" value="None"></td>
+ <td><input type="text" name="tg_tag" value=""> </td>
+ <td colspan=3>&nbsp;</td>
+ </tr>
+ </table>
+ </div>
+ </td>
+ <td>&nbsp;</td>
+ </tr>
+ </table>
+ </div>
+ </form>
+ </div>
+
+
+
+ </div> <!-- end hide settings -->
+ </div> <!-- END FIRST COLUMN -->
+ <div class="column"> <!-- START SECOND COLUMN -->
+
+ <!-- end div_settings -->
+ <div id="div_rx" style="display: none; border: 0px solid black;">&nbsp; </div>
+ <!-- end div_rx -->
+ <div id="div_logs" style="display: none;">
+ <div id="log_container_1">
+ <div class="historyLabel">
+ <a href="#" onclick="this.blur(); openTable('callHistory', this)" id="Call&nbsp;History" class="label" style="text-decoration: none;"> Call History &nbsp;&nbsp;&nbsp;<img src="search.png" width="13" height="13" title="Search"></a>
+ &nbsp;<span id="ch-count">-</span>
+ <span title="Expand / Retract" class="btnExp hlabel" onclick="this.blur(); divExpand('div_callHistory')"> &#x25BC; </span>
+ </div>
+ <div id="div_callHistory" class="log" style="border: 1px solid black; display: block; width:730px; height:301px; overflow-y: scroll;">
+ <table id="callHistory" class="history">
+ <thead>
+ <tr>
+ <th>Time</th>
+ <th>Sys</th>
+ <th>Svc</th>
+ <th colspan="2">Talkgroup</th>
+ <th colspan="2">Source</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <br>
+ </div>
+ <!-- end div log container 1 -->
+ <!-- <br> -->
+ <div id="log_container_2">
+ <!-- Search icon: &#x1F50E; can use this instead of an image for the search box -->
+ <div class="historyLabel">
+ <a href="#" onclick="this.blur(); openTable('history', this)" id="Events" class="label" style="text-decoration: none;">Events &nbsp;&nbsp;&nbsp;<img src="search.png" width="13" height="13" title="Search"></a>
+ &nbsp;<span id="eh-count">-</span>
+ <span title="Expand / Retract" class="btnExp hlabel" onclick="this.blur(); divExpand('div_history')"> &#x25BC; </span>
+ </div>
+ <div id="div_history" class="log" style="border: 1px solid black; display: block; width:730px; height:301px; overflow-y: scroll;">
+ <table id="history" class="history">
+ <thead>
+ <tr>
+ <th>Time </th>
+ <th>Type</th>
+ <th colspan="2">Source</th>
+ <th colspan="2">Event</th>
+ <th colspan="2">Target</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <br>
+ <div id="error_tracking" style="display: none;">
+ <div class="historyLabel">
+ <a href="#" onclick="this.blur(); openTable('errors', this)" id="Errors" class="label" style="text-decoration: none;">Error Tracking &nbsp;&nbsp;&nbsp;<img src="search.png" width="13" height="13" title="Search"></a>
+ <span title="Expand / Retract" class="btnExp hlabel" onclick="this.blur(); divExpand('div_errors')"> &#x25BC; </span>
+ </div>
+ <div id="div_errors" class="log" style="border: 1px solid black; display: block; width:730px; height:301px; overflow-y: scroll;">
+ <table id="errors" class="history">
+ <thead>
+ <tr>
+ <th>Time </th>
+ <th>Device</th>
+ <th>Name</th>
+ <th>Error Band</th>
+ <th>Freq Corr </th>
+ <th>Freq Error</th>
+ <th>Tune Error</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ <td>&nbsp; </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <!-- end div log container 2 -->
+ </div>
+ <!-- end div_logs -->
+ </div> <!-- END SECOND COLUMN -->
+ </div> <!-- END OF 2 COLUMN LAYOUT -->
+ </body>
+</html> \ No newline at end of file
diff --git a/op25/gr-op25_repeater/www/www-static/jquery.alerts.css b/op25/gr-op25_repeater/www/www-static/jquery.alerts.css
new file mode 100644
index 0000000..d75986f
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/jquery.alerts.css
@@ -0,0 +1,70 @@
+/* Custom dialog styles */
+#popup_title {
+ font-size: 14px;
+ font-weight: bold;
+ text-align: center;
+ line-height: 1.75em;
+ color: #FFFFFF;
+ background: #006699;
+ border: solid 1px #006699;
+ border-bottom: solid 1px #006699;
+ cursor: default;
+ padding: 0em;
+ margin: 0em;
+}
+
+#popup_container {
+ font-family: AntipastoRegular, sans-serif;
+ font-size: 14px;
+ min-width: 300px; /* Dialog will be no smaller than this */
+ max-width: 600px; /* Dialog will wrap after this width */
+ background: #FFFFFF;
+ border: solid 5px #006699;
+ color: #000000;
+ -moz-border-radius: 5px;
+ -webkit-border-radius: 5px;
+ border-radius: 5px;
+}
+
+#popup_content {
+ /*background: 16px 16px no-repeat url(images/info.gif);*/
+ padding: 1em 1.75em;
+ margin: 0em;
+}
+
+/*
+#popup_content.alert {
+ background-image: url(images/info.gif);
+}
+
+#popup_content.confirm {
+ background-image: url(images/important.gif);
+}
+
+#popup_content.prompt {
+ background-image: url(images/help.gif);
+}
+*/
+
+#popup_message {
+ /*padding-left: 10px;*/
+ margin:0px auto;
+}
+
+#popup_panel {
+ text-align: center;
+ margin: 1em 0em 0em 1em;
+}
+
+#popup_prompt {
+ margin: .5em 0em;
+}
+
+
+#popup_container INPUT[type='button'] {
+ width: 100px;
+ height: 30px;
+ border: outset 2px #006699;
+ color: #FFFFFF;
+ background: #006699;
+}
diff --git a/op25/gr-op25_repeater/www/www-static/jquery.alerts.js b/op25/gr-op25_repeater/www/www-static/jquery.alerts.js
new file mode 100644
index 0000000..332980a
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/jquery.alerts.js
@@ -0,0 +1,268 @@
+// jQuery Alert Dialogs Plugin
+//
+// Version 2.0
+//
+// Cory S.N. LaViska
+// A Beautiful Site (http://abeautifulsite.net/)
+// 14 May 2009
+//
+// Visit http://abeautifulsite.net/notebook/87 for more information
+//
+// Usage:
+// jLoad( message, [title, callback] )
+// jAlert( message, [title, callback] )
+// jConfirm( message, [title, callback] )
+// jPrompt( message, [value, title, callback] )
+//
+// History:
+//
+// 1.00 - Released (29 December 2008)
+// 1.01 - Fixed bug where unbinding would destroy all resize events
+// 2.0 - Released (01 April 2015)
+//
+// License:
+//
+// This plugin is dual-licensed under the GNU General Public License and the MIT License and
+// is copyright 2008 A Beautiful Site, LLC.
+//
+(function($) {
+
+ $.alerts = {
+
+ // These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
+
+ verticalOffset: -75, // vertical offset of the dialog from center screen, in pixels
+ horizontalOffset: 0, // horizontal offset of the dialog from center screen, in pixels/
+ repositionOnResize: true, // re-centers the dialog on window resize
+ overlayOpacity: .01, // transparency level of overlay
+ overlayColor: '#FFF', // base color of overlay
+ draggable: true, // make the dialogs draggable (requires UI Draggables plugin)
+ okButton: '&nbsp;OK&nbsp;', // text for the OK button
+ cancelButton: '&nbsp;Cancel&nbsp;', // text for the Cancel button
+ dialogClass: null, // if specified, this class will be applied to all dialogs
+
+ // Public methods
+
+ alert: function(message, title, callback) {
+ if( title == null ) title = 'Alert';
+ $.alerts._show(title, message, null, 'alert', function(result) {
+ if( callback ) callback(result);
+ });
+ },
+
+ confirm: function(message, title, callback) {
+ if( title == null ) title = 'Confirm';
+ $.alerts._show(title, message, null, 'confirm', function(result) {
+ if( callback ) callback(result);
+ });
+ },
+
+ prompt: function(message, value, title, callback) {
+ if( title == null ) title = 'Prompt';
+ $.alerts._show(title, message, value, 'prompt', function(result) {
+ if( callback ) callback(result);
+ });
+ },
+
+ load: function(message, title, callback) {
+ if( title == null ) title = 'Load';
+ $.alerts._show(title, message, null, 'load', function(result) {
+ if( callback ) callback(result);
+ });
+ },
+
+ // Private methods
+
+ _show: function(title, msg, value, type, callback) {
+
+ $.alerts._hide();
+ $.alerts._overlay('show');
+
+ $("BODY").append(
+ '<div id="popup_container">' +
+ '<h1 id="popup_title"></h1>' +
+ '<div id="popup_content">' +
+ '<div id="popup_message"></div>' +
+ '</div>' +
+ '</div>');
+
+ if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
+
+ // IE6 Fix
+ //var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';
+ var pos = 'fixed';
+
+ $("#popup_container").css({
+ position: pos,
+ zIndex: 99999,
+ padding: 0,
+ margin: 0
+ });
+
+ $("#popup_title").text(title);
+ $("#popup_content").addClass(type);
+ $("#popup_message").text(msg);
+ $("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
+
+ $("#popup_container").css({
+ minWidth: $("#popup_container").outerWidth(),
+ maxWidth: $("#popup_container").outerWidth()
+ });
+
+ $.alerts._reposition();
+ $.alerts._maintainPosition(true);
+
+ switch( type ) {
+ case 'alert':
+ $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
+ $("#popup_ok").click( function() {
+ $.alerts._hide();
+ callback(true);
+ });
+ $("#popup_ok").focus().keypress( function(e) {
+ if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
+ });
+ break;
+ case 'confirm':
+ $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
+ $("#popup_ok").click( function() {
+ $.alerts._hide();
+ if( callback ) callback(true);
+ });
+ $("#popup_cancel").click( function() {
+ $.alerts._hide();
+ if( callback ) callback(false);
+ });
+ $("#popup_ok").focus();
+ $("#popup_ok, #popup_cancel").keypress( function(e) {
+ if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
+ if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
+ });
+ break;
+ case 'prompt':
+ $("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
+ $("#popup_prompt").width( $("#popup_message").width() );
+ $("#popup_ok").click( function() {
+ var val = $("#popup_prompt").val();
+ $.alerts._hide();
+ if( callback ) callback( val );
+ });
+ $("#popup_cancel").click( function() {
+ $.alerts._hide();
+ if( callback ) callback( null );
+ });
+ $("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
+ if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
+ if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
+ });
+ if( value ) $("#popup_prompt").val(value);
+ $("#popup_prompt").focus().select();
+ break;
+ case 'load':
+ $("#popup_message").after('<div id="popup_panel"></div>');
+ $("#popup_ok").click( function() {
+ $.alerts._hide();
+ callback(true);
+ });
+ $("#popup_ok").focus().keypress( function(e) {
+ if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
+ });
+ break;
+ }
+
+ /*
+ // Make draggable requires jQuery UI draggables
+ if( $.alerts.draggable ) {
+ try {
+ $("#popup_container").draggable({ handle: $("#popup_title") });
+ $("#popup_title").css({ cursor: 'move' });
+ } catch(e) { }
+ }
+ */
+ },
+
+ _hide: function() {
+ $("#popup_container").remove();
+ $.alerts._overlay('hide');
+ $.alerts._maintainPosition(false);
+ },
+
+ _overlay: function(status) {
+ switch( status ) {
+ case 'show':
+ $.alerts._overlay('hide');
+ $("BODY").append('<div id="popup_overlay"></div>');
+ $("#popup_overlay").css({
+ position: 'absolute',
+ zIndex: 99998,
+ top: '0px',
+ left: '0px',
+ width: '100%',
+ height: $(document).height(),
+ background: $.alerts.overlayColor,
+ opacity: $.alerts.overlayOpacity
+ });
+ break;
+ case 'hide':
+ $("#popup_overlay").remove();
+ break;
+ }
+ },
+
+ _reposition: function() {
+ var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
+ var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
+ if( top < 0 ) top = 0;
+ if( left < 0 ) left = 0;
+
+ // IE6 fix
+ //f( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
+
+ $("#popup_container").css({
+ top: top + 'px',
+ left: left + 'px'
+ });
+ $("#popup_overlay").height( $(document).height() );
+ },
+
+ _maintainPosition: function(status) {
+ if( $.alerts.repositionOnResize ) {
+ switch(status) {
+ case true:
+ $(window).bind('resize', $.alerts._reposition);
+ break;
+ case false:
+ $(window).unbind('resize', $.alerts._reposition);
+ break;
+ }
+ }
+ }
+
+ }
+
+ // Shortuct functions
+ jAlert = function(message, title, callback) {
+ $.alerts.alert(message, title, callback);
+ }
+
+ jConfirm = function(message, title, callback) {
+ $.alerts.confirm(message, title, callback);
+ };
+
+ jPrompt = function(message, value, title, callback) {
+ $.alerts.prompt(message, value, title, callback);
+ };
+
+ jLoad = function(message, title, callback) {
+ $.alerts.load(message, title, callback);
+ }
+
+})(jQuery);
+
+
+var HideAlert = function() {
+
+ $.alerts._hide();
+
+}
+
diff --git a/op25/gr-op25_repeater/www/www-static/jquery.js b/op25/gr-op25_repeater/www/www-static/jquery.js
new file mode 100644
index 0000000..fc6c299
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/jquery.js
@@ -0,0 +1,10881 @@
+/*!
+ * jQuery JavaScript Library v3.6.0
+ * https://jquery.com/
+ *
+ * Includes Sizzle.js
+ * https://sizzlejs.com/
+ *
+ * Copyright OpenJS Foundation and other contributors
+ * Released under the MIT license
+ * https://jquery.org/license
+ *
+ * Date: 2021-03-02T17:08Z
+ */
+( function( global, factory ) {
+
+ "use strict";
+
+ if ( typeof module === "object" && typeof module.exports === "object" ) {
+
+ // For CommonJS and CommonJS-like environments where a proper `window`
+ // is present, execute the factory and get jQuery.
+ // For environments that do not have a `window` with a `document`
+ // (such as Node.js), expose a factory as module.exports.
+ // This accentuates the need for the creation of a real `window`.
+ // e.g. var jQuery = require("jquery")(window);
+ // See ticket #14549 for more info.
+ module.exports = global.document ?
+ factory( global, true ) :
+ function( w ) {
+ if ( !w.document ) {
+ throw new Error( "jQuery requires a window with a document" );
+ }
+ return factory( w );
+ };
+ } else {
+ factory( global );
+ }
+
+// Pass this if window is not defined yet
+} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
+
+// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
+// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
+// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
+// enough that all such attempts are guarded in a try block.
+"use strict";
+
+var arr = [];
+
+var getProto = Object.getPrototypeOf;
+
+var slice = arr.slice;
+
+var flat = arr.flat ? function( array ) {
+ return arr.flat.call( array );
+} : function( array ) {
+ return arr.concat.apply( [], array );
+};
+
+
+var push = arr.push;
+
+var indexOf = arr.indexOf;
+
+var class2type = {};
+
+var toString = class2type.toString;
+
+var hasOwn = class2type.hasOwnProperty;
+
+var fnToString = hasOwn.toString;
+
+var ObjectFunctionString = fnToString.call( Object );
+
+var support = {};
+
+var isFunction = function isFunction( obj ) {
+
+ // Support: Chrome <=57, Firefox <=52
+ // In some browsers, typeof returns "function" for HTML <object> elements
+ // (i.e., `typeof document.createElement( "object" ) === "function"`).
+ // We don't want to classify *any* DOM node as a function.
+ // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
+ // Plus for old WebKit, typeof returns "function" for HTML collections
+ // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
+ return typeof obj === "function" && typeof obj.nodeType !== "number" &&
+ typeof obj.item !== "function";
+ };
+
+
+var isWindow = function isWindow( obj ) {
+ return obj != null && obj === obj.window;
+ };
+
+
+var document = window.document;
+
+
+
+ var preservedScriptAttributes = {
+ type: true,
+ src: true,
+ nonce: true,
+ noModule: true
+ };
+
+ function DOMEval( code, node, doc ) {
+ doc = doc || document;
+
+ var i, val,
+ script = doc.createElement( "script" );
+
+ script.text = code;
+ if ( node ) {
+ for ( i in preservedScriptAttributes ) {
+
+ // Support: Firefox 64+, Edge 18+
+ // Some browsers don't support the "nonce" property on scripts.
+ // On the other hand, just using `getAttribute` is not enough as
+ // the `nonce` attribute is reset to an empty string whenever it
+ // becomes browsing-context connected.
+ // See https://github.com/whatwg/html/issues/2369
+ // See https://html.spec.whatwg.org/#nonce-attributes
+ // The `node.getAttribute` check was added for the sake of
+ // `jQuery.globalEval` so that it can fake a nonce-containing node
+ // via an object.
+ val = node[ i ] || node.getAttribute && node.getAttribute( i );
+ if ( val ) {
+ script.setAttribute( i, val );
+ }
+ }
+ }
+ doc.head.appendChild( script ).parentNode.removeChild( script );
+ }
+
+
+function toType( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+
+ // Support: Android <=2.3 only (functionish RegExp)
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call( obj ) ] || "object" :
+ typeof obj;
+}
+/* global Symbol */
+// Defining this global in .eslintrc.json would create a danger of using the global
+// unguarded in another place, it seems safer to define global only for this module
+
+
+
+var
+ version = "3.6.0",
+
+ // Define a local copy of jQuery
+ jQuery = function( selector, context ) {
+
+ // The jQuery object is actually just the init constructor 'enhanced'
+ // Need init if jQuery is called (just allow error to be thrown if not included)
+ return new jQuery.fn.init( selector, context );
+ };
+
+jQuery.fn = jQuery.prototype = {
+
+ // The current version of jQuery being used
+ jquery: version,
+
+ constructor: jQuery,
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ toArray: function() {
+ return slice.call( this );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+
+ // Return all the elements in a clean array
+ if ( num == null ) {
+ return slice.call( this );
+ }
+
+ // Return just the one element from the set
+ return num < 0 ? this[ num + this.length ] : this[ num ];
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems ) {
+
+ // Build a new jQuery matched element set
+ var ret = jQuery.merge( this.constructor(), elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ each: function( callback ) {
+ return jQuery.each( this, callback );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map( this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ } ) );
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ) );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ even: function() {
+ return this.pushStack( jQuery.grep( this, function( _elem, i ) {
+ return ( i + 1 ) % 2;
+ } ) );
+ },
+
+ odd: function() {
+ return this.pushStack( jQuery.grep( this, function( _elem, i ) {
+ return i % 2;
+ } ) );
+ },
+
+ eq: function( i ) {
+ var len = this.length,
+ j = +i + ( i < 0 ? len : 0 );
+ return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor();
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: arr.sort,
+ splice: arr.splice
+};
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[ 0 ] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+
+ // Skip the boolean and the target
+ target = arguments[ i ] || {};
+ i++;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !isFunction( target ) ) {
+ target = {};
+ }
+
+ // Extend jQuery itself if only one argument is passed
+ if ( i === length ) {
+ target = this;
+ i--;
+ }
+
+ for ( ; i < length; i++ ) {
+
+ // Only deal with non-null/undefined values
+ if ( ( options = arguments[ i ] ) != null ) {
+
+ // Extend the base object
+ for ( name in options ) {
+ copy = options[ name ];
+
+ // Prevent Object.prototype pollution
+ // Prevent never-ending loop
+ if ( name === "__proto__" || target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
+ ( copyIsArray = Array.isArray( copy ) ) ) ) {
+ src = target[ name ];
+
+ // Ensure proper type for the source value
+ if ( copyIsArray && !Array.isArray( src ) ) {
+ clone = [];
+ } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
+ clone = {};
+ } else {
+ clone = src;
+ }
+ copyIsArray = false;
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend( {
+
+ // Unique for each copy of jQuery on the page
+ expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
+
+ // Assume jQuery is ready without the ready module
+ isReady: true,
+
+ error: function( msg ) {
+ throw new Error( msg );
+ },
+
+ noop: function() {},
+
+ isPlainObject: function( obj ) {
+ var proto, Ctor;
+
+ // Detect obvious negatives
+ // Use toString instead of jQuery.type to catch host objects
+ if ( !obj || toString.call( obj ) !== "[object Object]" ) {
+ return false;
+ }
+
+ proto = getProto( obj );
+
+ // Objects with no prototype (e.g., `Object.create( null )`) are plain
+ if ( !proto ) {
+ return true;
+ }
+
+ // Objects with prototype are plain iff they were constructed by a global Object function
+ Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
+ return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
+ },
+
+ isEmptyObject: function( obj ) {
+ var name;
+
+ for ( name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ // Evaluates a script in a provided context; falls back to the global one
+ // if not specified.
+ globalEval: function( code, options, doc ) {
+ DOMEval( code, { nonce: options && options.nonce }, doc );
+ },
+
+ each: function( obj, callback ) {
+ var length, i = 0;
+
+ if ( isArrayLike( obj ) ) {
+ length = obj.length;
+ for ( ; i < length; i++ ) {
+ if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
+ break;
+ }
+ }
+ }
+
+ return obj;
+ },
+
+ // results is for internal usage only
+ makeArray: function( arr, results ) {
+ var ret = results || [];
+
+ if ( arr != null ) {
+ if ( isArrayLike( Object( arr ) ) ) {
+ jQuery.merge( ret,
+ typeof arr === "string" ?
+ [ arr ] : arr
+ );
+ } else {
+ push.call( ret, arr );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, arr, i ) {
+ return arr == null ? -1 : indexOf.call( arr, elem, i );
+ },
+
+ // Support: Android <=4.0 only, PhantomJS 1 only
+ // push.apply(_, arraylike) throws on ancient WebKit
+ merge: function( first, second ) {
+ var len = +second.length,
+ j = 0,
+ i = first.length;
+
+ for ( ; j < len; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, invert ) {
+ var callbackInverse,
+ matches = [],
+ i = 0,
+ length = elems.length,
+ callbackExpect = !invert;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( ; i < length; i++ ) {
+ callbackInverse = !callback( elems[ i ], i );
+ if ( callbackInverse !== callbackExpect ) {
+ matches.push( elems[ i ] );
+ }
+ }
+
+ return matches;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var length, value,
+ i = 0,
+ ret = [];
+
+ // Go through the array, translating each of the items to their new values
+ if ( isArrayLike( elems ) ) {
+ length = elems.length;
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( i in elems ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return flat( ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // jQuery.support is not used in Core but other projects attach their
+ // properties to it so it needs to exist.
+ support: support
+} );
+
+if ( typeof Symbol === "function" ) {
+ jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
+}
+
+// Populate the class2type map
+jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
+ function( _i, name ) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+ } );
+
+function isArrayLike( obj ) {
+
+ // Support: real iOS 8.2 only (not reproducible in simulator)
+ // `in` check used to prevent JIT error (gh-2145)
+ // hasOwn isn't used here due to false negatives
+ // regarding Nodelist length in IE
+ var length = !!obj && "length" in obj && obj.length,
+ type = toType( obj );
+
+ if ( isFunction( obj ) || isWindow( obj ) ) {
+ return false;
+ }
+
+ return type === "array" || length === 0 ||
+ typeof length === "number" && length > 0 && ( length - 1 ) in obj;
+}
+var Sizzle =
+/*!
+ * Sizzle CSS Selector Engine v2.3.6
+ * https://sizzlejs.com/
+ *
+ * Copyright JS Foundation and other contributors
+ * Released under the MIT license
+ * https://js.foundation/
+ *
+ * Date: 2021-02-16
+ */
+( function( window ) {
+var i,
+ support,
+ Expr,
+ getText,
+ isXML,
+ tokenize,
+ compile,
+ select,
+ outermostContext,
+ sortInput,
+ hasDuplicate,
+
+ // Local document vars
+ setDocument,
+ document,
+ docElem,
+ documentIsHTML,
+ rbuggyQSA,
+ rbuggyMatches,
+ matches,
+ contains,
+
+ // Instance-specific data
+ expando = "sizzle" + 1 * new Date(),
+ preferredDoc = window.document,
+ dirruns = 0,
+ done = 0,
+ classCache = createCache(),
+ tokenCache = createCache(),
+ compilerCache = createCache(),
+ nonnativeSelectorCache = createCache(),
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ }
+ return 0;
+ },
+
+ // Instance methods
+ hasOwn = ( {} ).hasOwnProperty,
+ arr = [],
+ pop = arr.pop,
+ pushNative = arr.push,
+ push = arr.push,
+ slice = arr.slice,
+
+ // Use a stripped-down indexOf as it's faster than native
+ // https://jsperf.com/thor-indexof-vs-for/5
+ indexOf = function( list, elem ) {
+ var i = 0,
+ len = list.length;
+ for ( ; i < len; i++ ) {
+ if ( list[ i ] === elem ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" +
+ "ismap|loop|multiple|open|readonly|required|scoped",
+
+ // Regular expressions
+
+ // http://www.w3.org/TR/css3-selectors/#whitespace
+ whitespace = "[\\x20\\t\\r\\n\\f]",
+
+ // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
+ identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
+ "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",
+
+ // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
+ attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
+
+ // Operator (capture 2)
+ "*([*^$|!~]?=)" + whitespace +
+
+ // "Attribute values must be CSS identifiers [capture 5]
+ // or strings [capture 3 or capture 4]"
+ "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
+ whitespace + "*\\]",
+
+ pseudos = ":(" + identifier + ")(?:\\((" +
+
+ // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
+ // 1. quoted (capture 3; capture 4 or capture 5)
+ "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
+
+ // 2. simple (capture 6)
+ "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
+
+ // 3. anything else (capture 2)
+ ".*" +
+ ")\\)|)",
+
+ // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+ rwhitespace = new RegExp( whitespace + "+", "g" ),
+ rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" +
+ whitespace + "+$", "g" ),
+
+ rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+ rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace +
+ "*" ),
+ rdescend = new RegExp( whitespace + "|>" ),
+
+ rpseudo = new RegExp( pseudos ),
+ ridentifier = new RegExp( "^" + identifier + "$" ),
+
+ matchExpr = {
+ "ID": new RegExp( "^#(" + identifier + ")" ),
+ "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
+ "TAG": new RegExp( "^(" + identifier + "|[*])" ),
+ "ATTR": new RegExp( "^" + attributes ),
+ "PSEUDO": new RegExp( "^" + pseudos ),
+ "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
+ whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
+ whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
+ "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
+
+ // For use in libraries implementing .is()
+ // We use this for POS matching in `select`
+ "needsContext": new RegExp( "^" + whitespace +
+ "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
+ "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
+ },
+
+ rhtml = /HTML$/i,
+ rinputs = /^(?:input|select|textarea|button)$/i,
+ rheader = /^h\d$/i,
+
+ rnative = /^[^{]+\{\s*\[native \w/,
+
+ // Easily-parseable/retrievable ID or TAG or CLASS selectors
+ rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+ rsibling = /[+~]/,
+
+ // CSS escapes
+ // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+ runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),
+ funescape = function( escape, nonHex ) {
+ var high = "0x" + escape.slice( 1 ) - 0x10000;
+
+ return nonHex ?
+
+ // Strip the backslash prefix from a non-hex escape sequence
+ nonHex :
+
+ // Replace a hexadecimal escape sequence with the encoded Unicode code point
+ // Support: IE <=11+
+ // For values outside the Basic Multilingual Plane (BMP), manually construct a
+ // surrogate pair
+ high < 0 ?
+ String.fromCharCode( high + 0x10000 ) :
+ String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+ },
+
+ // CSS string/identifier serialization
+ // https://drafts.csswg.org/cssom/#common-serializing-idioms
+ rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
+ fcssescape = function( ch, asCodePoint ) {
+ if ( asCodePoint ) {
+
+ // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
+ if ( ch === "\0" ) {
+ return "\uFFFD";
+ }
+
+ // Control characters and (dependent upon position) numbers get escaped as code points
+ return ch.slice( 0, -1 ) + "\\" +
+ ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
+ }
+
+ // Other potentially-special ASCII characters get backslash-escaped
+ return "\\" + ch;
+ },
+
+ // Used for iframes
+ // See setDocument()
+ // Removing the function wrapper causes a "Permission Denied"
+ // error in IE
+ unloadHandler = function() {
+ setDocument();
+ },
+
+ inDisabledFieldset = addCombinator(
+ function( elem ) {
+ return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
+ },
+ { dir: "parentNode", next: "legend" }
+ );
+
+// Optimize for push.apply( _, NodeList )
+try {
+ push.apply(
+ ( arr = slice.call( preferredDoc.childNodes ) ),
+ preferredDoc.childNodes
+ );
+
+ // Support: Android<4.0
+ // Detect silently failing push.apply
+ // eslint-disable-next-line no-unused-expressions
+ arr[ preferredDoc.childNodes.length ].nodeType;
+} catch ( e ) {
+ push = { apply: arr.length ?
+
+ // Leverage slice if possible
+ function( target, els ) {
+ pushNative.apply( target, slice.call( els ) );
+ } :
+
+ // Support: IE<9
+ // Otherwise append directly
+ function( target, els ) {
+ var j = target.length,
+ i = 0;
+
+ // Can't trust NodeList.length
+ while ( ( target[ j++ ] = els[ i++ ] ) ) {}
+ target.length = j - 1;
+ }
+ };
+}
+
+function Sizzle( selector, context, results, seed ) {
+ var m, i, elem, nid, match, groups, newSelector,
+ newContext = context && context.ownerDocument,
+
+ // nodeType defaults to 9, since context defaults to document
+ nodeType = context ? context.nodeType : 9;
+
+ results = results || [];
+
+ // Return early from calls with invalid selector or context
+ if ( typeof selector !== "string" || !selector ||
+ nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
+
+ return results;
+ }
+
+ // Try to shortcut find operations (as opposed to filters) in HTML documents
+ if ( !seed ) {
+ setDocument( context );
+ context = context || document;
+
+ if ( documentIsHTML ) {
+
+ // If the selector is sufficiently simple, try using a "get*By*" DOM method
+ // (excepting DocumentFragment context, where the methods don't exist)
+ if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {
+
+ // ID selector
+ if ( ( m = match[ 1 ] ) ) {
+
+ // Document context
+ if ( nodeType === 9 ) {
+ if ( ( elem = context.getElementById( m ) ) ) {
+
+ // Support: IE, Opera, Webkit
+ // TODO: identify versions
+ // getElementById can match elements by name instead of ID
+ if ( elem.id === m ) {
+ results.push( elem );
+ return results;
+ }
+ } else {
+ return results;
+ }
+
+ // Element context
+ } else {
+
+ // Support: IE, Opera, Webkit
+ // TODO: identify versions
+ // getElementById can match elements by name instead of ID
+ if ( newContext && ( elem = newContext.getElementById( m ) ) &&
+ contains( context, elem ) &&
+ elem.id === m ) {
+
+ results.push( elem );
+ return results;
+ }
+ }
+
+ // Type selector
+ } else if ( match[ 2 ] ) {
+ push.apply( results, context.getElementsByTagName( selector ) );
+ return results;
+
+ // Class selector
+ } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName &&
+ context.getElementsByClassName ) {
+
+ push.apply( results, context.getElementsByClassName( m ) );
+ return results;
+ }
+ }
+
+ // Take advantage of querySelectorAll
+ if ( support.qsa &&
+ !nonnativeSelectorCache[ selector + " " ] &&
+ ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &&
+
+ // Support: IE 8 only
+ // Exclude object elements
+ ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {
+
+ newSelector = selector;
+ newContext = context;
+
+ // qSA considers elements outside a scoping root when evaluating child or
+ // descendant combinators, which is not what we want.
+ // In such cases, we work around the behavior by prefixing every selector in the
+ // list with an ID selector referencing the scope context.
+ // The technique has to be used as well when a leading combinator is used
+ // as such selectors are not recognized by querySelectorAll.
+ // Thanks to Andrew Dupont for this technique.
+ if ( nodeType === 1 &&
+ ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) {
+
+ // Expand context for sibling selectors
+ newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
+ context;
+
+ // We can use :scope instead of the ID hack if the browser
+ // supports it & if we're not changing the context.
+ if ( newContext !== context || !support.scope ) {
+
+ // Capture the context ID, setting it first if necessary
+ if ( ( nid = context.getAttribute( "id" ) ) ) {
+ nid = nid.replace( rcssescape, fcssescape );
+ } else {
+ context.setAttribute( "id", ( nid = expando ) );
+ }
+ }
+
+ // Prefix every selector in the list
+ groups = tokenize( selector );
+ i = groups.length;
+ while ( i-- ) {
+ groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
+ toSelector( groups[ i ] );
+ }
+ newSelector = groups.join( "," );
+ }
+
+ try {
+ push.apply( results,
+ newContext.querySelectorAll( newSelector )
+ );
+ return results;
+ } catch ( qsaError ) {
+ nonnativeSelectorCache( selector, true );
+ } finally {
+ if ( nid === expando ) {
+ context.removeAttribute( "id" );
+ }
+ }
+ }
+ }
+ }
+
+ // All others
+ return select( selector.replace( rtrim, "$1" ), context, results, seed );
+}
+
+/**
+ * Create key-value caches of limited size
+ * @returns {function(string, object)} Returns the Object data after storing it on itself with
+ * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
+ * deleting the oldest entry
+ */
+function createCache() {
+ var keys = [];
+
+ function cache( key, value ) {
+
+ // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
+ if ( keys.push( key + " " ) > Expr.cacheLength ) {
+
+ // Only keep the most recent entries
+ delete cache[ keys.shift() ];
+ }
+ return ( cache[ key + " " ] = value );
+ }
+ return cache;
+}
+
+/**
+ * Mark a function for special use by Sizzle
+ * @param {Function} fn The function to mark
+ */
+function markFunction( fn ) {
+ fn[ expando ] = true;
+ return fn;
+}
+
+/**
+ * Support testing using an element
+ * @param {Function} fn Passed the created element and returns a boolean result
+ */
+function assert( fn ) {
+ var el = document.createElement( "fieldset" );
+
+ try {
+ return !!fn( el );
+ } catch ( e ) {
+ return false;
+ } finally {
+
+ // Remove from its parent by default
+ if ( el.parentNode ) {
+ el.parentNode.removeChild( el );
+ }
+
+ // release memory in IE
+ el = null;
+ }
+}
+
+/**
+ * Adds the same handler for all of the specified attrs
+ * @param {String} attrs Pipe-separated list of attributes
+ * @param {Function} handler The method that will be applied
+ */
+function addHandle( attrs, handler ) {
+ var arr = attrs.split( "|" ),
+ i = arr.length;
+
+ while ( i-- ) {
+ Expr.attrHandle[ arr[ i ] ] = handler;
+ }
+}
+
+/**
+ * Checks document order of two siblings
+ * @param {Element} a
+ * @param {Element} b
+ * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
+ */
+function siblingCheck( a, b ) {
+ var cur = b && a,
+ diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
+ a.sourceIndex - b.sourceIndex;
+
+ // Use IE sourceIndex if available on both nodes
+ if ( diff ) {
+ return diff;
+ }
+
+ // Check if b follows a
+ if ( cur ) {
+ while ( ( cur = cur.nextSibling ) ) {
+ if ( cur === b ) {
+ return -1;
+ }
+ }
+ }
+
+ return a ? 1 : -1;
+}
+
+/**
+ * Returns a function to use in pseudos for input types
+ * @param {String} type
+ */
+function createInputPseudo( type ) {
+ return function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === type;
+ };
+}
+
+/**
+ * Returns a function to use in pseudos for buttons
+ * @param {String} type
+ */
+function createButtonPseudo( type ) {
+ return function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return ( name === "input" || name === "button" ) && elem.type === type;
+ };
+}
+
+/**
+ * Returns a function to use in pseudos for :enabled/:disabled
+ * @param {Boolean} disabled true for :disabled; false for :enabled
+ */
+function createDisabledPseudo( disabled ) {
+
+ // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
+ return function( elem ) {
+
+ // Only certain elements can match :enabled or :disabled
+ // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
+ // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
+ if ( "form" in elem ) {
+
+ // Check for inherited disabledness on relevant non-disabled elements:
+ // * listed form-associated elements in a disabled fieldset
+ // https://html.spec.whatwg.org/multipage/forms.html#category-listed
+ // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
+ // * option elements in a disabled optgroup
+ // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
+ // All such elements have a "form" property.
+ if ( elem.parentNode && elem.disabled === false ) {
+
+ // Option elements defer to a parent optgroup if present
+ if ( "label" in elem ) {
+ if ( "label" in elem.parentNode ) {
+ return elem.parentNode.disabled === disabled;
+ } else {
+ return elem.disabled === disabled;
+ }
+ }
+
+ // Support: IE 6 - 11
+ // Use the isDisabled shortcut property to check for disabled fieldset ancestors
+ return elem.isDisabled === disabled ||
+
+ // Where there is no isDisabled, check manually
+ /* jshint -W018 */
+ elem.isDisabled !== !disabled &&
+ inDisabledFieldset( elem ) === disabled;
+ }
+
+ return elem.disabled === disabled;
+
+ // Try to winnow out elements that can't be disabled before trusting the disabled property.
+ // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
+ // even exist on them, let alone have a boolean value.
+ } else if ( "label" in elem ) {
+ return elem.disabled === disabled;
+ }
+
+ // Remaining elements are neither :enabled nor :disabled
+ return false;
+ };
+}
+
+/**
+ * Returns a function to use in pseudos for positionals
+ * @param {Function} fn
+ */
+function createPositionalPseudo( fn ) {
+ return markFunction( function( argument ) {
+ argument = +argument;
+ return markFunction( function( seed, matches ) {
+ var j,
+ matchIndexes = fn( [], seed.length, argument ),
+ i = matchIndexes.length;
+
+ // Match elements found at the specified indexes
+ while ( i-- ) {
+ if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
+ seed[ j ] = !( matches[ j ] = seed[ j ] );
+ }
+ }
+ } );
+ } );
+}
+
+/**
+ * Checks a node for validity as a Sizzle context
+ * @param {Element|Object=} context
+ * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
+ */
+function testContext( context ) {
+ return context && typeof context.getElementsByTagName !== "undefined" && context;
+}
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * Detects XML nodes
+ * @param {Element|Object} elem An element or a document
+ * @returns {Boolean} True iff elem is a non-HTML XML node
+ */
+isXML = Sizzle.isXML = function( elem ) {
+ var namespace = elem && elem.namespaceURI,
+ docElem = elem && ( elem.ownerDocument || elem ).documentElement;
+
+ // Support: IE <=8
+ // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
+ // https://bugs.jquery.com/ticket/4833
+ return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );
+};
+
+/**
+ * Sets document-related variables once based on the current document
+ * @param {Element|Object} [doc] An element or document object to use to set the document
+ * @returns {Object} Returns the current document
+ */
+setDocument = Sizzle.setDocument = function( node ) {
+ var hasCompare, subWindow,
+ doc = node ? node.ownerDocument || node : preferredDoc;
+
+ // Return early if doc is invalid or already selected
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
+ return document;
+ }
+
+ // Update global variables
+ document = doc;
+ docElem = document.documentElement;
+ documentIsHTML = !isXML( document );
+
+ // Support: IE 9 - 11+, Edge 12 - 18+
+ // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( preferredDoc != document &&
+ ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {
+
+ // Support: IE 11, Edge
+ if ( subWindow.addEventListener ) {
+ subWindow.addEventListener( "unload", unloadHandler, false );
+
+ // Support: IE 9 - 10 only
+ } else if ( subWindow.attachEvent ) {
+ subWindow.attachEvent( "onunload", unloadHandler );
+ }
+ }
+
+ // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
+ // Safari 4 - 5 only, Opera <=11.6 - 12.x only
+ // IE/Edge & older browsers don't support the :scope pseudo-class.
+ // Support: Safari 6.0 only
+ // Safari 6.0 supports :scope but it's an alias of :root there.
+ support.scope = assert( function( el ) {
+ docElem.appendChild( el ).appendChild( document.createElement( "div" ) );
+ return typeof el.querySelectorAll !== "undefined" &&
+ !el.querySelectorAll( ":scope fieldset div" ).length;
+ } );
+
+ /* Attributes
+ ---------------------------------------------------------------------- */
+
+ // Support: IE<8
+ // Verify that getAttribute really returns attributes and not properties
+ // (excepting IE8 booleans)
+ support.attributes = assert( function( el ) {
+ el.className = "i";
+ return !el.getAttribute( "className" );
+ } );
+
+ /* getElement(s)By*
+ ---------------------------------------------------------------------- */
+
+ // Check if getElementsByTagName("*") returns only elements
+ support.getElementsByTagName = assert( function( el ) {
+ el.appendChild( document.createComment( "" ) );
+ return !el.getElementsByTagName( "*" ).length;
+ } );
+
+ // Support: IE<9
+ support.getElementsByClassName = rnative.test( document.getElementsByClassName );
+
+ // Support: IE<10
+ // Check if getElementById returns elements by name
+ // The broken getElementById methods don't pick up programmatically-set names,
+ // so use a roundabout getElementsByName test
+ support.getById = assert( function( el ) {
+ docElem.appendChild( el ).id = expando;
+ return !document.getElementsByName || !document.getElementsByName( expando ).length;
+ } );
+
+ // ID filter and find
+ if ( support.getById ) {
+ Expr.filter[ "ID" ] = function( id ) {
+ var attrId = id.replace( runescape, funescape );
+ return function( elem ) {
+ return elem.getAttribute( "id" ) === attrId;
+ };
+ };
+ Expr.find[ "ID" ] = function( id, context ) {
+ if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
+ var elem = context.getElementById( id );
+ return elem ? [ elem ] : [];
+ }
+ };
+ } else {
+ Expr.filter[ "ID" ] = function( id ) {
+ var attrId = id.replace( runescape, funescape );
+ return function( elem ) {
+ var node = typeof elem.getAttributeNode !== "undefined" &&
+ elem.getAttributeNode( "id" );
+ return node && node.value === attrId;
+ };
+ };
+
+ // Support: IE 6 - 7 only
+ // getElementById is not reliable as a find shortcut
+ Expr.find[ "ID" ] = function( id, context ) {
+ if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
+ var node, i, elems,
+ elem = context.getElementById( id );
+
+ if ( elem ) {
+
+ // Verify the id attribute
+ node = elem.getAttributeNode( "id" );
+ if ( node && node.value === id ) {
+ return [ elem ];
+ }
+
+ // Fall back on getElementsByName
+ elems = context.getElementsByName( id );
+ i = 0;
+ while ( ( elem = elems[ i++ ] ) ) {
+ node = elem.getAttributeNode( "id" );
+ if ( node && node.value === id ) {
+ return [ elem ];
+ }
+ }
+ }
+
+ return [];
+ }
+ };
+ }
+
+ // Tag
+ Expr.find[ "TAG" ] = support.getElementsByTagName ?
+ function( tag, context ) {
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( tag );
+
+ // DocumentFragment nodes don't have gEBTN
+ } else if ( support.qsa ) {
+ return context.querySelectorAll( tag );
+ }
+ } :
+
+ function( tag, context ) {
+ var elem,
+ tmp = [],
+ i = 0,
+
+ // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
+ results = context.getElementsByTagName( tag );
+
+ // Filter out possible comments
+ if ( tag === "*" ) {
+ while ( ( elem = results[ i++ ] ) ) {
+ if ( elem.nodeType === 1 ) {
+ tmp.push( elem );
+ }
+ }
+
+ return tmp;
+ }
+ return results;
+ };
+
+ // Class
+ Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) {
+ if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
+ return context.getElementsByClassName( className );
+ }
+ };
+
+ /* QSA/matchesSelector
+ ---------------------------------------------------------------------- */
+
+ // QSA and matchesSelector support
+
+ // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
+ rbuggyMatches = [];
+
+ // qSa(:focus) reports false when true (Chrome 21)
+ // We allow this because of a bug in IE8/9 that throws an error
+ // whenever `document.activeElement` is accessed on an iframe
+ // So, we allow :focus to pass through QSA all the time to avoid the IE error
+ // See https://bugs.jquery.com/ticket/13378
+ rbuggyQSA = [];
+
+ if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {
+
+ // Build QSA regex
+ // Regex strategy adopted from Diego Perini
+ assert( function( el ) {
+
+ var input;
+
+ // Select is set to empty string on purpose
+ // This is to test IE's treatment of not explicitly
+ // setting a boolean content attribute,
+ // since its presence should be enough
+ // https://bugs.jquery.com/ticket/12359
+ docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
+ "<select id='" + expando + "-\r\\' msallowcapture=''>" +
+ "<option selected=''></option></select>";
+
+ // Support: IE8, Opera 11-12.16
+ // Nothing should be selected when empty strings follow ^= or $= or *=
+ // The test attribute must be unknown in Opera but "safe" for WinRT
+ // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
+ if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {
+ rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
+ }
+
+ // Support: IE8
+ // Boolean attributes and "value" are not treated correctly
+ if ( !el.querySelectorAll( "[selected]" ).length ) {
+ rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+ }
+
+ // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
+ rbuggyQSA.push( "~=" );
+ }
+
+ // Support: IE 11+, Edge 15 - 18+
+ // IE 11/Edge don't find elements on a `[name='']` query in some cases.
+ // Adding a temporary attribute to the document before the selection works
+ // around the issue.
+ // Interestingly, IE 10 & older don't seem to have the issue.
+ input = document.createElement( "input" );
+ input.setAttribute( "name", "" );
+ el.appendChild( input );
+ if ( !el.querySelectorAll( "[name='']" ).length ) {
+ rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
+ whitespace + "*(?:''|\"\")" );
+ }
+
+ // Webkit/Opera - :checked should return selected option elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ // IE8 throws error here and will not see later tests
+ if ( !el.querySelectorAll( ":checked" ).length ) {
+ rbuggyQSA.push( ":checked" );
+ }
+
+ // Support: Safari 8+, iOS 8+
+ // https://bugs.webkit.org/show_bug.cgi?id=136851
+ // In-page `selector#id sibling-combinator selector` fails
+ if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
+ rbuggyQSA.push( ".#.+[+~]" );
+ }
+
+ // Support: Firefox <=3.6 - 5 only
+ // Old Firefox doesn't throw on a badly-escaped identifier.
+ el.querySelectorAll( "\\\f" );
+ rbuggyQSA.push( "[\\r\\n\\f]" );
+ } );
+
+ assert( function( el ) {
+ el.innerHTML = "<a href='' disabled='disabled'></a>" +
+ "<select disabled='disabled'><option/></select>";
+
+ // Support: Windows 8 Native Apps
+ // The type and name attributes are restricted during .innerHTML assignment
+ var input = document.createElement( "input" );
+ input.setAttribute( "type", "hidden" );
+ el.appendChild( input ).setAttribute( "name", "D" );
+
+ // Support: IE8
+ // Enforce case-sensitivity of name attribute
+ if ( el.querySelectorAll( "[name=d]" ).length ) {
+ rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
+ }
+
+ // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
+ // IE8 throws error here and will not see later tests
+ if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {
+ rbuggyQSA.push( ":enabled", ":disabled" );
+ }
+
+ // Support: IE9-11+
+ // IE's :disabled selector does not pick up the children of disabled fieldsets
+ docElem.appendChild( el ).disabled = true;
+ if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
+ rbuggyQSA.push( ":enabled", ":disabled" );
+ }
+
+ // Support: Opera 10 - 11 only
+ // Opera 10-11 does not throw on post-comma invalid pseudos
+ el.querySelectorAll( "*,:x" );
+ rbuggyQSA.push( ",.*:" );
+ } );
+ }
+
+ if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||
+ docElem.webkitMatchesSelector ||
+ docElem.mozMatchesSelector ||
+ docElem.oMatchesSelector ||
+ docElem.msMatchesSelector ) ) ) ) {
+
+ assert( function( el ) {
+
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9)
+ support.disconnectedMatch = matches.call( el, "*" );
+
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( el, "[s!='']:x" );
+ rbuggyMatches.push( "!=", pseudos );
+ } );
+ }
+
+ rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );
+ rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) );
+
+ /* Contains
+ ---------------------------------------------------------------------- */
+ hasCompare = rnative.test( docElem.compareDocumentPosition );
+
+ // Element contains another
+ // Purposefully self-exclusive
+ // As in, an element does not contain itself
+ contains = hasCompare || rnative.test( docElem.contains ) ?
+ function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ) );
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( ( b = b.parentNode ) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ /* Sorting
+ ---------------------------------------------------------------------- */
+
+ // Document order sorting
+ sortOrder = hasCompare ?
+ function( a, b ) {
+
+ // Flag for duplicate removal
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ // Sort on method existence if only one input has compareDocumentPosition
+ var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
+ if ( compare ) {
+ return compare;
+ }
+
+ // Calculate position if both inputs belong to the same document
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
+ a.compareDocumentPosition( b ) :
+
+ // Otherwise we know they are disconnected
+ 1;
+
+ // Disconnected nodes
+ if ( compare & 1 ||
+ ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {
+
+ // Choose the first element that is related to our preferred document
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( a == document || a.ownerDocument == preferredDoc &&
+ contains( preferredDoc, a ) ) {
+ return -1;
+ }
+
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( b == document || b.ownerDocument == preferredDoc &&
+ contains( preferredDoc, b ) ) {
+ return 1;
+ }
+
+ // Maintain original order
+ return sortInput ?
+ ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
+ 0;
+ }
+
+ return compare & 4 ? -1 : 1;
+ } :
+ function( a, b ) {
+
+ // Exit early if the nodes are identical
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ var cur,
+ i = 0,
+ aup = a.parentNode,
+ bup = b.parentNode,
+ ap = [ a ],
+ bp = [ b ];
+
+ // Parentless nodes are either documents or disconnected
+ if ( !aup || !bup ) {
+
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ /* eslint-disable eqeqeq */
+ return a == document ? -1 :
+ b == document ? 1 :
+ /* eslint-enable eqeqeq */
+ aup ? -1 :
+ bup ? 1 :
+ sortInput ?
+ ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
+ 0;
+
+ // If the nodes are siblings, we can do a quick check
+ } else if ( aup === bup ) {
+ return siblingCheck( a, b );
+ }
+
+ // Otherwise we need full lists of their ancestors for comparison
+ cur = a;
+ while ( ( cur = cur.parentNode ) ) {
+ ap.unshift( cur );
+ }
+ cur = b;
+ while ( ( cur = cur.parentNode ) ) {
+ bp.unshift( cur );
+ }
+
+ // Walk down the tree looking for a discrepancy
+ while ( ap[ i ] === bp[ i ] ) {
+ i++;
+ }
+
+ return i ?
+
+ // Do a sibling check if the nodes have a common ancestor
+ siblingCheck( ap[ i ], bp[ i ] ) :
+
+ // Otherwise nodes in our document sort first
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ /* eslint-disable eqeqeq */
+ ap[ i ] == preferredDoc ? -1 :
+ bp[ i ] == preferredDoc ? 1 :
+ /* eslint-enable eqeqeq */
+ 0;
+ };
+
+ return document;
+};
+
+Sizzle.matches = function( expr, elements ) {
+ return Sizzle( expr, null, null, elements );
+};
+
+Sizzle.matchesSelector = function( elem, expr ) {
+ setDocument( elem );
+
+ if ( support.matchesSelector && documentIsHTML &&
+ !nonnativeSelectorCache[ expr + " " ] &&
+ ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
+ ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
+
+ try {
+ var ret = matches.call( elem, expr );
+
+ // IE 9's matchesSelector returns false on disconnected nodes
+ if ( ret || support.disconnectedMatch ||
+
+ // As well, disconnected nodes are said to be in a document
+ // fragment in IE 9
+ elem.document && elem.document.nodeType !== 11 ) {
+ return ret;
+ }
+ } catch ( e ) {
+ nonnativeSelectorCache( expr, true );
+ }
+ }
+
+ return Sizzle( expr, document, null, [ elem ] ).length > 0;
+};
+
+Sizzle.contains = function( context, elem ) {
+
+ // Set document vars if needed
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( ( context.ownerDocument || context ) != document ) {
+ setDocument( context );
+ }
+ return contains( context, elem );
+};
+
+Sizzle.attr = function( elem, name ) {
+
+ // Set document vars if needed
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( ( elem.ownerDocument || elem ) != document ) {
+ setDocument( elem );
+ }
+
+ var fn = Expr.attrHandle[ name.toLowerCase() ],
+
+ // Don't get fooled by Object.prototype properties (jQuery #13807)
+ val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
+ fn( elem, name, !documentIsHTML ) :
+ undefined;
+
+ return val !== undefined ?
+ val :
+ support.attributes || !documentIsHTML ?
+ elem.getAttribute( name ) :
+ ( val = elem.getAttributeNode( name ) ) && val.specified ?
+ val.value :
+ null;
+};
+
+Sizzle.escape = function( sel ) {
+ return ( sel + "" ).replace( rcssescape, fcssescape );
+};
+
+Sizzle.error = function( msg ) {
+ throw new Error( "Syntax error, unrecognized expression: " + msg );
+};
+
+/**
+ * Document sorting and removing duplicates
+ * @param {ArrayLike} results
+ */
+Sizzle.uniqueSort = function( results ) {
+ var elem,
+ duplicates = [],
+ j = 0,
+ i = 0;
+
+ // Unless we *know* we can detect duplicates, assume their presence
+ hasDuplicate = !support.detectDuplicates;
+ sortInput = !support.sortStable && results.slice( 0 );
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ while ( ( elem = results[ i++ ] ) ) {
+ if ( elem === results[ i ] ) {
+ j = duplicates.push( i );
+ }
+ }
+ while ( j-- ) {
+ results.splice( duplicates[ j ], 1 );
+ }
+ }
+
+ // Clear input after sorting to release objects
+ // See https://github.com/jquery/sizzle/pull/225
+ sortInput = null;
+
+ return results;
+};
+
+/**
+ * Utility function for retrieving the text value of an array of DOM nodes
+ * @param {Array|Element} elem
+ */
+getText = Sizzle.getText = function( elem ) {
+ var node,
+ ret = "",
+ i = 0,
+ nodeType = elem.nodeType;
+
+ if ( !nodeType ) {
+
+ // If no nodeType, this is expected to be an array
+ while ( ( node = elem[ i++ ] ) ) {
+
+ // Do not traverse comment nodes
+ ret += getText( node );
+ }
+ } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+
+ // Use textContent for elements
+ // innerText usage removed for consistency of new lines (jQuery #11153)
+ if ( typeof elem.textContent === "string" ) {
+ return elem.textContent;
+ } else {
+
+ // Traverse its children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ ret += getText( elem );
+ }
+ }
+ } else if ( nodeType === 3 || nodeType === 4 ) {
+ return elem.nodeValue;
+ }
+
+ // Do not include comment or processing instruction nodes
+
+ return ret;
+};
+
+Expr = Sizzle.selectors = {
+
+ // Can be adjusted by the user
+ cacheLength: 50,
+
+ createPseudo: markFunction,
+
+ match: matchExpr,
+
+ attrHandle: {},
+
+ find: {},
+
+ relative: {
+ ">": { dir: "parentNode", first: true },
+ " ": { dir: "parentNode" },
+ "+": { dir: "previousSibling", first: true },
+ "~": { dir: "previousSibling" }
+ },
+
+ preFilter: {
+ "ATTR": function( match ) {
+ match[ 1 ] = match[ 1 ].replace( runescape, funescape );
+
+ // Move the given value to match[3] whether quoted or unquoted
+ match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||
+ match[ 5 ] || "" ).replace( runescape, funescape );
+
+ if ( match[ 2 ] === "~=" ) {
+ match[ 3 ] = " " + match[ 3 ] + " ";
+ }
+
+ return match.slice( 0, 4 );
+ },
+
+ "CHILD": function( match ) {
+
+ /* matches from matchExpr["CHILD"]
+ 1 type (only|nth|...)
+ 2 what (child|of-type)
+ 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
+ 4 xn-component of xn+y argument ([+-]?\d*n|)
+ 5 sign of xn-component
+ 6 x of xn-component
+ 7 sign of y-component
+ 8 y of y-component
+ */
+ match[ 1 ] = match[ 1 ].toLowerCase();
+
+ if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {
+
+ // nth-* requires argument
+ if ( !match[ 3 ] ) {
+ Sizzle.error( match[ 0 ] );
+ }
+
+ // numeric x and y parameters for Expr.filter.CHILD
+ // remember that false/true cast respectively to 0/1
+ match[ 4 ] = +( match[ 4 ] ?
+ match[ 5 ] + ( match[ 6 ] || 1 ) :
+ 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );
+ match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );
+
+ // other types prohibit arguments
+ } else if ( match[ 3 ] ) {
+ Sizzle.error( match[ 0 ] );
+ }
+
+ return match;
+ },
+
+ "PSEUDO": function( match ) {
+ var excess,
+ unquoted = !match[ 6 ] && match[ 2 ];
+
+ if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {
+ return null;
+ }
+
+ // Accept quoted arguments as-is
+ if ( match[ 3 ] ) {
+ match[ 2 ] = match[ 4 ] || match[ 5 ] || "";
+
+ // Strip excess characters from unquoted arguments
+ } else if ( unquoted && rpseudo.test( unquoted ) &&
+
+ // Get excess from tokenize (recursively)
+ ( excess = tokenize( unquoted, true ) ) &&
+
+ // advance to the next closing parenthesis
+ ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {
+
+ // excess is a negative index
+ match[ 0 ] = match[ 0 ].slice( 0, excess );
+ match[ 2 ] = unquoted.slice( 0, excess );
+ }
+
+ // Return only captures needed by the pseudo filter method (type and argument)
+ return match.slice( 0, 3 );
+ }
+ },
+
+ filter: {
+
+ "TAG": function( nodeNameSelector ) {
+ var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
+ return nodeNameSelector === "*" ?
+ function() {
+ return true;
+ } :
+ function( elem ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
+ };
+ },
+
+ "CLASS": function( className ) {
+ var pattern = classCache[ className + " " ];
+
+ return pattern ||
+ ( pattern = new RegExp( "(^|" + whitespace +
+ ")" + className + "(" + whitespace + "|$)" ) ) && classCache(
+ className, function( elem ) {
+ return pattern.test(
+ typeof elem.className === "string" && elem.className ||
+ typeof elem.getAttribute !== "undefined" &&
+ elem.getAttribute( "class" ) ||
+ ""
+ );
+ } );
+ },
+
+ "ATTR": function( name, operator, check ) {
+ return function( elem ) {
+ var result = Sizzle.attr( elem, name );
+
+ if ( result == null ) {
+ return operator === "!=";
+ }
+ if ( !operator ) {
+ return true;
+ }
+
+ result += "";
+
+ /* eslint-disable max-len */
+
+ return operator === "=" ? result === check :
+ operator === "!=" ? result !== check :
+ operator === "^=" ? check && result.indexOf( check ) === 0 :
+ operator === "*=" ? check && result.indexOf( check ) > -1 :
+ operator === "$=" ? check && result.slice( -check.length ) === check :
+ operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
+ operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
+ false;
+ /* eslint-enable max-len */
+
+ };
+ },
+
+ "CHILD": function( type, what, _argument, first, last ) {
+ var simple = type.slice( 0, 3 ) !== "nth",
+ forward = type.slice( -4 ) !== "last",
+ ofType = what === "of-type";
+
+ return first === 1 && last === 0 ?
+
+ // Shortcut for :nth-*(n)
+ function( elem ) {
+ return !!elem.parentNode;
+ } :
+
+ function( elem, _context, xml ) {
+ var cache, uniqueCache, outerCache, node, nodeIndex, start,
+ dir = simple !== forward ? "nextSibling" : "previousSibling",
+ parent = elem.parentNode,
+ name = ofType && elem.nodeName.toLowerCase(),
+ useCache = !xml && !ofType,
+ diff = false;
+
+ if ( parent ) {
+
+ // :(first|last|only)-(child|of-type)
+ if ( simple ) {
+ while ( dir ) {
+ node = elem;
+ while ( ( node = node[ dir ] ) ) {
+ if ( ofType ?
+ node.nodeName.toLowerCase() === name :
+ node.nodeType === 1 ) {
+
+ return false;
+ }
+ }
+
+ // Reverse direction for :only-* (if we haven't yet done so)
+ start = dir = type === "only" && !start && "nextSibling";
+ }
+ return true;
+ }
+
+ start = [ forward ? parent.firstChild : parent.lastChild ];
+
+ // non-xml :nth-child(...) stores cache data on `parent`
+ if ( forward && useCache ) {
+
+ // Seek `elem` from a previously-cached index
+
+ // ...in a gzip-friendly way
+ node = parent;
+ outerCache = node[ expando ] || ( node[ expando ] = {} );
+
+ // Support: IE <9 only
+ // Defend against cloned attroperties (jQuery gh-1709)
+ uniqueCache = outerCache[ node.uniqueID ] ||
+ ( outerCache[ node.uniqueID ] = {} );
+
+ cache = uniqueCache[ type ] || [];
+ nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
+ diff = nodeIndex && cache[ 2 ];
+ node = nodeIndex && parent.childNodes[ nodeIndex ];
+
+ while ( ( node = ++nodeIndex && node && node[ dir ] ||
+
+ // Fallback to seeking `elem` from the start
+ ( diff = nodeIndex = 0 ) || start.pop() ) ) {
+
+ // When found, cache indexes on `parent` and break
+ if ( node.nodeType === 1 && ++diff && node === elem ) {
+ uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
+ break;
+ }
+ }
+
+ } else {
+
+ // Use previously-cached element index if available
+ if ( useCache ) {
+
+ // ...in a gzip-friendly way
+ node = elem;
+ outerCache = node[ expando ] || ( node[ expando ] = {} );
+
+ // Support: IE <9 only
+ // Defend against cloned attroperties (jQuery gh-1709)
+ uniqueCache = outerCache[ node.uniqueID ] ||
+ ( outerCache[ node.uniqueID ] = {} );
+
+ cache = uniqueCache[ type ] || [];
+ nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
+ diff = nodeIndex;
+ }
+
+ // xml :nth-child(...)
+ // or :nth-last-child(...) or :nth(-last)?-of-type(...)
+ if ( diff === false ) {
+
+ // Use the same loop as above to seek `elem` from the start
+ while ( ( node = ++nodeIndex && node && node[ dir ] ||
+ ( diff = nodeIndex = 0 ) || start.pop() ) ) {
+
+ if ( ( ofType ?
+ node.nodeName.toLowerCase() === name :
+ node.nodeType === 1 ) &&
+ ++diff ) {
+
+ // Cache the index of each encountered element
+ if ( useCache ) {
+ outerCache = node[ expando ] ||
+ ( node[ expando ] = {} );
+
+ // Support: IE <9 only
+ // Defend against cloned attroperties (jQuery gh-1709)
+ uniqueCache = outerCache[ node.uniqueID ] ||
+ ( outerCache[ node.uniqueID ] = {} );
+
+ uniqueCache[ type ] = [ dirruns, diff ];
+ }
+
+ if ( node === elem ) {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // Incorporate the offset, then check against cycle size
+ diff -= last;
+ return diff === first || ( diff % first === 0 && diff / first >= 0 );
+ }
+ };
+ },
+
+ "PSEUDO": function( pseudo, argument ) {
+
+ // pseudo-class names are case-insensitive
+ // http://www.w3.org/TR/selectors/#pseudo-classes
+ // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
+ // Remember that setFilters inherits from pseudos
+ var args,
+ fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
+ Sizzle.error( "unsupported pseudo: " + pseudo );
+
+ // The user may use createPseudo to indicate that
+ // arguments are needed to create the filter function
+ // just as Sizzle does
+ if ( fn[ expando ] ) {
+ return fn( argument );
+ }
+
+ // But maintain support for old signatures
+ if ( fn.length > 1 ) {
+ args = [ pseudo, pseudo, "", argument ];
+ return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
+ markFunction( function( seed, matches ) {
+ var idx,
+ matched = fn( seed, argument ),
+ i = matched.length;
+ while ( i-- ) {
+ idx = indexOf( seed, matched[ i ] );
+ seed[ idx ] = !( matches[ idx ] = matched[ i ] );
+ }
+ } ) :
+ function( elem ) {
+ return fn( elem, 0, args );
+ };
+ }
+
+ return fn;
+ }
+ },
+
+ pseudos: {
+
+ // Potentially complex pseudos
+ "not": markFunction( function( selector ) {
+
+ // Trim the selector passed to compile
+ // to avoid treating leading and trailing
+ // spaces as combinators
+ var input = [],
+ results = [],
+ matcher = compile( selector.replace( rtrim, "$1" ) );
+
+ return matcher[ expando ] ?
+ markFunction( function( seed, matches, _context, xml ) {
+ var elem,
+ unmatched = matcher( seed, null, xml, [] ),
+ i = seed.length;
+
+ // Match elements unmatched by `matcher`
+ while ( i-- ) {
+ if ( ( elem = unmatched[ i ] ) ) {
+ seed[ i ] = !( matches[ i ] = elem );
+ }
+ }
+ } ) :
+ function( elem, _context, xml ) {
+ input[ 0 ] = elem;
+ matcher( input, null, xml, results );
+
+ // Don't keep the element (issue #299)
+ input[ 0 ] = null;
+ return !results.pop();
+ };
+ } ),
+
+ "has": markFunction( function( selector ) {
+ return function( elem ) {
+ return Sizzle( selector, elem ).length > 0;
+ };
+ } ),
+
+ "contains": markFunction( function( text ) {
+ text = text.replace( runescape, funescape );
+ return function( elem ) {
+ return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1;
+ };
+ } ),
+
+ // "Whether an element is represented by a :lang() selector
+ // is based solely on the element's language value
+ // being equal to the identifier C,
+ // or beginning with the identifier C immediately followed by "-".
+ // The matching of C against the element's language value is performed case-insensitively.
+ // The identifier C does not have to be a valid language name."
+ // http://www.w3.org/TR/selectors/#lang-pseudo
+ "lang": markFunction( function( lang ) {
+
+ // lang value must be a valid identifier
+ if ( !ridentifier.test( lang || "" ) ) {
+ Sizzle.error( "unsupported lang: " + lang );
+ }
+ lang = lang.replace( runescape, funescape ).toLowerCase();
+ return function( elem ) {
+ var elemLang;
+ do {
+ if ( ( elemLang = documentIsHTML ?
+ elem.lang :
+ elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {
+
+ elemLang = elemLang.toLowerCase();
+ return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
+ }
+ } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
+ return false;
+ };
+ } ),
+
+ // Miscellaneous
+ "target": function( elem ) {
+ var hash = window.location && window.location.hash;
+ return hash && hash.slice( 1 ) === elem.id;
+ },
+
+ "root": function( elem ) {
+ return elem === docElem;
+ },
+
+ "focus": function( elem ) {
+ return elem === document.activeElement &&
+ ( !document.hasFocus || document.hasFocus() ) &&
+ !!( elem.type || elem.href || ~elem.tabIndex );
+ },
+
+ // Boolean properties
+ "enabled": createDisabledPseudo( false ),
+ "disabled": createDisabledPseudo( true ),
+
+ "checked": function( elem ) {
+
+ // In CSS3, :checked should return both checked and selected elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ var nodeName = elem.nodeName.toLowerCase();
+ return ( nodeName === "input" && !!elem.checked ) ||
+ ( nodeName === "option" && !!elem.selected );
+ },
+
+ "selected": function( elem ) {
+
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ // eslint-disable-next-line no-unused-expressions
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ // Contents
+ "empty": function( elem ) {
+
+ // http://www.w3.org/TR/selectors/#empty-pseudo
+ // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
+ // but not by others (comment: 8; processing instruction: 7; etc.)
+ // nodeType < 6 works because attributes (2) do not appear as children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ if ( elem.nodeType < 6 ) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ "parent": function( elem ) {
+ return !Expr.pseudos[ "empty" ]( elem );
+ },
+
+ // Element/input types
+ "header": function( elem ) {
+ return rheader.test( elem.nodeName );
+ },
+
+ "input": function( elem ) {
+ return rinputs.test( elem.nodeName );
+ },
+
+ "button": function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === "button" || name === "button";
+ },
+
+ "text": function( elem ) {
+ var attr;
+ return elem.nodeName.toLowerCase() === "input" &&
+ elem.type === "text" &&
+
+ // Support: IE<8
+ // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
+ ( ( attr = elem.getAttribute( "type" ) ) == null ||
+ attr.toLowerCase() === "text" );
+ },
+
+ // Position-in-collection
+ "first": createPositionalPseudo( function() {
+ return [ 0 ];
+ } ),
+
+ "last": createPositionalPseudo( function( _matchIndexes, length ) {
+ return [ length - 1 ];
+ } ),
+
+ "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {
+ return [ argument < 0 ? argument + length : argument ];
+ } ),
+
+ "even": createPositionalPseudo( function( matchIndexes, length ) {
+ var i = 0;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ } ),
+
+ "odd": createPositionalPseudo( function( matchIndexes, length ) {
+ var i = 1;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ } ),
+
+ "lt": createPositionalPseudo( function( matchIndexes, length, argument ) {
+ var i = argument < 0 ?
+ argument + length :
+ argument > length ?
+ length :
+ argument;
+ for ( ; --i >= 0; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ } ),
+
+ "gt": createPositionalPseudo( function( matchIndexes, length, argument ) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; ++i < length; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ } )
+ }
+};
+
+Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];
+
+// Add button/input type pseudos
+for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
+ Expr.pseudos[ i ] = createInputPseudo( i );
+}
+for ( i in { submit: true, reset: true } ) {
+ Expr.pseudos[ i ] = createButtonPseudo( i );
+}
+
+// Easy API for creating new setFilters
+function setFilters() {}
+setFilters.prototype = Expr.filters = Expr.pseudos;
+Expr.setFilters = new setFilters();
+
+tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
+ var matched, match, tokens, type,
+ soFar, groups, preFilters,
+ cached = tokenCache[ selector + " " ];
+
+ if ( cached ) {
+ return parseOnly ? 0 : cached.slice( 0 );
+ }
+
+ soFar = selector;
+ groups = [];
+ preFilters = Expr.preFilter;
+
+ while ( soFar ) {
+
+ // Comma and first run
+ if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
+ if ( match ) {
+
+ // Don't consume trailing commas as valid
+ soFar = soFar.slice( match[ 0 ].length ) || soFar;
+ }
+ groups.push( ( tokens = [] ) );
+ }
+
+ matched = false;
+
+ // Combinators
+ if ( ( match = rcombinators.exec( soFar ) ) ) {
+ matched = match.shift();
+ tokens.push( {
+ value: matched,
+
+ // Cast descendant combinators to space
+ type: match[ 0 ].replace( rtrim, " " )
+ } );
+ soFar = soFar.slice( matched.length );
+ }
+
+ // Filters
+ for ( type in Expr.filter ) {
+ if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||
+ ( match = preFilters[ type ]( match ) ) ) ) {
+ matched = match.shift();
+ tokens.push( {
+ value: matched,
+ type: type,
+ matches: match
+ } );
+ soFar = soFar.slice( matched.length );
+ }
+ }
+
+ if ( !matched ) {
+ break;
+ }
+ }
+
+ // Return the length of the invalid excess
+ // if we're just parsing
+ // Otherwise, throw an error or return tokens
+ return parseOnly ?
+ soFar.length :
+ soFar ?
+ Sizzle.error( selector ) :
+
+ // Cache the tokens
+ tokenCache( selector, groups ).slice( 0 );
+};
+
+function toSelector( tokens ) {
+ var i = 0,
+ len = tokens.length,
+ selector = "";
+ for ( ; i < len; i++ ) {
+ selector += tokens[ i ].value;
+ }
+ return selector;
+}
+
+function addCombinator( matcher, combinator, base ) {
+ var dir = combinator.dir,
+ skip = combinator.next,
+ key = skip || dir,
+ checkNonElements = base && key === "parentNode",
+ doneName = done++;
+
+ return combinator.first ?
+
+ // Check against closest ancestor/preceding element
+ function( elem, context, xml ) {
+ while ( ( elem = elem[ dir ] ) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ return matcher( elem, context, xml );
+ }
+ }
+ return false;
+ } :
+
+ // Check against all ancestor/preceding elements
+ function( elem, context, xml ) {
+ var oldCache, uniqueCache, outerCache,
+ newCache = [ dirruns, doneName ];
+
+ // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
+ if ( xml ) {
+ while ( ( elem = elem[ dir ] ) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ if ( matcher( elem, context, xml ) ) {
+ return true;
+ }
+ }
+ }
+ } else {
+ while ( ( elem = elem[ dir ] ) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ outerCache = elem[ expando ] || ( elem[ expando ] = {} );
+
+ // Support: IE <9 only
+ // Defend against cloned attroperties (jQuery gh-1709)
+ uniqueCache = outerCache[ elem.uniqueID ] ||
+ ( outerCache[ elem.uniqueID ] = {} );
+
+ if ( skip && skip === elem.nodeName.toLowerCase() ) {
+ elem = elem[ dir ] || elem;
+ } else if ( ( oldCache = uniqueCache[ key ] ) &&
+ oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
+
+ // Assign to newCache so results back-propagate to previous elements
+ return ( newCache[ 2 ] = oldCache[ 2 ] );
+ } else {
+
+ // Reuse newcache so results back-propagate to previous elements
+ uniqueCache[ key ] = newCache;
+
+ // A match means we're done; a fail means we have to keep checking
+ if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ };
+}
+
+function elementMatcher( matchers ) {
+ return matchers.length > 1 ?
+ function( elem, context, xml ) {
+ var i = matchers.length;
+ while ( i-- ) {
+ if ( !matchers[ i ]( elem, context, xml ) ) {
+ return false;
+ }
+ }
+ return true;
+ } :
+ matchers[ 0 ];
+}
+
+function multipleContexts( selector, contexts, results ) {
+ var i = 0,
+ len = contexts.length;
+ for ( ; i < len; i++ ) {
+ Sizzle( selector, contexts[ i ], results );
+ }
+ return results;
+}
+
+function condense( unmatched, map, filter, context, xml ) {
+ var elem,
+ newUnmatched = [],
+ i = 0,
+ len = unmatched.length,
+ mapped = map != null;
+
+ for ( ; i < len; i++ ) {
+ if ( ( elem = unmatched[ i ] ) ) {
+ if ( !filter || filter( elem, context, xml ) ) {
+ newUnmatched.push( elem );
+ if ( mapped ) {
+ map.push( i );
+ }
+ }
+ }
+ }
+
+ return newUnmatched;
+}
+
+function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
+ if ( postFilter && !postFilter[ expando ] ) {
+ postFilter = setMatcher( postFilter );
+ }
+ if ( postFinder && !postFinder[ expando ] ) {
+ postFinder = setMatcher( postFinder, postSelector );
+ }
+ return markFunction( function( seed, results, context, xml ) {
+ var temp, i, elem,
+ preMap = [],
+ postMap = [],
+ preexisting = results.length,
+
+ // Get initial elements from seed or context
+ elems = seed || multipleContexts(
+ selector || "*",
+ context.nodeType ? [ context ] : context,
+ []
+ ),
+
+ // Prefilter to get matcher input, preserving a map for seed-results synchronization
+ matcherIn = preFilter && ( seed || !selector ) ?
+ condense( elems, preMap, preFilter, context, xml ) :
+ elems,
+
+ matcherOut = matcher ?
+
+ // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
+ postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
+
+ // ...intermediate processing is necessary
+ [] :
+
+ // ...otherwise use results directly
+ results :
+ matcherIn;
+
+ // Find primary matches
+ if ( matcher ) {
+ matcher( matcherIn, matcherOut, context, xml );
+ }
+
+ // Apply postFilter
+ if ( postFilter ) {
+ temp = condense( matcherOut, postMap );
+ postFilter( temp, [], context, xml );
+
+ // Un-match failing elements by moving them back to matcherIn
+ i = temp.length;
+ while ( i-- ) {
+ if ( ( elem = temp[ i ] ) ) {
+ matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
+ }
+ }
+ }
+
+ if ( seed ) {
+ if ( postFinder || preFilter ) {
+ if ( postFinder ) {
+
+ // Get the final matcherOut by condensing this intermediate into postFinder contexts
+ temp = [];
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( ( elem = matcherOut[ i ] ) ) {
+
+ // Restore matcherIn since elem is not yet a final match
+ temp.push( ( matcherIn[ i ] = elem ) );
+ }
+ }
+ postFinder( null, ( matcherOut = [] ), temp, xml );
+ }
+
+ // Move matched elements from seed to results to keep them synchronized
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( ( elem = matcherOut[ i ] ) &&
+ ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) {
+
+ seed[ temp ] = !( results[ temp ] = elem );
+ }
+ }
+ }
+
+ // Add elements to results, through postFinder if defined
+ } else {
+ matcherOut = condense(
+ matcherOut === results ?
+ matcherOut.splice( preexisting, matcherOut.length ) :
+ matcherOut
+ );
+ if ( postFinder ) {
+ postFinder( null, results, matcherOut, xml );
+ } else {
+ push.apply( results, matcherOut );
+ }
+ }
+ } );
+}
+
+function matcherFromTokens( tokens ) {
+ var checkContext, matcher, j,
+ len = tokens.length,
+ leadingRelative = Expr.relative[ tokens[ 0 ].type ],
+ implicitRelative = leadingRelative || Expr.relative[ " " ],
+ i = leadingRelative ? 1 : 0,
+
+ // The foundational matcher ensures that elements are reachable from top-level context(s)
+ matchContext = addCombinator( function( elem ) {
+ return elem === checkContext;
+ }, implicitRelative, true ),
+ matchAnyContext = addCombinator( function( elem ) {
+ return indexOf( checkContext, elem ) > -1;
+ }, implicitRelative, true ),
+ matchers = [ function( elem, context, xml ) {
+ var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+ ( checkContext = context ).nodeType ?
+ matchContext( elem, context, xml ) :
+ matchAnyContext( elem, context, xml ) );
+
+ // Avoid hanging onto element (issue #299)
+ checkContext = null;
+ return ret;
+ } ];
+
+ for ( ; i < len; i++ ) {
+ if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
+ matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
+ } else {
+ matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );
+
+ // Return special upon seeing a positional matcher
+ if ( matcher[ expando ] ) {
+
+ // Find the next relative operator (if any) for proper handling
+ j = ++i;
+ for ( ; j < len; j++ ) {
+ if ( Expr.relative[ tokens[ j ].type ] ) {
+ break;
+ }
+ }
+ return setMatcher(
+ i > 1 && elementMatcher( matchers ),
+ i > 1 && toSelector(
+
+ // If the preceding token was a descendant combinator, insert an implicit any-element `*`
+ tokens
+ .slice( 0, i - 1 )
+ .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
+ ).replace( rtrim, "$1" ),
+ matcher,
+ i < j && matcherFromTokens( tokens.slice( i, j ) ),
+ j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
+ j < len && toSelector( tokens )
+ );
+ }
+ matchers.push( matcher );
+ }
+ }
+
+ return elementMatcher( matchers );
+}
+
+function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
+ var bySet = setMatchers.length > 0,
+ byElement = elementMatchers.length > 0,
+ superMatcher = function( seed, context, xml, results, outermost ) {
+ var elem, j, matcher,
+ matchedCount = 0,
+ i = "0",
+ unmatched = seed && [],
+ setMatched = [],
+ contextBackup = outermostContext,
+
+ // We must always have either seed elements or outermost context
+ elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ),
+
+ // Use integer dirruns iff this is the outermost matcher
+ dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
+ len = elems.length;
+
+ if ( outermost ) {
+
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ outermostContext = context == document || context || outermost;
+ }
+
+ // Add elements passing elementMatchers directly to results
+ // Support: IE<9, Safari
+ // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
+ for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {
+ if ( byElement && elem ) {
+ j = 0;
+
+ // Support: IE 11+, Edge 17 - 18+
+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
+ // two documents; shallow comparisons work.
+ // eslint-disable-next-line eqeqeq
+ if ( !context && elem.ownerDocument != document ) {
+ setDocument( elem );
+ xml = !documentIsHTML;
+ }
+ while ( ( matcher = elementMatchers[ j++ ] ) ) {
+ if ( matcher( elem, context || document, xml ) ) {
+ results.push( elem );
+ break;
+ }
+ }
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ }
+ }
+
+ // Track unmatched elements for set filters
+ if ( bySet ) {
+
+ // They will have gone through all possible matchers
+ if ( ( elem = !matcher && elem ) ) {
+ matchedCount--;
+ }
+
+ // Lengthen the array for every element, matched or not
+ if ( seed ) {
+ unmatched.push( elem );
+ }
+ }
+ }
+
+ // `i` is now the count of elements visited above, and adding it to `matchedCount`
+ // makes the latter nonnegative.
+ matchedCount += i;
+
+ // Apply set filters to unmatched elements
+ // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
+ // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
+ // no element matchers and no seed.
+ // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
+ // case, which will result in a "00" `matchedCount` that differs from `i` but is also
+ // numerically zero.
+ if ( bySet && i !== matchedCount ) {
+ j = 0;
+ while ( ( matcher = setMatchers[ j++ ] ) ) {
+ matcher( unmatched, setMatched, context, xml );
+ }
+
+ if ( seed ) {
+
+ // Reintegrate element matches to eliminate the need for sorting
+ if ( matchedCount > 0 ) {
+ while ( i-- ) {
+ if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
+ setMatched[ i ] = pop.call( results );
+ }
+ }
+ }
+
+ // Discard index placeholder values to get only actual matches
+ setMatched = condense( setMatched );
+ }
+
+ // Add matches to results
+ push.apply( results, setMatched );
+
+ // Seedless set matches succeeding multiple successful matchers stipulate sorting
+ if ( outermost && !seed && setMatched.length > 0 &&
+ ( matchedCount + setMatchers.length ) > 1 ) {
+
+ Sizzle.uniqueSort( results );
+ }
+ }
+
+ // Override manipulation of globals by nested matchers
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ outermostContext = contextBackup;
+ }
+
+ return unmatched;
+ };
+
+ return bySet ?
+ markFunction( superMatcher ) :
+ superMatcher;
+}
+
+compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
+ var i,
+ setMatchers = [],
+ elementMatchers = [],
+ cached = compilerCache[ selector + " " ];
+
+ if ( !cached ) {
+
+ // Generate a function of recursive functions that can be used to check each element
+ if ( !match ) {
+ match = tokenize( selector );
+ }
+ i = match.length;
+ while ( i-- ) {
+ cached = matcherFromTokens( match[ i ] );
+ if ( cached[ expando ] ) {
+ setMatchers.push( cached );
+ } else {
+ elementMatchers.push( cached );
+ }
+ }
+
+ // Cache the compiled function
+ cached = compilerCache(
+ selector,
+ matcherFromGroupMatchers( elementMatchers, setMatchers )
+ );
+
+ // Save selector and tokenization
+ cached.selector = selector;
+ }
+ return cached;
+};
+
+/**
+ * A low-level selection function that works with Sizzle's compiled
+ * selector functions
+ * @param {String|Function} selector A selector or a pre-compiled
+ * selector function built with Sizzle.compile
+ * @param {Element} context
+ * @param {Array} [results]
+ * @param {Array} [seed] A set of elements to match against
+ */
+select = Sizzle.select = function( selector, context, results, seed ) {
+ var i, tokens, token, type, find,
+ compiled = typeof selector === "function" && selector,
+ match = !seed && tokenize( ( selector = compiled.selector || selector ) );
+
+ results = results || [];
+
+ // Try to minimize operations if there is only one selector in the list and no seed
+ // (the latter of which guarantees us context)
+ if ( match.length === 1 ) {
+
+ // Reduce context if the leading compound selector is an ID
+ tokens = match[ 0 ] = match[ 0 ].slice( 0 );
+ if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
+ context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {
+
+ context = ( Expr.find[ "ID" ]( token.matches[ 0 ]
+ .replace( runescape, funescape ), context ) || [] )[ 0 ];
+ if ( !context ) {
+ return results;
+
+ // Precompiled matchers will still verify ancestry, so step up a level
+ } else if ( compiled ) {
+ context = context.parentNode;
+ }
+
+ selector = selector.slice( tokens.shift().value.length );
+ }
+
+ // Fetch a seed set for right-to-left matching
+ i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;
+ while ( i-- ) {
+ token = tokens[ i ];
+
+ // Abort if we hit a combinator
+ if ( Expr.relative[ ( type = token.type ) ] ) {
+ break;
+ }
+ if ( ( find = Expr.find[ type ] ) ) {
+
+ // Search, expanding context for leading sibling combinators
+ if ( ( seed = find(
+ token.matches[ 0 ].replace( runescape, funescape ),
+ rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) ||
+ context
+ ) ) ) {
+
+ // If seed is empty or no tokens remain, we can return early
+ tokens.splice( i, 1 );
+ selector = seed.length && toSelector( tokens );
+ if ( !selector ) {
+ push.apply( results, seed );
+ return results;
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ // Compile and execute a filtering function if one is not provided
+ // Provide `match` to avoid retokenization if we modified the selector above
+ ( compiled || compile( selector, match ) )(
+ seed,
+ context,
+ !documentIsHTML,
+ results,
+ !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
+ );
+ return results;
+};
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;
+
+// Support: Chrome 14-35+
+// Always assume duplicates if they aren't passed to the comparison function
+support.detectDuplicates = !!hasDuplicate;
+
+// Initialize against the default document
+setDocument();
+
+// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
+// Detached nodes confoundingly follow *each other*
+support.sortDetached = assert( function( el ) {
+
+ // Should return 1, but returns 4 (following)
+ return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;
+} );
+
+// Support: IE<8
+// Prevent attribute/property "interpolation"
+// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !assert( function( el ) {
+ el.innerHTML = "<a href='#'></a>";
+ return el.firstChild.getAttribute( "href" ) === "#";
+} ) ) {
+ addHandle( "type|href|height|width", function( elem, name, isXML ) {
+ if ( !isXML ) {
+ return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
+ }
+ } );
+}
+
+// Support: IE<9
+// Use defaultValue in place of getAttribute("value")
+if ( !support.attributes || !assert( function( el ) {
+ el.innerHTML = "<input/>";
+ el.firstChild.setAttribute( "value", "" );
+ return el.firstChild.getAttribute( "value" ) === "";
+} ) ) {
+ addHandle( "value", function( elem, _name, isXML ) {
+ if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
+ return elem.defaultValue;
+ }
+ } );
+}
+
+// Support: IE<9
+// Use getAttributeNode to fetch booleans when getAttribute lies
+if ( !assert( function( el ) {
+ return el.getAttribute( "disabled" ) == null;
+} ) ) {
+ addHandle( booleans, function( elem, name, isXML ) {
+ var val;
+ if ( !isXML ) {
+ return elem[ name ] === true ? name.toLowerCase() :
+ ( val = elem.getAttributeNode( name ) ) && val.specified ?
+ val.value :
+ null;
+ }
+ } );
+}
+
+return Sizzle;
+
+} )( window );
+
+
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+
+// Deprecated
+jQuery.expr[ ":" ] = jQuery.expr.pseudos;
+jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+jQuery.escapeSelector = Sizzle.escape;
+
+
+
+
+var dir = function( elem, dir, until ) {
+ var matched = [],
+ truncate = until !== undefined;
+
+ while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
+ if ( elem.nodeType === 1 ) {
+ if ( truncate && jQuery( elem ).is( until ) ) {
+ break;
+ }
+ matched.push( elem );
+ }
+ }
+ return matched;
+};
+
+
+var siblings = function( n, elem ) {
+ var matched = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ matched.push( n );
+ }
+ }
+
+ return matched;
+};
+
+
+var rneedsContext = jQuery.expr.match.needsContext;
+
+
+
+function nodeName( elem, name ) {
+
+ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
+
+}
+var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
+
+
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, not ) {
+ if ( isFunction( qualifier ) ) {
+ return jQuery.grep( elements, function( elem, i ) {
+ return !!qualifier.call( elem, i, elem ) !== not;
+ } );
+ }
+
+ // Single element
+ if ( qualifier.nodeType ) {
+ return jQuery.grep( elements, function( elem ) {
+ return ( elem === qualifier ) !== not;
+ } );
+ }
+
+ // Arraylike of elements (jQuery, arguments, Array)
+ if ( typeof qualifier !== "string" ) {
+ return jQuery.grep( elements, function( elem ) {
+ return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
+ } );
+ }
+
+ // Filtered directly for both simple and complex selectors
+ return jQuery.filter( qualifier, elements, not );
+}
+
+jQuery.filter = function( expr, elems, not ) {
+ var elem = elems[ 0 ];
+
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ if ( elems.length === 1 && elem.nodeType === 1 ) {
+ return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
+ }
+
+ return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+ return elem.nodeType === 1;
+ } ) );
+};
+
+jQuery.fn.extend( {
+ find: function( selector ) {
+ var i, ret,
+ len = this.length,
+ self = this;
+
+ if ( typeof selector !== "string" ) {
+ return this.pushStack( jQuery( selector ).filter( function() {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ } ) );
+ }
+
+ ret = this.pushStack( [] );
+
+ for ( i = 0; i < len; i++ ) {
+ jQuery.find( selector, self[ i ], ret );
+ }
+
+ return len > 1 ? jQuery.uniqueSort( ret ) : ret;
+ },
+ filter: function( selector ) {
+ return this.pushStack( winnow( this, selector || [], false ) );
+ },
+ not: function( selector ) {
+ return this.pushStack( winnow( this, selector || [], true ) );
+ },
+ is: function( selector ) {
+ return !!winnow(
+ this,
+
+ // If this is a positional/relative selector, check membership in the returned set
+ // so $("p:first").is("p:last") won't return true for a doc with two "p".
+ typeof selector === "string" && rneedsContext.test( selector ) ?
+ jQuery( selector ) :
+ selector || [],
+ false
+ ).length;
+ }
+} );
+
+
+// Initialize a jQuery object
+
+
+// A central reference to the root jQuery(document)
+var rootjQuery,
+
+ // A simple way to check for HTML strings
+ // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+ // Strict HTML recognition (#11290: must start with <)
+ // Shortcut simple #id case for speed
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
+
+ init = jQuery.fn.init = function( selector, context, root ) {
+ var match, elem;
+
+ // HANDLE: $(""), $(null), $(undefined), $(false)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Method init() accepts an alternate rootjQuery
+ // so migrate can support jQuery.sub (gh-2101)
+ root = root || rootjQuery;
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ if ( selector[ 0 ] === "<" &&
+ selector[ selector.length - 1 ] === ">" &&
+ selector.length >= 3 ) {
+
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = rquickExpr.exec( selector );
+ }
+
+ // Match html or make sure no context is specified for #id
+ if ( match && ( match[ 1 ] || !context ) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[ 1 ] ) {
+ context = context instanceof jQuery ? context[ 0 ] : context;
+
+ // Option to run scripts is true for back-compat
+ // Intentionally let the error be thrown if parseHTML is not present
+ jQuery.merge( this, jQuery.parseHTML(
+ match[ 1 ],
+ context && context.nodeType ? context.ownerDocument || context : document,
+ true
+ ) );
+
+ // HANDLE: $(html, props)
+ if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
+ for ( match in context ) {
+
+ // Properties of context are called as methods if possible
+ if ( isFunction( this[ match ] ) ) {
+ this[ match ]( context[ match ] );
+
+ // ...and otherwise set as attributes
+ } else {
+ this.attr( match, context[ match ] );
+ }
+ }
+ }
+
+ return this;
+
+ // HANDLE: $(#id)
+ } else {
+ elem = document.getElementById( match[ 2 ] );
+
+ if ( elem ) {
+
+ // Inject the element directly into the jQuery object
+ this[ 0 ] = elem;
+ this.length = 1;
+ }
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return ( context || root ).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(DOMElement)
+ } else if ( selector.nodeType ) {
+ this[ 0 ] = selector;
+ this.length = 1;
+ return this;
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( isFunction( selector ) ) {
+ return root.ready !== undefined ?
+ root.ready( selector ) :
+
+ // Execute immediately if ready is not present
+ selector( jQuery );
+ }
+
+ return jQuery.makeArray( selector, this );
+ };
+
+// Give the init function the jQuery prototype for later instantiation
+init.prototype = jQuery.fn;
+
+// Initialize central reference
+rootjQuery = jQuery( document );
+
+
+var rparentsprev = /^(?:parents|prev(?:Until|All))/,
+
+ // Methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.fn.extend( {
+ has: function( target ) {
+ var targets = jQuery( target, this ),
+ l = targets.length;
+
+ return this.filter( function() {
+ var i = 0;
+ for ( ; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[ i ] ) ) {
+ return true;
+ }
+ }
+ } );
+ },
+
+ closest: function( selectors, context ) {
+ var cur,
+ i = 0,
+ l = this.length,
+ matched = [],
+ targets = typeof selectors !== "string" && jQuery( selectors );
+
+ // Positional selectors never match, since there's no _selection_ context
+ if ( !rneedsContext.test( selectors ) ) {
+ for ( ; i < l; i++ ) {
+ for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
+
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && ( targets ?
+ targets.index( cur ) > -1 :
+
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector( cur, selectors ) ) ) {
+
+ matched.push( cur );
+ break;
+ }
+ }
+ }
+ }
+
+ return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
+ },
+
+ // Determine the position of an element within the set
+ index: function( elem ) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
+ }
+
+ // Index in selector
+ if ( typeof elem === "string" ) {
+ return indexOf.call( jQuery( elem ), this[ 0 ] );
+ }
+
+ // Locate the position of the desired element
+ return indexOf.call( this,
+
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[ 0 ] : elem
+ );
+ },
+
+ add: function( selector, context ) {
+ return this.pushStack(
+ jQuery.uniqueSort(
+ jQuery.merge( this.get(), jQuery( selector, context ) )
+ )
+ );
+ },
+
+ addBack: function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter( selector )
+ );
+ }
+} );
+
+function sibling( cur, dir ) {
+ while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
+ return cur;
+}
+
+jQuery.each( {
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, _i, until ) {
+ return dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return sibling( elem, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return sibling( elem, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, _i, until ) {
+ return dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, _i, until ) {
+ return dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return siblings( ( elem.parentNode || {} ).firstChild, elem );
+ },
+ children: function( elem ) {
+ return siblings( elem.firstChild );
+ },
+ contents: function( elem ) {
+ if ( elem.contentDocument != null &&
+
+ // Support: IE 11+
+ // <object> elements with no `data` attribute has an object
+ // `contentDocument` with a `null` prototype.
+ getProto( elem.contentDocument ) ) {
+
+ return elem.contentDocument;
+ }
+
+ // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
+ // Treat the template element as a regular one in browsers that
+ // don't support it.
+ if ( nodeName( elem, "template" ) ) {
+ elem = elem.content || elem;
+ }
+
+ return jQuery.merge( [], elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var matched = jQuery.map( this, fn, until );
+
+ if ( name.slice( -5 ) !== "Until" ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ matched = jQuery.filter( selector, matched );
+ }
+
+ if ( this.length > 1 ) {
+
+ // Remove duplicates
+ if ( !guaranteedUnique[ name ] ) {
+ jQuery.uniqueSort( matched );
+ }
+
+ // Reverse order for parents* and prev-derivatives
+ if ( rparentsprev.test( name ) ) {
+ matched.reverse();
+ }
+ }
+
+ return this.pushStack( matched );
+ };
+} );
+var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
+
+
+
+// Convert String-formatted options into Object-formatted ones
+function createOptions( options ) {
+ var object = {};
+ jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
+ object[ flag ] = true;
+ } );
+ return object;
+}
+
+/*
+ * Create a callback list using the following parameters:
+ *
+ * options: an optional list of space-separated options that will change how
+ * the callback list behaves or a more traditional option object
+ *
+ * By default a callback list will act like an event callback list and can be
+ * "fired" multiple times.
+ *
+ * Possible options:
+ *
+ * once: will ensure the callback list can only be fired once (like a Deferred)
+ *
+ * memory: will keep track of previous values and will call any callback added
+ * after the list has been fired right away with the latest "memorized"
+ * values (like a Deferred)
+ *
+ * unique: will ensure a callback can only be added once (no duplicate in the list)
+ *
+ * stopOnFalse: interrupt callings when a callback returns false
+ *
+ */
+jQuery.Callbacks = function( options ) {
+
+ // Convert options from String-formatted to Object-formatted if needed
+ // (we check in cache first)
+ options = typeof options === "string" ?
+ createOptions( options ) :
+ jQuery.extend( {}, options );
+
+ var // Flag to know if list is currently firing
+ firing,
+
+ // Last fire value for non-forgettable lists
+ memory,
+
+ // Flag to know if list was already fired
+ fired,
+
+ // Flag to prevent firing
+ locked,
+
+ // Actual callback list
+ list = [],
+
+ // Queue of execution data for repeatable lists
+ queue = [],
+
+ // Index of currently firing callback (modified by add/remove as needed)
+ firingIndex = -1,
+
+ // Fire callbacks
+ fire = function() {
+
+ // Enforce single-firing
+ locked = locked || options.once;
+
+ // Execute callbacks for all pending executions,
+ // respecting firingIndex overrides and runtime changes
+ fired = firing = true;
+ for ( ; queue.length; firingIndex = -1 ) {
+ memory = queue.shift();
+ while ( ++firingIndex < list.length ) {
+
+ // Run callback and check for early termination
+ if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
+ options.stopOnFalse ) {
+
+ // Jump to end and forget the data so .add doesn't re-fire
+ firingIndex = list.length;
+ memory = false;
+ }
+ }
+ }
+
+ // Forget the data if we're done with it
+ if ( !options.memory ) {
+ memory = false;
+ }
+
+ firing = false;
+
+ // Clean up if we're done firing for good
+ if ( locked ) {
+
+ // Keep an empty list if we have data for future add calls
+ if ( memory ) {
+ list = [];
+
+ // Otherwise, this object is spent
+ } else {
+ list = "";
+ }
+ }
+ },
+
+ // Actual Callbacks object
+ self = {
+
+ // Add a callback or a collection of callbacks to the list
+ add: function() {
+ if ( list ) {
+
+ // If we have memory from a past run, we should fire after adding
+ if ( memory && !firing ) {
+ firingIndex = list.length - 1;
+ queue.push( memory );
+ }
+
+ ( function add( args ) {
+ jQuery.each( args, function( _, arg ) {
+ if ( isFunction( arg ) ) {
+ if ( !options.unique || !self.has( arg ) ) {
+ list.push( arg );
+ }
+ } else if ( arg && arg.length && toType( arg ) !== "string" ) {
+
+ // Inspect recursively
+ add( arg );
+ }
+ } );
+ } )( arguments );
+
+ if ( memory && !firing ) {
+ fire();
+ }
+ }
+ return this;
+ },
+
+ // Remove a callback from the list
+ remove: function() {
+ jQuery.each( arguments, function( _, arg ) {
+ var index;
+ while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+ list.splice( index, 1 );
+
+ // Handle firing indexes
+ if ( index <= firingIndex ) {
+ firingIndex--;
+ }
+ }
+ } );
+ return this;
+ },
+
+ // Check if a given callback is in the list.
+ // If no argument is given, return whether or not list has callbacks attached.
+ has: function( fn ) {
+ return fn ?
+ jQuery.inArray( fn, list ) > -1 :
+ list.length > 0;
+ },
+
+ // Remove all callbacks from the list
+ empty: function() {
+ if ( list ) {
+ list = [];
+ }
+ return this;
+ },
+
+ // Disable .fire and .add
+ // Abort any current/pending executions
+ // Clear all callbacks and values
+ disable: function() {
+ locked = queue = [];
+ list = memory = "";
+ return this;
+ },
+ disabled: function() {
+ return !list;
+ },
+
+ // Disable .fire
+ // Also disable .add unless we have memory (since it would have no effect)
+ // Abort any pending executions
+ lock: function() {
+ locked = queue = [];
+ if ( !memory && !firing ) {
+ list = memory = "";
+ }
+ return this;
+ },
+ locked: function() {
+ return !!locked;
+ },
+
+ // Call all callbacks with the given context and arguments
+ fireWith: function( context, args ) {
+ if ( !locked ) {
+ args = args || [];
+ args = [ context, args.slice ? args.slice() : args ];
+ queue.push( args );
+ if ( !firing ) {
+ fire();
+ }
+ }
+ return this;
+ },
+
+ // Call all the callbacks with the given arguments
+ fire: function() {
+ self.fireWith( this, arguments );
+ return this;
+ },
+
+ // To know if the callbacks have already been called at least once
+ fired: function() {
+ return !!fired;
+ }
+ };
+
+ return self;
+};
+
+
+function Identity( v ) {
+ return v;
+}
+function Thrower( ex ) {
+ throw ex;
+}
+
+function adoptValue( value, resolve, reject, noValue ) {
+ var method;
+
+ try {
+
+ // Check for promise aspect first to privilege synchronous behavior
+ if ( value && isFunction( ( method = value.promise ) ) ) {
+ method.call( value ).done( resolve ).fail( reject );
+
+ // Other thenables
+ } else if ( value && isFunction( ( method = value.then ) ) ) {
+ method.call( value, resolve, reject );
+
+ // Other non-thenables
+ } else {
+
+ // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
+ // * false: [ value ].slice( 0 ) => resolve( value )
+ // * true: [ value ].slice( 1 ) => resolve()
+ resolve.apply( undefined, [ value ].slice( noValue ) );
+ }
+
+ // For Promises/A+, convert exceptions into rejections
+ // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
+ // Deferred#then to conditionally suppress rejection.
+ } catch ( value ) {
+
+ // Support: Android 4.0 only
+ // Strict mode functions invoked without .call/.apply get global-object context
+ reject.apply( undefined, [ value ] );
+ }
+}
+
+jQuery.extend( {
+
+ Deferred: function( func ) {
+ var tuples = [
+
+ // action, add listener, callbacks,
+ // ... .then handlers, argument index, [final state]
+ [ "notify", "progress", jQuery.Callbacks( "memory" ),
+ jQuery.Callbacks( "memory" ), 2 ],
+ [ "resolve", "done", jQuery.Callbacks( "once memory" ),
+ jQuery.Callbacks( "once memory" ), 0, "resolved" ],
+ [ "reject", "fail", jQuery.Callbacks( "once memory" ),
+ jQuery.Callbacks( "once memory" ), 1, "rejected" ]
+ ],
+ state = "pending",
+ promise = {
+ state: function() {
+ return state;
+ },
+ always: function() {
+ deferred.done( arguments ).fail( arguments );
+ return this;
+ },
+ "catch": function( fn ) {
+ return promise.then( null, fn );
+ },
+
+ // Keep pipe for back-compat
+ pipe: function( /* fnDone, fnFail, fnProgress */ ) {
+ var fns = arguments;
+
+ return jQuery.Deferred( function( newDefer ) {
+ jQuery.each( tuples, function( _i, tuple ) {
+
+ // Map tuples (progress, done, fail) to arguments (done, fail, progress)
+ var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
+
+ // deferred.progress(function() { bind to newDefer or newDefer.notify })
+ // deferred.done(function() { bind to newDefer or newDefer.resolve })
+ // deferred.fail(function() { bind to newDefer or newDefer.reject })
+ deferred[ tuple[ 1 ] ]( function() {
+ var returned = fn && fn.apply( this, arguments );
+ if ( returned && isFunction( returned.promise ) ) {
+ returned.promise()
+ .progress( newDefer.notify )
+ .done( newDefer.resolve )
+ .fail( newDefer.reject );
+ } else {
+ newDefer[ tuple[ 0 ] + "With" ](
+ this,
+ fn ? [ returned ] : arguments
+ );
+ }
+ } );
+ } );
+ fns = null;
+ } ).promise();
+ },
+ then: function( onFulfilled, onRejected, onProgress ) {
+ var maxDepth = 0;
+ function resolve( depth, deferred, handler, special ) {
+ return function() {
+ var that = this,
+ args = arguments,
+ mightThrow = function() {
+ var returned, then;
+
+ // Support: Promises/A+ section 2.3.3.3.3
+ // https://promisesaplus.com/#point-59
+ // Ignore double-resolution attempts
+ if ( depth < maxDepth ) {
+ return;
+ }
+
+ returned = handler.apply( that, args );
+
+ // Support: Promises/A+ section 2.3.1
+ // https://promisesaplus.com/#point-48
+ if ( returned === deferred.promise() ) {
+ throw new TypeError( "Thenable self-resolution" );
+ }
+
+ // Support: Promises/A+ sections 2.3.3.1, 3.5
+ // https://promisesaplus.com/#point-54
+ // https://promisesaplus.com/#point-75
+ // Retrieve `then` only once
+ then = returned &&
+
+ // Support: Promises/A+ section 2.3.4
+ // https://promisesaplus.com/#point-64
+ // Only check objects and functions for thenability
+ ( typeof returned === "object" ||
+ typeof returned === "function" ) &&
+ returned.then;
+
+ // Handle a returned thenable
+ if ( isFunction( then ) ) {
+
+ // Special processors (notify) just wait for resolution
+ if ( special ) {
+ then.call(
+ returned,
+ resolve( maxDepth, deferred, Identity, special ),
+ resolve( maxDepth, deferred, Thrower, special )
+ );
+
+ // Normal processors (resolve) also hook into progress
+ } else {
+
+ // ...and disregard older resolution values
+ maxDepth++;
+
+ then.call(
+ returned,
+ resolve( maxDepth, deferred, Identity, special ),
+ resolve( maxDepth, deferred, Thrower, special ),
+ resolve( maxDepth, deferred, Identity,
+ deferred.notifyWith )
+ );
+ }
+
+ // Handle all other returned values
+ } else {
+
+ // Only substitute handlers pass on context
+ // and multiple values (non-spec behavior)
+ if ( handler !== Identity ) {
+ that = undefined;
+ args = [ returned ];
+ }
+
+ // Process the value(s)
+ // Default process is resolve
+ ( special || deferred.resolveWith )( that, args );
+ }
+ },
+
+ // Only normal processors (resolve) catch and reject exceptions
+ process = special ?
+ mightThrow :
+ function() {
+ try {
+ mightThrow();
+ } catch ( e ) {
+
+ if ( jQuery.Deferred.exceptionHook ) {
+ jQuery.Deferred.exceptionHook( e,
+ process.stackTrace );
+ }
+
+ // Support: Promises/A+ section 2.3.3.3.4.1
+ // https://promisesaplus.com/#point-61
+ // Ignore post-resolution exceptions
+ if ( depth + 1 >= maxDepth ) {
+
+ // Only substitute handlers pass on context
+ // and multiple values (non-spec behavior)
+ if ( handler !== Thrower ) {
+ that = undefined;
+ args = [ e ];
+ }
+
+ deferred.rejectWith( that, args );
+ }
+ }
+ };
+
+ // Support: Promises/A+ section 2.3.3.3.1
+ // https://promisesaplus.com/#point-57
+ // Re-resolve promises immediately to dodge false rejection from
+ // subsequent errors
+ if ( depth ) {
+ process();
+ } else {
+
+ // Call an optional hook to record the stack, in case of exception
+ // since it's otherwise lost when execution goes async
+ if ( jQuery.Deferred.getStackHook ) {
+ process.stackTrace = jQuery.Deferred.getStackHook();
+ }
+ window.setTimeout( process );
+ }
+ };
+ }
+
+ return jQuery.Deferred( function( newDefer ) {
+
+ // progress_handlers.add( ... )
+ tuples[ 0 ][ 3 ].add(
+ resolve(
+ 0,
+ newDefer,
+ isFunction( onProgress ) ?
+ onProgress :
+ Identity,
+ newDefer.notifyWith
+ )
+ );
+
+ // fulfilled_handlers.add( ... )
+ tuples[ 1 ][ 3 ].add(
+ resolve(
+ 0,
+ newDefer,
+ isFunction( onFulfilled ) ?
+ onFulfilled :
+ Identity
+ )
+ );
+
+ // rejected_handlers.add( ... )
+ tuples[ 2 ][ 3 ].add(
+ resolve(
+ 0,
+ newDefer,
+ isFunction( onRejected ) ?
+ onRejected :
+ Thrower
+ )
+ );
+ } ).promise();
+ },
+
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ return obj != null ? jQuery.extend( obj, promise ) : promise;
+ }
+ },
+ deferred = {};
+
+ // Add list-specific methods
+ jQuery.each( tuples, function( i, tuple ) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 5 ];
+
+ // promise.progress = list.add
+ // promise.done = list.add
+ // promise.fail = list.add
+ promise[ tuple[ 1 ] ] = list.add;
+
+ // Handle state
+ if ( stateString ) {
+ list.add(
+ function() {
+
+ // state = "resolved" (i.e., fulfilled)
+ // state = "rejected"
+ state = stateString;
+ },
+
+ // rejected_callbacks.disable
+ // fulfilled_callbacks.disable
+ tuples[ 3 - i ][ 2 ].disable,
+
+ // rejected_handlers.disable
+ // fulfilled_handlers.disable
+ tuples[ 3 - i ][ 3 ].disable,
+
+ // progress_callbacks.lock
+ tuples[ 0 ][ 2 ].lock,
+
+ // progress_handlers.lock
+ tuples[ 0 ][ 3 ].lock
+ );
+ }
+
+ // progress_handlers.fire
+ // fulfilled_handlers.fire
+ // rejected_handlers.fire
+ list.add( tuple[ 3 ].fire );
+
+ // deferred.notify = function() { deferred.notifyWith(...) }
+ // deferred.resolve = function() { deferred.resolveWith(...) }
+ // deferred.reject = function() { deferred.rejectWith(...) }
+ deferred[ tuple[ 0 ] ] = function() {
+ deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
+ return this;
+ };
+
+ // deferred.notifyWith = list.fireWith
+ // deferred.resolveWith = list.fireWith
+ // deferred.rejectWith = list.fireWith
+ deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
+ } );
+
+ // Make the deferred a promise
+ promise.promise( deferred );
+
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+
+ // All done!
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( singleValue ) {
+ var
+
+ // count of uncompleted subordinates
+ remaining = arguments.length,
+
+ // count of unprocessed arguments
+ i = remaining,
+
+ // subordinate fulfillment data
+ resolveContexts = Array( i ),
+ resolveValues = slice.call( arguments ),
+
+ // the primary Deferred
+ primary = jQuery.Deferred(),
+
+ // subordinate callback factory
+ updateFunc = function( i ) {
+ return function( value ) {
+ resolveContexts[ i ] = this;
+ resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
+ if ( !( --remaining ) ) {
+ primary.resolveWith( resolveContexts, resolveValues );
+ }
+ };
+ };
+
+ // Single- and empty arguments are adopted like Promise.resolve
+ if ( remaining <= 1 ) {
+ adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
+ !remaining );
+
+ // Use .then() to unwrap secondary thenables (cf. gh-3000)
+ if ( primary.state() === "pending" ||
+ isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
+
+ return primary.then();
+ }
+ }
+
+ // Multiple arguments are aggregated like Promise.all array elements
+ while ( i-- ) {
+ adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
+ }
+
+ return primary.promise();
+ }
+} );
+
+
+// These usually indicate a programmer mistake during development,
+// warn about them ASAP rather than swallowing them by default.
+var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
+
+jQuery.Deferred.exceptionHook = function( error, stack ) {
+
+ // Support: IE 8 - 9 only
+ // Console exists when dev tools are open, which can happen at any time
+ if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
+ window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
+ }
+};
+
+
+
+
+jQuery.readyException = function( error ) {
+ window.setTimeout( function() {
+ throw error;
+ } );
+};
+
+
+
+
+// The deferred used on DOM ready
+var readyList = jQuery.Deferred();
+
+jQuery.fn.ready = function( fn ) {
+
+ readyList
+ .then( fn )
+
+ // Wrap jQuery.readyException in a function so that the lookup
+ // happens at the time of error handling instead of callback
+ // registration.
+ .catch( function( error ) {
+ jQuery.readyException( error );
+ } );
+
+ return this;
+};
+
+jQuery.extend( {
+
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+
+ // Abort if there are pending holds or we're already ready
+ if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
+ return;
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+ }
+} );
+
+jQuery.ready.then = readyList.then;
+
+// The ready event handler and self cleanup method
+function completed() {
+ document.removeEventListener( "DOMContentLoaded", completed );
+ window.removeEventListener( "load", completed );
+ jQuery.ready();
+}
+
+// Catch cases where $(document).ready() is called
+// after the browser event has already occurred.
+// Support: IE <=9 - 10 only
+// Older IE sometimes signals "interactive" too soon
+if ( document.readyState === "complete" ||
+ ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
+
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ window.setTimeout( jQuery.ready );
+
+} else {
+
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", completed );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", completed );
+}
+
+
+
+
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
+ var i = 0,
+ len = elems.length,
+ bulk = key == null;
+
+ // Sets many values
+ if ( toType( key ) === "object" ) {
+ chainable = true;
+ for ( i in key ) {
+ access( elems, fn, i, key[ i ], true, emptyGet, raw );
+ }
+
+ // Sets one value
+ } else if ( value !== undefined ) {
+ chainable = true;
+
+ if ( !isFunction( value ) ) {
+ raw = true;
+ }
+
+ if ( bulk ) {
+
+ // Bulk operations run against the entire set
+ if ( raw ) {
+ fn.call( elems, value );
+ fn = null;
+
+ // ...except when executing function values
+ } else {
+ bulk = fn;
+ fn = function( elem, _key, value ) {
+ return bulk.call( jQuery( elem ), value );
+ };
+ }
+ }
+
+ if ( fn ) {
+ for ( ; i < len; i++ ) {
+ fn(
+ elems[ i ], key, raw ?
+ value :
+ value.call( elems[ i ], i, fn( elems[ i ], key ) )
+ );
+ }
+ }
+ }
+
+ if ( chainable ) {
+ return elems;
+ }
+
+ // Gets
+ if ( bulk ) {
+ return fn.call( elems );
+ }
+
+ return len ? fn( elems[ 0 ], key ) : emptyGet;
+};
+
+
+// Matches dashed string for camelizing
+var rmsPrefix = /^-ms-/,
+ rdashAlpha = /-([a-z])/g;
+
+// Used by camelCase as callback to replace()
+function fcamelCase( _all, letter ) {
+ return letter.toUpperCase();
+}
+
+// Convert dashed to camelCase; used by the css and data modules
+// Support: IE <=9 - 11, Edge 12 - 15
+// Microsoft forgot to hump their vendor prefix (#9572)
+function camelCase( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+}
+var acceptData = function( owner ) {
+
+ // Accepts only:
+ // - Node
+ // - Node.ELEMENT_NODE
+ // - Node.DOCUMENT_NODE
+ // - Object
+ // - Any
+ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
+};
+
+
+
+
+function Data() {
+ this.expando = jQuery.expando + Data.uid++;
+}
+
+Data.uid = 1;
+
+Data.prototype = {
+
+ cache: function( owner ) {
+
+ // Check if the owner object already has a cache
+ var value = owner[ this.expando ];
+
+ // If not, create one
+ if ( !value ) {
+ value = {};
+
+ // We can accept data for non-element nodes in modern browsers,
+ // but we should not, see #8335.
+ // Always return an empty object.
+ if ( acceptData( owner ) ) {
+
+ // If it is a node unlikely to be stringify-ed or looped over
+ // use plain assignment
+ if ( owner.nodeType ) {
+ owner[ this.expando ] = value;
+
+ // Otherwise secure it in a non-enumerable property
+ // configurable must be true to allow the property to be
+ // deleted when data is removed
+ } else {
+ Object.defineProperty( owner, this.expando, {
+ value: value,
+ configurable: true
+ } );
+ }
+ }
+ }
+
+ return value;
+ },
+ set: function( owner, data, value ) {
+ var prop,
+ cache = this.cache( owner );
+
+ // Handle: [ owner, key, value ] args
+ // Always use camelCase key (gh-2257)
+ if ( typeof data === "string" ) {
+ cache[ camelCase( data ) ] = value;
+
+ // Handle: [ owner, { properties } ] args
+ } else {
+
+ // Copy the properties one-by-one to the cache object
+ for ( prop in data ) {
+ cache[ camelCase( prop ) ] = data[ prop ];
+ }
+ }
+ return cache;
+ },
+ get: function( owner, key ) {
+ return key === undefined ?
+ this.cache( owner ) :
+
+ // Always use camelCase key (gh-2257)
+ owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
+ },
+ access: function( owner, key, value ) {
+
+ // In cases where either:
+ //
+ // 1. No key was specified
+ // 2. A string key was specified, but no value provided
+ //
+ // Take the "read" path and allow the get method to determine
+ // which value to return, respectively either:
+ //
+ // 1. The entire cache object
+ // 2. The data stored at the key
+ //
+ if ( key === undefined ||
+ ( ( key && typeof key === "string" ) && value === undefined ) ) {
+
+ return this.get( owner, key );
+ }
+
+ // When the key is not a string, or both a key and value
+ // are specified, set or extend (existing objects) with either:
+ //
+ // 1. An object of properties
+ // 2. A key and value
+ //
+ this.set( owner, key, value );
+
+ // Since the "set" path can have two possible entry points
+ // return the expected data based on which path was taken[*]
+ return value !== undefined ? value : key;
+ },
+ remove: function( owner, key ) {
+ var i,
+ cache = owner[ this.expando ];
+
+ if ( cache === undefined ) {
+ return;
+ }
+
+ if ( key !== undefined ) {
+
+ // Support array or space separated string of keys
+ if ( Array.isArray( key ) ) {
+
+ // If key is an array of keys...
+ // We always set camelCase keys, so remove that.
+ key = key.map( camelCase );
+ } else {
+ key = camelCase( key );
+
+ // If a key with the spaces exists, use it.
+ // Otherwise, create an array by matching non-whitespace
+ key = key in cache ?
+ [ key ] :
+ ( key.match( rnothtmlwhite ) || [] );
+ }
+
+ i = key.length;
+
+ while ( i-- ) {
+ delete cache[ key[ i ] ];
+ }
+ }
+
+ // Remove the expando if there's no more data
+ if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
+
+ // Support: Chrome <=35 - 45
+ // Webkit & Blink performance suffers when deleting properties
+ // from DOM nodes, so set to undefined instead
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
+ if ( owner.nodeType ) {
+ owner[ this.expando ] = undefined;
+ } else {
+ delete owner[ this.expando ];
+ }
+ }
+ },
+ hasData: function( owner ) {
+ var cache = owner[ this.expando ];
+ return cache !== undefined && !jQuery.isEmptyObject( cache );
+ }
+};
+var dataPriv = new Data();
+
+var dataUser = new Data();
+
+
+
+// Implementation Summary
+//
+// 1. Enforce API surface and semantic compatibility with 1.9.x branch
+// 2. Improve the module's maintainability by reducing the storage
+// paths to a single mechanism.
+// 3. Use the same single mechanism to support "private" and "user" data.
+// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
+// 5. Avoid exposing implementation details on user objects (eg. expando properties)
+// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
+
+var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /[A-Z]/g;
+
+function getData( data ) {
+ if ( data === "true" ) {
+ return true;
+ }
+
+ if ( data === "false" ) {
+ return false;
+ }
+
+ if ( data === "null" ) {
+ return null;
+ }
+
+ // Only convert to a number if it doesn't change the string
+ if ( data === +data + "" ) {
+ return +data;
+ }
+
+ if ( rbrace.test( data ) ) {
+ return JSON.parse( data );
+ }
+
+ return data;
+}
+
+function dataAttr( elem, key, data ) {
+ var name;
+
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
+ data = elem.getAttribute( name );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = getData( data );
+ } catch ( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ dataUser.set( elem, key, data );
+ } else {
+ data = undefined;
+ }
+ }
+ return data;
+}
+
+jQuery.extend( {
+ hasData: function( elem ) {
+ return dataUser.hasData( elem ) || dataPriv.hasData( elem );
+ },
+
+ data: function( elem, name, data ) {
+ return dataUser.access( elem, name, data );
+ },
+
+ removeData: function( elem, name ) {
+ dataUser.remove( elem, name );
+ },
+
+ // TODO: Now that all calls to _data and _removeData have been replaced
+ // with direct calls to dataPriv methods, these can be deprecated.
+ _data: function( elem, name, data ) {
+ return dataPriv.access( elem, name, data );
+ },
+
+ _removeData: function( elem, name ) {
+ dataPriv.remove( elem, name );
+ }
+} );
+
+jQuery.fn.extend( {
+ data: function( key, value ) {
+ var i, name, data,
+ elem = this[ 0 ],
+ attrs = elem && elem.attributes;
+
+ // Gets all values
+ if ( key === undefined ) {
+ if ( this.length ) {
+ data = dataUser.get( elem );
+
+ if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
+ i = attrs.length;
+ while ( i-- ) {
+
+ // Support: IE 11 only
+ // The attrs elements can be null (#14894)
+ if ( attrs[ i ] ) {
+ name = attrs[ i ].name;
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = camelCase( name.slice( 5 ) );
+ dataAttr( elem, name, data[ name ] );
+ }
+ }
+ }
+ dataPriv.set( elem, "hasDataAttrs", true );
+ }
+ }
+
+ return data;
+ }
+
+ // Sets multiple values
+ if ( typeof key === "object" ) {
+ return this.each( function() {
+ dataUser.set( this, key );
+ } );
+ }
+
+ return access( this, function( value ) {
+ var data;
+
+ // The calling jQuery object (element matches) is not empty
+ // (and therefore has an element appears at this[ 0 ]) and the
+ // `value` parameter was not undefined. An empty jQuery object
+ // will result in `undefined` for elem = this[ 0 ] which will
+ // throw an exception if an attempt to read a data cache is made.
+ if ( elem && value === undefined ) {
+
+ // Attempt to get data from the cache
+ // The key will always be camelCased in Data
+ data = dataUser.get( elem, key );
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // Attempt to "discover" the data in
+ // HTML5 custom data-* attrs
+ data = dataAttr( elem, key );
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // We tried really hard, but the data doesn't exist.
+ return;
+ }
+
+ // Set the data...
+ this.each( function() {
+
+ // We always store the camelCased key
+ dataUser.set( this, key, value );
+ } );
+ }, null, value, arguments.length > 1, null, true );
+ },
+
+ removeData: function( key ) {
+ return this.each( function() {
+ dataUser.remove( this, key );
+ } );
+ }
+} );
+
+
+jQuery.extend( {
+ queue: function( elem, type, data ) {
+ var queue;
+
+ if ( elem ) {
+ type = ( type || "fx" ) + "queue";
+ queue = dataPriv.get( elem, type );
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !queue || Array.isArray( data ) ) {
+ queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
+ } else {
+ queue.push( data );
+ }
+ }
+ return queue || [];
+ }
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ startLength = queue.length,
+ fn = queue.shift(),
+ hooks = jQuery._queueHooks( elem, type ),
+ next = function() {
+ jQuery.dequeue( elem, type );
+ };
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ startLength--;
+ }
+
+ if ( fn ) {
+
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift( "inprogress" );
+ }
+
+ // Clear up the last queue stop function
+ delete hooks.stop;
+ fn.call( elem, next, hooks );
+ }
+
+ if ( !startLength && hooks ) {
+ hooks.empty.fire();
+ }
+ },
+
+ // Not public - generate a queueHooks object, or return the current one
+ _queueHooks: function( elem, type ) {
+ var key = type + "queueHooks";
+ return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
+ empty: jQuery.Callbacks( "once memory" ).add( function() {
+ dataPriv.remove( elem, [ type + "queue", key ] );
+ } )
+ } );
+ }
+} );
+
+jQuery.fn.extend( {
+ queue: function( type, data ) {
+ var setter = 2;
+
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ setter--;
+ }
+
+ if ( arguments.length < setter ) {
+ return jQuery.queue( this[ 0 ], type );
+ }
+
+ return data === undefined ?
+ this :
+ this.each( function() {
+ var queue = jQuery.queue( this, type, data );
+
+ // Ensure a hooks for this queue
+ jQuery._queueHooks( this, type );
+
+ if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ } );
+ },
+ dequeue: function( type ) {
+ return this.each( function() {
+ jQuery.dequeue( this, type );
+ } );
+ },
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ },
+
+ // Get a promise resolved when queues of a certain type
+ // are emptied (fx is the type by default)
+ promise: function( type, obj ) {
+ var tmp,
+ count = 1,
+ defer = jQuery.Deferred(),
+ elements = this,
+ i = this.length,
+ resolve = function() {
+ if ( !( --count ) ) {
+ defer.resolveWith( elements, [ elements ] );
+ }
+ };
+
+ if ( typeof type !== "string" ) {
+ obj = type;
+ type = undefined;
+ }
+ type = type || "fx";
+
+ while ( i-- ) {
+ tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
+ if ( tmp && tmp.empty ) {
+ count++;
+ tmp.empty.add( resolve );
+ }
+ }
+ resolve();
+ return defer.promise( obj );
+ }
+} );
+var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
+
+var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
+
+
+var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
+
+var documentElement = document.documentElement;
+
+
+
+ var isAttached = function( elem ) {
+ return jQuery.contains( elem.ownerDocument, elem );
+ },
+ composed = { composed: true };
+
+ // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
+ // Check attachment across shadow DOM boundaries when possible (gh-3504)
+ // Support: iOS 10.0-10.2 only
+ // Early iOS 10 versions support `attachShadow` but not `getRootNode`,
+ // leading to errors. We need to check for `getRootNode`.
+ if ( documentElement.getRootNode ) {
+ isAttached = function( elem ) {
+ return jQuery.contains( elem.ownerDocument, elem ) ||
+ elem.getRootNode( composed ) === elem.ownerDocument;
+ };
+ }
+var isHiddenWithinTree = function( elem, el ) {
+
+ // isHiddenWithinTree might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+
+ // Inline style trumps all
+ return elem.style.display === "none" ||
+ elem.style.display === "" &&
+
+ // Otherwise, check computed style
+ // Support: Firefox <=43 - 45
+ // Disconnected elements can have computed display: none, so first confirm that elem is
+ // in the document.
+ isAttached( elem ) &&
+
+ jQuery.css( elem, "display" ) === "none";
+ };
+
+
+
+function adjustCSS( elem, prop, valueParts, tween ) {
+ var adjusted, scale,
+ maxIterations = 20,
+ currentValue = tween ?
+ function() {
+ return tween.cur();
+ } :
+ function() {
+ return jQuery.css( elem, prop, "" );
+ },
+ initial = currentValue(),
+ unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+ // Starting value computation is required for potential unit mismatches
+ initialInUnit = elem.nodeType &&
+ ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
+ rcssNum.exec( jQuery.css( elem, prop ) );
+
+ if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
+
+ // Support: Firefox <=54
+ // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
+ initial = initial / 2;
+
+ // Trust units reported by jQuery.css
+ unit = unit || initialInUnit[ 3 ];
+
+ // Iteratively approximate from a nonzero starting point
+ initialInUnit = +initial || 1;
+
+ while ( maxIterations-- ) {
+
+ // Evaluate and update our best guess (doubling guesses that zero out).
+ // Finish if the scale equals or crosses 1 (making the old*new product non-positive).
+ jQuery.style( elem, prop, initialInUnit + unit );
+ if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
+ maxIterations = 0;
+ }
+ initialInUnit = initialInUnit / scale;
+
+ }
+
+ initialInUnit = initialInUnit * 2;
+ jQuery.style( elem, prop, initialInUnit + unit );
+
+ // Make sure we update the tween properties later on
+ valueParts = valueParts || [];
+ }
+
+ if ( valueParts ) {
+ initialInUnit = +initialInUnit || +initial || 0;
+
+ // Apply relative offset (+=/-=) if specified
+ adjusted = valueParts[ 1 ] ?
+ initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+ +valueParts[ 2 ];
+ if ( tween ) {
+ tween.unit = unit;
+ tween.start = initialInUnit;
+ tween.end = adjusted;
+ }
+ }
+ return adjusted;
+}
+
+
+var defaultDisplayMap = {};
+
+function getDefaultDisplay( elem ) {
+ var temp,
+ doc = elem.ownerDocument,
+ nodeName = elem.nodeName,
+ display = defaultDisplayMap[ nodeName ];
+
+ if ( display ) {
+ return display;
+ }
+
+ temp = doc.body.appendChild( doc.createElement( nodeName ) );
+ display = jQuery.css( temp, "display" );
+
+ temp.parentNode.removeChild( temp );
+
+ if ( display === "none" ) {
+ display = "block";
+ }
+ defaultDisplayMap[ nodeName ] = display;
+
+ return display;
+}
+
+function showHide( elements, show ) {
+ var display, elem,
+ values = [],
+ index = 0,
+ length = elements.length;
+
+ // Determine new display value for elements that need to change
+ for ( ; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+
+ display = elem.style.display;
+ if ( show ) {
+
+ // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
+ // check is required in this first loop unless we have a nonempty display value (either
+ // inline or about-to-be-restored)
+ if ( display === "none" ) {
+ values[ index ] = dataPriv.get( elem, "display" ) || null;
+ if ( !values[ index ] ) {
+ elem.style.display = "";
+ }
+ }
+ if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
+ values[ index ] = getDefaultDisplay( elem );
+ }
+ } else {
+ if ( display !== "none" ) {
+ values[ index ] = "none";
+
+ // Remember what we're overwriting
+ dataPriv.set( elem, "display", display );
+ }
+ }
+ }
+
+ // Set the display of the elements in a second loop to avoid constant reflow
+ for ( index = 0; index < length; index++ ) {
+ if ( values[ index ] != null ) {
+ elements[ index ].style.display = values[ index ];
+ }
+ }
+
+ return elements;
+}
+
+jQuery.fn.extend( {
+ show: function() {
+ return showHide( this, true );
+ },
+ hide: function() {
+ return showHide( this );
+ },
+ toggle: function( state ) {
+ if ( typeof state === "boolean" ) {
+ return state ? this.show() : this.hide();
+ }
+
+ return this.each( function() {
+ if ( isHiddenWithinTree( this ) ) {
+ jQuery( this ).show();
+ } else {
+ jQuery( this ).hide();
+ }
+ } );
+ }
+} );
+var rcheckableType = ( /^(?:checkbox|radio)$/i );
+
+var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i );
+
+var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );
+
+
+
+( function() {
+ var fragment = document.createDocumentFragment(),
+ div = fragment.appendChild( document.createElement( "div" ) ),
+ input = document.createElement( "input" );
+
+ // Support: Android 4.0 - 4.3 only
+ // Check state lost if the name is set (#11217)
+ // Support: Windows Web Apps (WWA)
+ // `name` and `type` must use .setAttribute for WWA (#14901)
+ input.setAttribute( "type", "radio" );
+ input.setAttribute( "checked", "checked" );
+ input.setAttribute( "name", "t" );
+
+ div.appendChild( input );
+
+ // Support: Android <=4.1 only
+ // Older WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ // Support: IE <=11 only
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ div.innerHTML = "<textarea>x</textarea>";
+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+
+ // Support: IE <=9 only
+ // IE <=9 replaces <option> tags with their contents when inserted outside of
+ // the select element.
+ div.innerHTML = "<option></option>";
+ support.option = !!div.lastChild;
+} )();
+
+
+// We have to close these tags to support XHTML (#13200)
+var wrapMap = {
+
+ // XHTML parsers do not magically insert elements in the
+ // same way that tag soup parsers do. So we cannot shorten
+ // this by omitting <tbody> or other required elements.
+ thead: [ 1, "<table>", "</table>" ],
+ col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
+ tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+ td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+ _default: [ 0, "", "" ]
+};
+
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// Support: IE <=9 only
+if ( !support.option ) {
+ wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ];
+}
+
+
+function getAll( context, tag ) {
+
+ // Support: IE <=9 - 11 only
+ // Use typeof to avoid zero-argument method invocation on host objects (#15151)
+ var ret;
+
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ ret = context.getElementsByTagName( tag || "*" );
+
+ } else if ( typeof context.querySelectorAll !== "undefined" ) {
+ ret = context.querySelectorAll( tag || "*" );
+
+ } else {
+ ret = [];
+ }
+
+ if ( tag === undefined || tag && nodeName( context, tag ) ) {
+ return jQuery.merge( [ context ], ret );
+ }
+
+ return ret;
+}
+
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+ var i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ dataPriv.set(
+ elems[ i ],
+ "globalEval",
+ !refElements || dataPriv.get( refElements[ i ], "globalEval" )
+ );
+ }
+}
+
+
+var rhtml = /<|&#?\w+;/;
+
+function buildFragment( elems, context, scripts, selection, ignored ) {
+ var elem, tmp, tag, wrap, attached, j,
+ fragment = context.createDocumentFragment(),
+ nodes = [],
+ i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ elem = elems[ i ];
+
+ if ( elem || elem === 0 ) {
+
+ // Add nodes directly
+ if ( toType( elem ) === "object" ) {
+
+ // Support: Android <=4.0 only, PhantomJS 1 only
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
+
+ // Convert non-html into a text node
+ } else if ( !rhtml.test( elem ) ) {
+ nodes.push( context.createTextNode( elem ) );
+
+ // Convert html into DOM nodes
+ } else {
+ tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
+
+ // Deserialize a standard representation
+ tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
+ wrap = wrapMap[ tag ] || wrapMap._default;
+ tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
+
+ // Descend through wrappers to the right content
+ j = wrap[ 0 ];
+ while ( j-- ) {
+ tmp = tmp.lastChild;
+ }
+
+ // Support: Android <=4.0 only, PhantomJS 1 only
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( nodes, tmp.childNodes );
+
+ // Remember the top-level container
+ tmp = fragment.firstChild;
+
+ // Ensure the created nodes are orphaned (#12392)
+ tmp.textContent = "";
+ }
+ }
+ }
+
+ // Remove wrapper from fragment
+ fragment.textContent = "";
+
+ i = 0;
+ while ( ( elem = nodes[ i++ ] ) ) {
+
+ // Skip elements already in the context collection (trac-4087)
+ if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
+ if ( ignored ) {
+ ignored.push( elem );
+ }
+ continue;
+ }
+
+ attached = isAttached( elem );
+
+ // Append to fragment
+ tmp = getAll( fragment.appendChild( elem ), "script" );
+
+ // Preserve script evaluation history
+ if ( attached ) {
+ setGlobalEval( tmp );
+ }
+
+ // Capture executables
+ if ( scripts ) {
+ j = 0;
+ while ( ( elem = tmp[ j++ ] ) ) {
+ if ( rscriptType.test( elem.type || "" ) ) {
+ scripts.push( elem );
+ }
+ }
+ }
+ }
+
+ return fragment;
+}
+
+
+var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
+
+function returnTrue() {
+ return true;
+}
+
+function returnFalse() {
+ return false;
+}
+
+// Support: IE <=9 - 11+
+// focus() and blur() are asynchronous, except when they are no-op.
+// So expect focus to be synchronous when the element is already active,
+// and blur to be synchronous when the element is not already active.
+// (focus and blur are always synchronous in other supported browsers,
+// this just defines when we can count on it).
+function expectSync( elem, type ) {
+ return ( elem === safeActiveElement() ) === ( type === "focus" );
+}
+
+// Support: IE <=9 only
+// Accessing document.activeElement can throw unexpectedly
+// https://bugs.jquery.com/ticket/13393
+function safeActiveElement() {
+ try {
+ return document.activeElement;
+ } catch ( err ) { }
+}
+
+function on( elem, types, selector, data, fn, one ) {
+ var origFn, type;
+
+ // Types can be a map of types/handlers
+ if ( typeof types === "object" ) {
+
+ // ( types-Object, selector, data )
+ if ( typeof selector !== "string" ) {
+
+ // ( types-Object, data )
+ data = data || selector;
+ selector = undefined;
+ }
+ for ( type in types ) {
+ on( elem, type, selector, data, types[ type ], one );
+ }
+ return elem;
+ }
+
+ if ( data == null && fn == null ) {
+
+ // ( types, fn )
+ fn = selector;
+ data = selector = undefined;
+ } else if ( fn == null ) {
+ if ( typeof selector === "string" ) {
+
+ // ( types, selector, fn )
+ fn = data;
+ data = undefined;
+ } else {
+
+ // ( types, data, fn )
+ fn = data;
+ data = selector;
+ selector = undefined;
+ }
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ } else if ( !fn ) {
+ return elem;
+ }
+
+ if ( one === 1 ) {
+ origFn = fn;
+ fn = function( event ) {
+
+ // Can use an empty set, since event contains the info
+ jQuery().off( event );
+ return origFn.apply( this, arguments );
+ };
+
+ // Use same guid so caller can remove using origFn
+ fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
+ }
+ return elem.each( function() {
+ jQuery.event.add( this, types, fn, data, selector );
+ } );
+}
+
+/*
+ * Helper functions for managing events -- not part of the public interface.
+ * Props to Dean Edwards' addEvent library for many of the ideas.
+ */
+jQuery.event = {
+
+ global: {},
+
+ add: function( elem, types, handler, data, selector ) {
+
+ var handleObjIn, eventHandle, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = dataPriv.get( elem );
+
+ // Only attach events to objects that accept data
+ if ( !acceptData( elem ) ) {
+ return;
+ }
+
+ // Caller can pass in an object of custom data in lieu of the handler
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ selector = handleObjIn.selector;
+ }
+
+ // Ensure that invalid selectors throw exceptions at attach time
+ // Evaluate against documentElement in case elem is a non-element node (e.g., document)
+ if ( selector ) {
+ jQuery.find.matchesSelector( documentElement, selector );
+ }
+
+ // Make sure that the handler has a unique ID, used to find/remove it later
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure and main handler, if this is the first
+ if ( !( events = elemData.events ) ) {
+ events = elemData.events = Object.create( null );
+ }
+ if ( !( eventHandle = elemData.handle ) ) {
+ eventHandle = elemData.handle = function( e ) {
+
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
+ jQuery.event.dispatch.apply( elem, arguments ) : undefined;
+ };
+ }
+
+ // Handle multiple events separated by a space
+ types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[ t ] ) || [];
+ type = origType = tmp[ 1 ];
+ namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
+
+ // There *must* be a type, no attaching namespace-only handlers
+ if ( !type ) {
+ continue;
+ }
+
+ // If event changes its type, use the special event handlers for the changed type
+ special = jQuery.event.special[ type ] || {};
+
+ // If selector defined, determine special event api type, otherwise given type
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+
+ // Update special based on newly reset type
+ special = jQuery.event.special[ type ] || {};
+
+ // handleObj is passed to all event handlers
+ handleObj = jQuery.extend( {
+ type: type,
+ origType: origType,
+ data: data,
+ handler: handler,
+ guid: handler.guid,
+ selector: selector,
+ needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
+ namespace: namespaces.join( "." )
+ }, handleObjIn );
+
+ // Init the event handler queue if we're the first
+ if ( !( handlers = events[ type ] ) ) {
+ handlers = events[ type ] = [];
+ handlers.delegateCount = 0;
+
+ // Only use addEventListener if the special events handler returns false
+ if ( !special.setup ||
+ special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add to the element's handler list, delegates in front
+ if ( selector ) {
+ handlers.splice( handlers.delegateCount++, 0, handleObj );
+ } else {
+ handlers.push( handleObj );
+ }
+
+ // Keep track of which events have ever been used, for event optimization
+ jQuery.event.global[ type ] = true;
+ }
+
+ },
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, selector, mappedTypes ) {
+
+ var j, origCount, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
+
+ if ( !elemData || !( events = elemData.events ) ) {
+ return;
+ }
+
+ // Once for each type.namespace in types; type may be omitted
+ types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[ t ] ) || [];
+ type = origType = tmp[ 1 ];
+ namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
+
+ // Unbind all events (on this namespace, if provided) for the element
+ if ( !type ) {
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
+ }
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+ handlers = events[ type ] || [];
+ tmp = tmp[ 2 ] &&
+ new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
+
+ // Remove matching events
+ origCount = j = handlers.length;
+ while ( j-- ) {
+ handleObj = handlers[ j ];
+
+ if ( ( mappedTypes || origType === handleObj.origType ) &&
+ ( !handler || handler.guid === handleObj.guid ) &&
+ ( !tmp || tmp.test( handleObj.namespace ) ) &&
+ ( !selector || selector === handleObj.selector ||
+ selector === "**" && handleObj.selector ) ) {
+ handlers.splice( j, 1 );
+
+ if ( handleObj.selector ) {
+ handlers.delegateCount--;
+ }
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+ }
+
+ // Remove generic event handler if we removed something and no more handlers exist
+ // (avoids potential for endless recursion during removal of special event handlers)
+ if ( origCount && !handlers.length ) {
+ if ( !special.teardown ||
+ special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
+
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ delete events[ type ];
+ }
+ }
+
+ // Remove data and the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ dataPriv.remove( elem, "handle events" );
+ }
+ },
+
+ dispatch: function( nativeEvent ) {
+
+ var i, j, ret, matched, handleObj, handlerQueue,
+ args = new Array( arguments.length ),
+
+ // Make a writable jQuery.Event from the native event object
+ event = jQuery.event.fix( nativeEvent ),
+
+ handlers = (
+ dataPriv.get( this, "events" ) || Object.create( null )
+ )[ event.type ] || [],
+ special = jQuery.event.special[ event.type ] || {};
+
+ // Use the fix-ed jQuery.Event rather than the (read-only) native event
+ args[ 0 ] = event;
+
+ for ( i = 1; i < arguments.length; i++ ) {
+ args[ i ] = arguments[ i ];
+ }
+
+ event.delegateTarget = this;
+
+ // Call the preDispatch hook for the mapped type, and let it bail if desired
+ if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
+ return;
+ }
+
+ // Determine handlers
+ handlerQueue = jQuery.event.handlers.call( this, event, handlers );
+
+ // Run delegates first; they may want to stop propagation beneath us
+ i = 0;
+ while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
+ event.currentTarget = matched.elem;
+
+ j = 0;
+ while ( ( handleObj = matched.handlers[ j++ ] ) &&
+ !event.isImmediatePropagationStopped() ) {
+
+ // If the event is namespaced, then each handler is only invoked if it is
+ // specially universal or its namespaces are a superset of the event's.
+ if ( !event.rnamespace || handleObj.namespace === false ||
+ event.rnamespace.test( handleObj.namespace ) ) {
+
+ event.handleObj = handleObj;
+ event.data = handleObj.data;
+
+ ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
+ handleObj.handler ).apply( matched.elem, args );
+
+ if ( ret !== undefined ) {
+ if ( ( event.result = ret ) === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+ }
+ }
+ }
+
+ // Call the postDispatch hook for the mapped type
+ if ( special.postDispatch ) {
+ special.postDispatch.call( this, event );
+ }
+
+ return event.result;
+ },
+
+ handlers: function( event, handlers ) {
+ var i, handleObj, sel, matchedHandlers, matchedSelectors,
+ handlerQueue = [],
+ delegateCount = handlers.delegateCount,
+ cur = event.target;
+
+ // Find delegate handlers
+ if ( delegateCount &&
+
+ // Support: IE <=9
+ // Black-hole SVG <use> instance trees (trac-13180)
+ cur.nodeType &&
+
+ // Support: Firefox <=42
+ // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
+ // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
+ // Support: IE 11 only
+ // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
+ !( event.type === "click" && event.button >= 1 ) ) {
+
+ for ( ; cur !== this; cur = cur.parentNode || this ) {
+
+ // Don't check non-elements (#13208)
+ // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+ if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
+ matchedHandlers = [];
+ matchedSelectors = {};
+ for ( i = 0; i < delegateCount; i++ ) {
+ handleObj = handlers[ i ];
+
+ // Don't conflict with Object.prototype properties (#13203)
+ sel = handleObj.selector + " ";
+
+ if ( matchedSelectors[ sel ] === undefined ) {
+ matchedSelectors[ sel ] = handleObj.needsContext ?
+ jQuery( sel, this ).index( cur ) > -1 :
+ jQuery.find( sel, this, null, [ cur ] ).length;
+ }
+ if ( matchedSelectors[ sel ] ) {
+ matchedHandlers.push( handleObj );
+ }
+ }
+ if ( matchedHandlers.length ) {
+ handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
+ }
+ }
+ }
+ }
+
+ // Add the remaining (directly-bound) handlers
+ cur = this;
+ if ( delegateCount < handlers.length ) {
+ handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
+ }
+
+ return handlerQueue;
+ },
+
+ addProp: function( name, hook ) {
+ Object.defineProperty( jQuery.Event.prototype, name, {
+ enumerable: true,
+ configurable: true,
+
+ get: isFunction( hook ) ?
+ function() {
+ if ( this.originalEvent ) {
+ return hook( this.originalEvent );
+ }
+ } :
+ function() {
+ if ( this.originalEvent ) {
+ return this.originalEvent[ name ];
+ }
+ },
+
+ set: function( value ) {
+ Object.defineProperty( this, name, {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: value
+ } );
+ }
+ } );
+ },
+
+ fix: function( originalEvent ) {
+ return originalEvent[ jQuery.expando ] ?
+ originalEvent :
+ new jQuery.Event( originalEvent );
+ },
+
+ special: {
+ load: {
+
+ // Prevent triggered image.load events from bubbling to window.load
+ noBubble: true
+ },
+ click: {
+
+ // Utilize native event to ensure correct state for checkable inputs
+ setup: function( data ) {
+
+ // For mutual compressibility with _default, replace `this` access with a local var.
+ // `|| data` is dead code meant only to preserve the variable through minification.
+ var el = this || data;
+
+ // Claim the first handler
+ if ( rcheckableType.test( el.type ) &&
+ el.click && nodeName( el, "input" ) ) {
+
+ // dataPriv.set( el, "click", ... )
+ leverageNative( el, "click", returnTrue );
+ }
+
+ // Return false to allow normal processing in the caller
+ return false;
+ },
+ trigger: function( data ) {
+
+ // For mutual compressibility with _default, replace `this` access with a local var.
+ // `|| data` is dead code meant only to preserve the variable through minification.
+ var el = this || data;
+
+ // Force setup before triggering a click
+ if ( rcheckableType.test( el.type ) &&
+ el.click && nodeName( el, "input" ) ) {
+
+ leverageNative( el, "click" );
+ }
+
+ // Return non-false to allow normal event-path propagation
+ return true;
+ },
+
+ // For cross-browser consistency, suppress native .click() on links
+ // Also prevent it if we're currently inside a leveraged native-event stack
+ _default: function( event ) {
+ var target = event.target;
+ return rcheckableType.test( target.type ) &&
+ target.click && nodeName( target, "input" ) &&
+ dataPriv.get( target, "click" ) ||
+ nodeName( target, "a" );
+ }
+ },
+
+ beforeunload: {
+ postDispatch: function( event ) {
+
+ // Support: Firefox 20+
+ // Firefox doesn't alert if the returnValue field is not set.
+ if ( event.result !== undefined && event.originalEvent ) {
+ event.originalEvent.returnValue = event.result;
+ }
+ }
+ }
+ }
+};
+
+// Ensure the presence of an event listener that handles manually-triggered
+// synthetic events by interrupting progress until reinvoked in response to
+// *native* events that it fires directly, ensuring that state changes have
+// already occurred before other listeners are invoked.
+function leverageNative( el, type, expectSync ) {
+
+ // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
+ if ( !expectSync ) {
+ if ( dataPriv.get( el, type ) === undefined ) {
+ jQuery.event.add( el, type, returnTrue );
+ }
+ return;
+ }
+
+ // Register the controller as a special universal handler for all event namespaces
+ dataPriv.set( el, type, false );
+ jQuery.event.add( el, type, {
+ namespace: false,
+ handler: function( event ) {
+ var notAsync, result,
+ saved = dataPriv.get( this, type );
+
+ if ( ( event.isTrigger & 1 ) && this[ type ] ) {
+
+ // Interrupt processing of the outer synthetic .trigger()ed event
+ // Saved data should be false in such cases, but might be a leftover capture object
+ // from an async native handler (gh-4350)
+ if ( !saved.length ) {
+
+ // Store arguments for use when handling the inner native event
+ // There will always be at least one argument (an event object), so this array
+ // will not be confused with a leftover capture object.
+ saved = slice.call( arguments );
+ dataPriv.set( this, type, saved );
+
+ // Trigger the native event and capture its result
+ // Support: IE <=9 - 11+
+ // focus() and blur() are asynchronous
+ notAsync = expectSync( this, type );
+ this[ type ]();
+ result = dataPriv.get( this, type );
+ if ( saved !== result || notAsync ) {
+ dataPriv.set( this, type, false );
+ } else {
+ result = {};
+ }
+ if ( saved !== result ) {
+
+ // Cancel the outer synthetic event
+ event.stopImmediatePropagation();
+ event.preventDefault();
+
+ // Support: Chrome 86+
+ // In Chrome, if an element having a focusout handler is blurred by
+ // clicking outside of it, it invokes the handler synchronously. If
+ // that handler calls `.remove()` on the element, the data is cleared,
+ // leaving `result` undefined. We need to guard against this.
+ return result && result.value;
+ }
+
+ // If this is an inner synthetic event for an event with a bubbling surrogate
+ // (focus or blur), assume that the surrogate already propagated from triggering the
+ // native event and prevent that from happening again here.
+ // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
+ // bubbling surrogate propagates *after* the non-bubbling base), but that seems
+ // less bad than duplication.
+ } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
+ event.stopPropagation();
+ }
+
+ // If this is a native event triggered above, everything is now in order
+ // Fire an inner synthetic event with the original arguments
+ } else if ( saved.length ) {
+
+ // ...and capture the result
+ dataPriv.set( this, type, {
+ value: jQuery.event.trigger(
+
+ // Support: IE <=9 - 11+
+ // Extend with the prototype to reset the above stopImmediatePropagation()
+ jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),
+ saved.slice( 1 ),
+ this
+ )
+ } );
+
+ // Abort handling of the native event
+ event.stopImmediatePropagation();
+ }
+ }
+ } );
+}
+
+jQuery.removeEvent = function( elem, type, handle ) {
+
+ // This "if" is needed for plain objects
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle );
+ }
+};
+
+jQuery.Event = function( src, props ) {
+
+ // Allow instantiation without the 'new' keyword
+ if ( !( this instanceof jQuery.Event ) ) {
+ return new jQuery.Event( src, props );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = src.defaultPrevented ||
+ src.defaultPrevented === undefined &&
+
+ // Support: Android <=2.3 only
+ src.returnValue === false ?
+ returnTrue :
+ returnFalse;
+
+ // Create target properties
+ // Support: Safari <=6 - 7 only
+ // Target should not be a text node (#504, #13143)
+ this.target = ( src.target && src.target.nodeType === 3 ) ?
+ src.target.parentNode :
+ src.target;
+
+ this.currentTarget = src.currentTarget;
+ this.relatedTarget = src.relatedTarget;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // Create a timestamp if incoming event doesn't have one
+ this.timeStamp = src && src.timeStamp || Date.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ constructor: jQuery.Event,
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse,
+ isSimulated: false,
+
+ preventDefault: function() {
+ var e = this.originalEvent;
+
+ this.isDefaultPrevented = returnTrue;
+
+ if ( e && !this.isSimulated ) {
+ e.preventDefault();
+ }
+ },
+ stopPropagation: function() {
+ var e = this.originalEvent;
+
+ this.isPropagationStopped = returnTrue;
+
+ if ( e && !this.isSimulated ) {
+ e.stopPropagation();
+ }
+ },
+ stopImmediatePropagation: function() {
+ var e = this.originalEvent;
+
+ this.isImmediatePropagationStopped = returnTrue;
+
+ if ( e && !this.isSimulated ) {
+ e.stopImmediatePropagation();
+ }
+
+ this.stopPropagation();
+ }
+};
+
+// Includes all common event props including KeyEvent and MouseEvent specific props
+jQuery.each( {
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ changedTouches: true,
+ ctrlKey: true,
+ detail: true,
+ eventPhase: true,
+ metaKey: true,
+ pageX: true,
+ pageY: true,
+ shiftKey: true,
+ view: true,
+ "char": true,
+ code: true,
+ charCode: true,
+ key: true,
+ keyCode: true,
+ button: true,
+ buttons: true,
+ clientX: true,
+ clientY: true,
+ offsetX: true,
+ offsetY: true,
+ pointerId: true,
+ pointerType: true,
+ screenX: true,
+ screenY: true,
+ targetTouches: true,
+ toElement: true,
+ touches: true,
+ which: true
+}, jQuery.event.addProp );
+
+jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
+ jQuery.event.special[ type ] = {
+
+ // Utilize native event if possible so blur/focus sequence is correct
+ setup: function() {
+
+ // Claim the first handler
+ // dataPriv.set( this, "focus", ... )
+ // dataPriv.set( this, "blur", ... )
+ leverageNative( this, type, expectSync );
+
+ // Return false to allow normal processing in the caller
+ return false;
+ },
+ trigger: function() {
+
+ // Force setup before trigger
+ leverageNative( this, type );
+
+ // Return non-false to allow normal event-path propagation
+ return true;
+ },
+
+ // Suppress native focus or blur as it's already being fired
+ // in leverageNative.
+ _default: function() {
+ return true;
+ },
+
+ delegateType: delegateType
+ };
+} );
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// so that event delegation works in jQuery.
+// Do the same for pointerenter/pointerleave and pointerover/pointerout
+//
+// Support: Safari 7 only
+// Safari sends mouseenter too often; see:
+// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
+// for the description of the bug (it existed in older Chrome versions as well).
+jQuery.each( {
+ mouseenter: "mouseover",
+ mouseleave: "mouseout",
+ pointerenter: "pointerover",
+ pointerleave: "pointerout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ delegateType: fix,
+ bindType: fix,
+
+ handle: function( event ) {
+ var ret,
+ target = this,
+ related = event.relatedTarget,
+ handleObj = event.handleObj;
+
+ // For mouseenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
+ event.type = handleObj.origType;
+ ret = handleObj.handler.apply( this, arguments );
+ event.type = fix;
+ }
+ return ret;
+ }
+ };
+} );
+
+jQuery.fn.extend( {
+
+ on: function( types, selector, data, fn ) {
+ return on( this, types, selector, data, fn );
+ },
+ one: function( types, selector, data, fn ) {
+ return on( this, types, selector, data, fn, 1 );
+ },
+ off: function( types, selector, fn ) {
+ var handleObj, type;
+ if ( types && types.preventDefault && types.handleObj ) {
+
+ // ( event ) dispatched jQuery.Event
+ handleObj = types.handleObj;
+ jQuery( types.delegateTarget ).off(
+ handleObj.namespace ?
+ handleObj.origType + "." + handleObj.namespace :
+ handleObj.origType,
+ handleObj.selector,
+ handleObj.handler
+ );
+ return this;
+ }
+ if ( typeof types === "object" ) {
+
+ // ( types-object [, selector] )
+ for ( type in types ) {
+ this.off( type, selector, types[ type ] );
+ }
+ return this;
+ }
+ if ( selector === false || typeof selector === "function" ) {
+
+ // ( types [, fn] )
+ fn = selector;
+ selector = undefined;
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ }
+ return this.each( function() {
+ jQuery.event.remove( this, types, fn, selector );
+ } );
+ }
+} );
+
+
+var
+
+ // Support: IE <=10 - 11, Edge 12 - 13 only
+ // In IE/Edge using regex groups here causes severe slowdowns.
+ // See https://connect.microsoft.com/IE/feedback/details/1736512/
+ rnoInnerhtml = /<script|<style|<link/i,
+
+ // checked="checked" or checked
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+ rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
+
+// Prefer a tbody over its parent table for containing new rows
+function manipulationTarget( elem, content ) {
+ if ( nodeName( elem, "table" ) &&
+ nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
+
+ return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
+ }
+
+ return elem;
+}
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+function disableScript( elem ) {
+ elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
+ return elem;
+}
+function restoreScript( elem ) {
+ if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
+ elem.type = elem.type.slice( 5 );
+ } else {
+ elem.removeAttribute( "type" );
+ }
+
+ return elem;
+}
+
+function cloneCopyEvent( src, dest ) {
+ var i, l, type, pdataOld, udataOld, udataCur, events;
+
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ // 1. Copy private data: events, handlers, etc.
+ if ( dataPriv.hasData( src ) ) {
+ pdataOld = dataPriv.get( src );
+ events = pdataOld.events;
+
+ if ( events ) {
+ dataPriv.remove( dest, "handle events" );
+
+ for ( type in events ) {
+ for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ] );
+ }
+ }
+ }
+ }
+
+ // 2. Copy user data
+ if ( dataUser.hasData( src ) ) {
+ udataOld = dataUser.access( src );
+ udataCur = jQuery.extend( {}, udataOld );
+
+ dataUser.set( dest, udataCur );
+ }
+}
+
+// Fix IE bugs, see support tests
+function fixInput( src, dest ) {
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // Fails to persist the checked state of a cloned checkbox or radio button.
+ if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
+ dest.checked = src.checked;
+
+ // Fails to return the selected option to the default selected state when cloning options
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+}
+
+function domManip( collection, args, callback, ignored ) {
+
+ // Flatten any nested arrays
+ args = flat( args );
+
+ var fragment, first, scripts, hasScripts, node, doc,
+ i = 0,
+ l = collection.length,
+ iNoClone = l - 1,
+ value = args[ 0 ],
+ valueIsFunction = isFunction( value );
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( valueIsFunction ||
+ ( l > 1 && typeof value === "string" &&
+ !support.checkClone && rchecked.test( value ) ) ) {
+ return collection.each( function( index ) {
+ var self = collection.eq( index );
+ if ( valueIsFunction ) {
+ args[ 0 ] = value.call( this, index, self.html() );
+ }
+ domManip( self, args, callback, ignored );
+ } );
+ }
+
+ if ( l ) {
+ fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
+ first = fragment.firstChild;
+
+ if ( fragment.childNodes.length === 1 ) {
+ fragment = first;
+ }
+
+ // Require either new content or an interest in ignored elements to invoke the callback
+ if ( first || ignored ) {
+ scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
+ hasScripts = scripts.length;
+
+ // Use the original fragment for the last item
+ // instead of the first because it can end up
+ // being emptied incorrectly in certain situations (#8070).
+ for ( ; i < l; i++ ) {
+ node = fragment;
+
+ if ( i !== iNoClone ) {
+ node = jQuery.clone( node, true, true );
+
+ // Keep references to cloned scripts for later restoration
+ if ( hasScripts ) {
+
+ // Support: Android <=4.0 only, PhantomJS 1 only
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( scripts, getAll( node, "script" ) );
+ }
+ }
+
+ callback.call( collection[ i ], node, i );
+ }
+
+ if ( hasScripts ) {
+ doc = scripts[ scripts.length - 1 ].ownerDocument;
+
+ // Reenable scripts
+ jQuery.map( scripts, restoreScript );
+
+ // Evaluate executable scripts on first document insertion
+ for ( i = 0; i < hasScripts; i++ ) {
+ node = scripts[ i ];
+ if ( rscriptType.test( node.type || "" ) &&
+ !dataPriv.access( node, "globalEval" ) &&
+ jQuery.contains( doc, node ) ) {
+
+ if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) {
+
+ // Optional AJAX dependency, but won't run scripts if not present
+ if ( jQuery._evalUrl && !node.noModule ) {
+ jQuery._evalUrl( node.src, {
+ nonce: node.nonce || node.getAttribute( "nonce" )
+ }, doc );
+ }
+ } else {
+ DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return collection;
+}
+
+function remove( elem, selector, keepData ) {
+ var node,
+ nodes = selector ? jQuery.filter( selector, elem ) : elem,
+ i = 0;
+
+ for ( ; ( node = nodes[ i ] ) != null; i++ ) {
+ if ( !keepData && node.nodeType === 1 ) {
+ jQuery.cleanData( getAll( node ) );
+ }
+
+ if ( node.parentNode ) {
+ if ( keepData && isAttached( node ) ) {
+ setGlobalEval( getAll( node, "script" ) );
+ }
+ node.parentNode.removeChild( node );
+ }
+ }
+
+ return elem;
+}
+
+jQuery.extend( {
+ htmlPrefilter: function( html ) {
+ return html;
+ },
+
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var i, l, srcElements, destElements,
+ clone = elem.cloneNode( true ),
+ inPage = isAttached( elem );
+
+ // Fix IE cloning issues
+ if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
+ !jQuery.isXMLDoc( elem ) ) {
+
+ // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
+ destElements = getAll( clone );
+ srcElements = getAll( elem );
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ fixInput( srcElements[ i ], destElements[ i ] );
+ }
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+ if ( deepDataAndEvents ) {
+ srcElements = srcElements || getAll( elem );
+ destElements = destElements || getAll( clone );
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ cloneCopyEvent( srcElements[ i ], destElements[ i ] );
+ }
+ } else {
+ cloneCopyEvent( elem, clone );
+ }
+ }
+
+ // Preserve script evaluation history
+ destElements = getAll( clone, "script" );
+ if ( destElements.length > 0 ) {
+ setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+ }
+
+ // Return the cloned set
+ return clone;
+ },
+
+ cleanData: function( elems ) {
+ var data, elem, type,
+ special = jQuery.event.special,
+ i = 0;
+
+ for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
+ if ( acceptData( elem ) ) {
+ if ( ( data = elem[ dataPriv.expando ] ) ) {
+ if ( data.events ) {
+ for ( type in data.events ) {
+ if ( special[ type ] ) {
+ jQuery.event.remove( elem, type );
+
+ // This is a shortcut to avoid jQuery.event.remove's overhead
+ } else {
+ jQuery.removeEvent( elem, type, data.handle );
+ }
+ }
+ }
+
+ // Support: Chrome <=35 - 45+
+ // Assign undefined instead of using delete, see Data#remove
+ elem[ dataPriv.expando ] = undefined;
+ }
+ if ( elem[ dataUser.expando ] ) {
+
+ // Support: Chrome <=35 - 45+
+ // Assign undefined instead of using delete, see Data#remove
+ elem[ dataUser.expando ] = undefined;
+ }
+ }
+ }
+ }
+} );
+
+jQuery.fn.extend( {
+ detach: function( selector ) {
+ return remove( this, selector, true );
+ },
+
+ remove: function( selector ) {
+ return remove( this, selector );
+ },
+
+ text: function( value ) {
+ return access( this, function( value ) {
+ return value === undefined ?
+ jQuery.text( this ) :
+ this.empty().each( function() {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ this.textContent = value;
+ }
+ } );
+ }, null, value, arguments.length );
+ },
+
+ append: function() {
+ return domManip( this, arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.appendChild( elem );
+ }
+ } );
+ },
+
+ prepend: function() {
+ return domManip( this, arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.insertBefore( elem, target.firstChild );
+ }
+ } );
+ },
+
+ before: function() {
+ return domManip( this, arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this );
+ }
+ } );
+ },
+
+ after: function() {
+ return domManip( this, arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ }
+ } );
+ },
+
+ empty: function() {
+ var elem,
+ i = 0;
+
+ for ( ; ( elem = this[ i ] ) != null; i++ ) {
+ if ( elem.nodeType === 1 ) {
+
+ // Prevent memory leaks
+ jQuery.cleanData( getAll( elem, false ) );
+
+ // Remove any remaining nodes
+ elem.textContent = "";
+ }
+ }
+
+ return this;
+ },
+
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+ return this.map( function() {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ } );
+ },
+
+ html: function( value ) {
+ return access( this, function( value ) {
+ var elem = this[ 0 ] || {},
+ i = 0,
+ l = this.length;
+
+ if ( value === undefined && elem.nodeType === 1 ) {
+ return elem.innerHTML;
+ }
+
+ // See if we can take a shortcut and just use innerHTML
+ if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+ !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
+
+ value = jQuery.htmlPrefilter( value );
+
+ try {
+ for ( ; i < l; i++ ) {
+ elem = this[ i ] || {};
+
+ // Remove element nodes and prevent memory leaks
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem, false ) );
+ elem.innerHTML = value;
+ }
+ }
+
+ elem = 0;
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch ( e ) {}
+ }
+
+ if ( elem ) {
+ this.empty().append( value );
+ }
+ }, null, value, arguments.length );
+ },
+
+ replaceWith: function() {
+ var ignored = [];
+
+ // Make the changes, replacing each non-ignored context element with the new content
+ return domManip( this, arguments, function( elem ) {
+ var parent = this.parentNode;
+
+ if ( jQuery.inArray( this, ignored ) < 0 ) {
+ jQuery.cleanData( getAll( this ) );
+ if ( parent ) {
+ parent.replaceChild( elem, this );
+ }
+ }
+
+ // Force callback invocation
+ }, ignored );
+ }
+} );
+
+jQuery.each( {
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function( name, original ) {
+ jQuery.fn[ name ] = function( selector ) {
+ var elems,
+ ret = [],
+ insert = jQuery( selector ),
+ last = insert.length - 1,
+ i = 0;
+
+ for ( ; i <= last; i++ ) {
+ elems = i === last ? this : this.clone( true );
+ jQuery( insert[ i ] )[ original ]( elems );
+
+ // Support: Android <=4.0 only, PhantomJS 1 only
+ // .get() because push.apply(_, arraylike) throws on ancient WebKit
+ push.apply( ret, elems.get() );
+ }
+
+ return this.pushStack( ret );
+ };
+} );
+var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
+
+var getStyles = function( elem ) {
+
+ // Support: IE <=11 only, Firefox <=30 (#15098, #14150)
+ // IE throws on elements created in popups
+ // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
+ var view = elem.ownerDocument.defaultView;
+
+ if ( !view || !view.opener ) {
+ view = window;
+ }
+
+ return view.getComputedStyle( elem );
+ };
+
+var swap = function( elem, options, callback ) {
+ var ret, name,
+ old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ ret = callback.call( elem );
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+
+ return ret;
+};
+
+
+var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );
+
+
+
+( function() {
+
+ // Executing both pixelPosition & boxSizingReliable tests require only one layout
+ // so they're executed at the same time to save the second computation.
+ function computeStyleTests() {
+
+ // This is a singleton, we need to execute it only once
+ if ( !div ) {
+ return;
+ }
+
+ container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
+ "margin-top:1px;padding:0;border:0";
+ div.style.cssText =
+ "position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
+ "margin:auto;border:1px;padding:1px;" +
+ "width:60%;top:1%";
+ documentElement.appendChild( container ).appendChild( div );
+
+ var divStyle = window.getComputedStyle( div );
+ pixelPositionVal = divStyle.top !== "1%";
+
+ // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
+ reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;
+
+ // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
+ // Some styles come back with percentage values, even though they shouldn't
+ div.style.right = "60%";
+ pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;
+
+ // Support: IE 9 - 11 only
+ // Detect misreporting of content dimensions for box-sizing:border-box elements
+ boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;
+
+ // Support: IE 9 only
+ // Detect overflow:scroll screwiness (gh-3699)
+ // Support: Chrome <=64
+ // Don't get tricked when zoom affects offsetWidth (gh-4029)
+ div.style.position = "absolute";
+ scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;
+
+ documentElement.removeChild( container );
+
+ // Nullify the div so it wouldn't be stored in the memory and
+ // it will also be a sign that checks already performed
+ div = null;
+ }
+
+ function roundPixelMeasures( measure ) {
+ return Math.round( parseFloat( measure ) );
+ }
+
+ var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
+ reliableTrDimensionsVal, reliableMarginLeftVal,
+ container = document.createElement( "div" ),
+ div = document.createElement( "div" );
+
+ // Finish early in limited (non-browser) environments
+ if ( !div.style ) {
+ return;
+ }
+
+ // Support: IE <=9 - 11 only
+ // Style of cloned element affects source element cloned (#8908)
+ div.style.backgroundClip = "content-box";
+ div.cloneNode( true ).style.backgroundClip = "";
+ support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+ jQuery.extend( support, {
+ boxSizingReliable: function() {
+ computeStyleTests();
+ return boxSizingReliableVal;
+ },
+ pixelBoxStyles: function() {
+ computeStyleTests();
+ return pixelBoxStylesVal;
+ },
+ pixelPosition: function() {
+ computeStyleTests();
+ return pixelPositionVal;
+ },
+ reliableMarginLeft: function() {
+ computeStyleTests();
+ return reliableMarginLeftVal;
+ },
+ scrollboxSize: function() {
+ computeStyleTests();
+ return scrollboxSizeVal;
+ },
+
+ // Support: IE 9 - 11+, Edge 15 - 18+
+ // IE/Edge misreport `getComputedStyle` of table rows with width/height
+ // set in CSS while `offset*` properties report correct values.
+ // Behavior in IE 9 is more subtle than in newer versions & it passes
+ // some versions of this test; make sure not to make it pass there!
+ //
+ // Support: Firefox 70+
+ // Only Firefox includes border widths
+ // in computed dimensions. (gh-4529)
+ reliableTrDimensions: function() {
+ var table, tr, trChild, trStyle;
+ if ( reliableTrDimensionsVal == null ) {
+ table = document.createElement( "table" );
+ tr = document.createElement( "tr" );
+ trChild = document.createElement( "div" );
+
+ table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
+ tr.style.cssText = "border:1px solid";
+
+ // Support: Chrome 86+
+ // Height set through cssText does not get applied.
+ // Computed height then comes back as 0.
+ tr.style.height = "1px";
+ trChild.style.height = "9px";
+
+ // Support: Android 8 Chrome 86+
+ // In our bodyBackground.html iframe,
+ // display for all div elements is set to "inline",
+ // which causes a problem only in Android 8 Chrome 86.
+ // Ensuring the div is display: block
+ // gets around this issue.
+ trChild.style.display = "block";
+
+ documentElement
+ .appendChild( table )
+ .appendChild( tr )
+ .appendChild( trChild );
+
+ trStyle = window.getComputedStyle( tr );
+ reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
+ parseInt( trStyle.borderTopWidth, 10 ) +
+ parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;
+
+ documentElement.removeChild( table );
+ }
+ return reliableTrDimensionsVal;
+ }
+ } );
+} )();
+
+
+function curCSS( elem, name, computed ) {
+ var width, minWidth, maxWidth, ret,
+
+ // Support: Firefox 51+
+ // Retrieving style before computed somehow
+ // fixes an issue with getting wrong values
+ // on detached elements
+ style = elem.style;
+
+ computed = computed || getStyles( elem );
+
+ // getPropertyValue is needed for:
+ // .css('filter') (IE 9 only, #12537)
+ // .css('--customProperty) (#3144)
+ if ( computed ) {
+ ret = computed.getPropertyValue( name ) || computed[ name ];
+
+ if ( ret === "" && !isAttached( elem ) ) {
+ ret = jQuery.style( elem, name );
+ }
+
+ // A tribute to the "awesome hack by Dean Edwards"
+ // Android Browser returns percentage for some values,
+ // but width seems to be reliably pixels.
+ // This is against the CSSOM draft spec:
+ // https://drafts.csswg.org/cssom/#resolved-values
+ if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {
+
+ // Remember the original values
+ width = style.width;
+ minWidth = style.minWidth;
+ maxWidth = style.maxWidth;
+
+ // Put in the new values to get a computed value out
+ style.minWidth = style.maxWidth = style.width = ret;
+ ret = computed.width;
+
+ // Revert the changed values
+ style.width = width;
+ style.minWidth = minWidth;
+ style.maxWidth = maxWidth;
+ }
+ }
+
+ return ret !== undefined ?
+
+ // Support: IE <=9 - 11 only
+ // IE returns zIndex value as an integer.
+ ret + "" :
+ ret;
+}
+
+
+function addGetHookIf( conditionFn, hookFn ) {
+
+ // Define the hook, we'll check on the first run if it's really needed.
+ return {
+ get: function() {
+ if ( conditionFn() ) {
+
+ // Hook not needed (or it's not possible to use it due
+ // to missing dependency), remove it.
+ delete this.get;
+ return;
+ }
+
+ // Hook needed; redefine it so that the support test is not executed again.
+ return ( this.get = hookFn ).apply( this, arguments );
+ }
+ };
+}
+
+
+var cssPrefixes = [ "Webkit", "Moz", "ms" ],
+ emptyStyle = document.createElement( "div" ).style,
+ vendorProps = {};
+
+// Return a vendor-prefixed property or undefined
+function vendorPropName( name ) {
+
+ // Check for vendor prefixed names
+ var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
+ i = cssPrefixes.length;
+
+ while ( i-- ) {
+ name = cssPrefixes[ i ] + capName;
+ if ( name in emptyStyle ) {
+ return name;
+ }
+ }
+}
+
+// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
+function finalPropName( name ) {
+ var final = jQuery.cssProps[ name ] || vendorProps[ name ];
+
+ if ( final ) {
+ return final;
+ }
+ if ( name in emptyStyle ) {
+ return name;
+ }
+ return vendorProps[ name ] = vendorPropName( name ) || name;
+}
+
+
+var
+
+ // Swappable if display is none or starts with table
+ // except "table", "table-cell", or "table-caption"
+ // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
+ rdisplayswap = /^(none|table(?!-c[ea]).+)/,
+ rcustomProp = /^--/,
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssNormalTransform = {
+ letterSpacing: "0",
+ fontWeight: "400"
+ };
+
+function setPositiveNumber( _elem, value, subtract ) {
+
+ // Any relative (+/-) values have already been
+ // normalized at this point
+ var matches = rcssNum.exec( value );
+ return matches ?
+
+ // Guard against undefined "subtract", e.g., when used as in cssHooks
+ Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
+ value;
+}
+
+function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
+ var i = dimension === "width" ? 1 : 0,
+ extra = 0,
+ delta = 0;
+
+ // Adjustment may not be necessary
+ if ( box === ( isBorderBox ? "border" : "content" ) ) {
+ return 0;
+ }
+
+ for ( ; i < 4; i += 2 ) {
+
+ // Both box models exclude margin
+ if ( box === "margin" ) {
+ delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
+ }
+
+ // If we get here with a content-box, we're seeking "padding" or "border" or "margin"
+ if ( !isBorderBox ) {
+
+ // Add padding
+ delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+
+ // For "border" or "margin", add border
+ if ( box !== "padding" ) {
+ delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+
+ // But still keep track of it otherwise
+ } else {
+ extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+
+ // If we get here with a border-box (content + padding + border), we're seeking "content" or
+ // "padding" or "margin"
+ } else {
+
+ // For "content", subtract padding
+ if ( box === "content" ) {
+ delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+ }
+
+ // For "content" or "padding", subtract border
+ if ( box !== "margin" ) {
+ delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+ }
+ }
+
+ // Account for positive content-box scroll gutter when requested by providing computedVal
+ if ( !isBorderBox && computedVal >= 0 ) {
+
+ // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
+ // Assuming integer scroll gutter, subtract the rest and round down
+ delta += Math.max( 0, Math.ceil(
+ elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
+ computedVal -
+ delta -
+ extra -
+ 0.5
+
+ // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
+ // Use an explicit zero to avoid NaN (gh-3964)
+ ) ) || 0;
+ }
+
+ return delta;
+}
+
+function getWidthOrHeight( elem, dimension, extra ) {
+
+ // Start with computed style
+ var styles = getStyles( elem ),
+
+ // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
+ // Fake content-box until we know it's needed to know the true value.
+ boxSizingNeeded = !support.boxSizingReliable() || extra,
+ isBorderBox = boxSizingNeeded &&
+ jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+ valueIsBorderBox = isBorderBox,
+
+ val = curCSS( elem, dimension, styles ),
+ offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );
+
+ // Support: Firefox <=54
+ // Return a confounding non-pixel value or feign ignorance, as appropriate.
+ if ( rnumnonpx.test( val ) ) {
+ if ( !extra ) {
+ return val;
+ }
+ val = "auto";
+ }
+
+
+ // Support: IE 9 - 11 only
+ // Use offsetWidth/offsetHeight for when box sizing is unreliable.
+ // In those cases, the computed value can be trusted to be border-box.
+ if ( ( !support.boxSizingReliable() && isBorderBox ||
+
+ // Support: IE 10 - 11+, Edge 15 - 18+
+ // IE/Edge misreport `getComputedStyle` of table rows with width/height
+ // set in CSS while `offset*` properties report correct values.
+ // Interestingly, in some cases IE 9 doesn't suffer from this issue.
+ !support.reliableTrDimensions() && nodeName( elem, "tr" ) ||
+
+ // Fall back to offsetWidth/offsetHeight when value is "auto"
+ // This happens for inline elements with no explicit setting (gh-3571)
+ val === "auto" ||
+
+ // Support: Android <=4.1 - 4.3 only
+ // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
+ !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&
+
+ // Make sure the element is visible & connected
+ elem.getClientRects().length ) {
+
+ isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
+
+ // Where available, offsetWidth/offsetHeight approximate border box dimensions.
+ // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
+ // retrieved value as a content box dimension.
+ valueIsBorderBox = offsetProp in elem;
+ if ( valueIsBorderBox ) {
+ val = elem[ offsetProp ];
+ }
+ }
+
+ // Normalize "" and auto
+ val = parseFloat( val ) || 0;
+
+ // Adjust for the element's box model
+ return ( val +
+ boxModelAdjustment(
+ elem,
+ dimension,
+ extra || ( isBorderBox ? "border" : "content" ),
+ valueIsBorderBox,
+ styles,
+
+ // Provide the current computed size to request scroll gutter calculation (gh-3589)
+ val
+ )
+ ) + "px";
+}
+
+jQuery.extend( {
+
+ // Add in style property hooks for overriding the default
+ // behavior of getting and setting a style property
+ cssHooks: {
+ opacity: {
+ get: function( elem, computed ) {
+ if ( computed ) {
+
+ // We should always get a number back from opacity
+ var ret = curCSS( elem, "opacity" );
+ return ret === "" ? "1" : ret;
+ }
+ }
+ }
+ },
+
+ // Don't automatically add "px" to these possibly-unitless properties
+ cssNumber: {
+ "animationIterationCount": true,
+ "columnCount": true,
+ "fillOpacity": true,
+ "flexGrow": true,
+ "flexShrink": true,
+ "fontWeight": true,
+ "gridArea": true,
+ "gridColumn": true,
+ "gridColumnEnd": true,
+ "gridColumnStart": true,
+ "gridRow": true,
+ "gridRowEnd": true,
+ "gridRowStart": true,
+ "lineHeight": true,
+ "opacity": true,
+ "order": true,
+ "orphans": true,
+ "widows": true,
+ "zIndex": true,
+ "zoom": true
+ },
+
+ // Add in properties whose names you wish to fix before
+ // setting or getting the value
+ cssProps: {},
+
+ // Get and set the style property on a DOM Node
+ style: function( elem, name, value, extra ) {
+
+ // Don't set styles on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+ return;
+ }
+
+ // Make sure that we're working with the right name
+ var ret, type, hooks,
+ origName = camelCase( name ),
+ isCustomProp = rcustomProp.test( name ),
+ style = elem.style;
+
+ // Make sure that we're working with the right name. We don't
+ // want to query the value if it is a CSS custom property
+ // since they are user-defined.
+ if ( !isCustomProp ) {
+ name = finalPropName( origName );
+ }
+
+ // Gets hook for the prefixed version, then unprefixed version
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // Check if we're setting a value
+ if ( value !== undefined ) {
+ type = typeof value;
+
+ // Convert "+=" or "-=" to relative numbers (#7345)
+ if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
+ value = adjustCSS( elem, name, ret );
+
+ // Fixes bug #9237
+ type = "number";
+ }
+
+ // Make sure that null and NaN values aren't set (#7116)
+ if ( value == null || value !== value ) {
+ return;
+ }
+
+ // If a number was passed in, add the unit (except for certain CSS properties)
+ // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
+ // "px" to a few hardcoded values.
+ if ( type === "number" && !isCustomProp ) {
+ value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
+ }
+
+ // background-* props affect original clone's values
+ if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
+ style[ name ] = "inherit";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !( "set" in hooks ) ||
+ ( value = hooks.set( elem, value, extra ) ) !== undefined ) {
+
+ if ( isCustomProp ) {
+ style.setProperty( name, value );
+ } else {
+ style[ name ] = value;
+ }
+ }
+
+ } else {
+
+ // If a hook was provided get the non-computed value from there
+ if ( hooks && "get" in hooks &&
+ ( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
+
+ return ret;
+ }
+
+ // Otherwise just get the value from the style object
+ return style[ name ];
+ }
+ },
+
+ css: function( elem, name, extra, styles ) {
+ var val, num, hooks,
+ origName = camelCase( name ),
+ isCustomProp = rcustomProp.test( name );
+
+ // Make sure that we're working with the right name. We don't
+ // want to modify the value if it is a CSS custom property
+ // since they are user-defined.
+ if ( !isCustomProp ) {
+ name = finalPropName( origName );
+ }
+
+ // Try prefixed name followed by the unprefixed name
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // If a hook was provided get the computed value from there
+ if ( hooks && "get" in hooks ) {
+ val = hooks.get( elem, true, extra );
+ }
+
+ // Otherwise, if a way to get the computed value exists, use that
+ if ( val === undefined ) {
+ val = curCSS( elem, name, styles );
+ }
+
+ // Convert "normal" to computed value
+ if ( val === "normal" && name in cssNormalTransform ) {
+ val = cssNormalTransform[ name ];
+ }
+
+ // Make numeric if forced or a qualifier was provided and val looks numeric
+ if ( extra === "" || extra ) {
+ num = parseFloat( val );
+ return extra === true || isFinite( num ) ? num || 0 : val;
+ }
+
+ return val;
+ }
+} );
+
+jQuery.each( [ "height", "width" ], function( _i, dimension ) {
+ jQuery.cssHooks[ dimension ] = {
+ get: function( elem, computed, extra ) {
+ if ( computed ) {
+
+ // Certain elements can have dimension info if we invisibly show them
+ // but it must have a current display style that would benefit
+ return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
+
+ // Support: Safari 8+
+ // Table columns in Safari have non-zero offsetWidth & zero
+ // getBoundingClientRect().width unless display is changed.
+ // Support: IE <=11 only
+ // Running getBoundingClientRect on a disconnected node
+ // in IE throws an error.
+ ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
+ swap( elem, cssShow, function() {
+ return getWidthOrHeight( elem, dimension, extra );
+ } ) :
+ getWidthOrHeight( elem, dimension, extra );
+ }
+ },
+
+ set: function( elem, value, extra ) {
+ var matches,
+ styles = getStyles( elem ),
+
+ // Only read styles.position if the test has a chance to fail
+ // to avoid forcing a reflow.
+ scrollboxSizeBuggy = !support.scrollboxSize() &&
+ styles.position === "absolute",
+
+ // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
+ boxSizingNeeded = scrollboxSizeBuggy || extra,
+ isBorderBox = boxSizingNeeded &&
+ jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+ subtract = extra ?
+ boxModelAdjustment(
+ elem,
+ dimension,
+ extra,
+ isBorderBox,
+ styles
+ ) :
+ 0;
+
+ // Account for unreliable border-box dimensions by comparing offset* to computed and
+ // faking a content-box to get border and padding (gh-3699)
+ if ( isBorderBox && scrollboxSizeBuggy ) {
+ subtract -= Math.ceil(
+ elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
+ parseFloat( styles[ dimension ] ) -
+ boxModelAdjustment( elem, dimension, "border", false, styles ) -
+ 0.5
+ );
+ }
+
+ // Convert to pixels if value adjustment is needed
+ if ( subtract && ( matches = rcssNum.exec( value ) ) &&
+ ( matches[ 3 ] || "px" ) !== "px" ) {
+
+ elem.style[ dimension ] = value;
+ value = jQuery.css( elem, dimension );
+ }
+
+ return setPositiveNumber( elem, value, subtract );
+ }
+ };
+} );
+
+jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
+ function( elem, computed ) {
+ if ( computed ) {
+ return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
+ elem.getBoundingClientRect().left -
+ swap( elem, { marginLeft: 0 }, function() {
+ return elem.getBoundingClientRect().left;
+ } )
+ ) + "px";
+ }
+ }
+);
+
+// These hooks are used by animate to expand properties
+jQuery.each( {
+ margin: "",
+ padding: "",
+ border: "Width"
+}, function( prefix, suffix ) {
+ jQuery.cssHooks[ prefix + suffix ] = {
+ expand: function( value ) {
+ var i = 0,
+ expanded = {},
+
+ // Assumes a single number if not a string
+ parts = typeof value === "string" ? value.split( " " ) : [ value ];
+
+ for ( ; i < 4; i++ ) {
+ expanded[ prefix + cssExpand[ i ] + suffix ] =
+ parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
+ }
+
+ return expanded;
+ }
+ };
+
+ if ( prefix !== "margin" ) {
+ jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
+ }
+} );
+
+jQuery.fn.extend( {
+ css: function( name, value ) {
+ return access( this, function( elem, name, value ) {
+ var styles, len,
+ map = {},
+ i = 0;
+
+ if ( Array.isArray( name ) ) {
+ styles = getStyles( elem );
+ len = name.length;
+
+ for ( ; i < len; i++ ) {
+ map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
+ }
+
+ return map;
+ }
+
+ return value !== undefined ?
+ jQuery.style( elem, name, value ) :
+ jQuery.css( elem, name );
+ }, name, value, arguments.length > 1 );
+ }
+} );
+
+
+function Tween( elem, options, prop, end, easing ) {
+ return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+ constructor: Tween,
+ init: function( elem, options, prop, end, easing, unit ) {
+ this.elem = elem;
+ this.prop = prop;
+ this.easing = easing || jQuery.easing._default;
+ this.options = options;
+ this.start = this.now = this.cur();
+ this.end = end;
+ this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+ },
+ cur: function() {
+ var hooks = Tween.propHooks[ this.prop ];
+
+ return hooks && hooks.get ?
+ hooks.get( this ) :
+ Tween.propHooks._default.get( this );
+ },
+ run: function( percent ) {
+ var eased,
+ hooks = Tween.propHooks[ this.prop ];
+
+ if ( this.options.duration ) {
+ this.pos = eased = jQuery.easing[ this.easing ](
+ percent, this.options.duration * percent, 0, 1, this.options.duration
+ );
+ } else {
+ this.pos = eased = percent;
+ }
+ this.now = ( this.end - this.start ) * eased + this.start;
+
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ if ( hooks && hooks.set ) {
+ hooks.set( this );
+ } else {
+ Tween.propHooks._default.set( this );
+ }
+ return this;
+ }
+};
+
+Tween.prototype.init.prototype = Tween.prototype;
+
+Tween.propHooks = {
+ _default: {
+ get: function( tween ) {
+ var result;
+
+ // Use a property on the element directly when it is not a DOM element,
+ // or when there is no matching style property that exists.
+ if ( tween.elem.nodeType !== 1 ||
+ tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
+ return tween.elem[ tween.prop ];
+ }
+
+ // Passing an empty string as a 3rd parameter to .css will automatically
+ // attempt a parseFloat and fallback to a string if the parse fails.
+ // Simple values such as "10px" are parsed to Float;
+ // complex values such as "rotate(1rad)" are returned as-is.
+ result = jQuery.css( tween.elem, tween.prop, "" );
+
+ // Empty strings, null, undefined and "auto" are converted to 0.
+ return !result || result === "auto" ? 0 : result;
+ },
+ set: function( tween ) {
+
+ // Use step hook for back compat.
+ // Use cssHook if its there.
+ // Use .style if available and use plain properties where available.
+ if ( jQuery.fx.step[ tween.prop ] ) {
+ jQuery.fx.step[ tween.prop ]( tween );
+ } else if ( tween.elem.nodeType === 1 && (
+ jQuery.cssHooks[ tween.prop ] ||
+ tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
+ jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
+ } else {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+ }
+};
+
+// Support: IE <=9 only
+// Panic based approach to setting things on disconnected nodes
+Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
+ set: function( tween ) {
+ if ( tween.elem.nodeType && tween.elem.parentNode ) {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+};
+
+jQuery.easing = {
+ linear: function( p ) {
+ return p;
+ },
+ swing: function( p ) {
+ return 0.5 - Math.cos( p * Math.PI ) / 2;
+ },
+ _default: "swing"
+};
+
+jQuery.fx = Tween.prototype.init;
+
+// Back compat <1.8 extension point
+jQuery.fx.step = {};
+
+
+
+
+var
+ fxNow, inProgress,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rrun = /queueHooks$/;
+
+function schedule() {
+ if ( inProgress ) {
+ if ( document.hidden === false && window.requestAnimationFrame ) {
+ window.requestAnimationFrame( schedule );
+ } else {
+ window.setTimeout( schedule, jQuery.fx.interval );
+ }
+
+ jQuery.fx.tick();
+ }
+}
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+ window.setTimeout( function() {
+ fxNow = undefined;
+ } );
+ return ( fxNow = Date.now() );
+}
+
+// Generate parameters to create a standard animation
+function genFx( type, includeWidth ) {
+ var which,
+ i = 0,
+ attrs = { height: type };
+
+ // If we include width, step value is 1 to do all cssExpand values,
+ // otherwise step value is 2 to skip over Left and Right
+ includeWidth = includeWidth ? 1 : 0;
+ for ( ; i < 4; i += 2 - includeWidth ) {
+ which = cssExpand[ i ];
+ attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
+ }
+
+ if ( includeWidth ) {
+ attrs.opacity = attrs.width = type;
+ }
+
+ return attrs;
+}
+
+function createTween( value, prop, animation ) {
+ var tween,
+ collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
+ index = 0,
+ length = collection.length;
+ for ( ; index < length; index++ ) {
+ if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
+
+ // We're done with this property
+ return tween;
+ }
+ }
+}
+
+function defaultPrefilter( elem, props, opts ) {
+ var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
+ isBox = "width" in props || "height" in props,
+ anim = this,
+ orig = {},
+ style = elem.style,
+ hidden = elem.nodeType && isHiddenWithinTree( elem ),
+ dataShow = dataPriv.get( elem, "fxshow" );
+
+ // Queue-skipping animations hijack the fx hooks
+ if ( !opts.queue ) {
+ hooks = jQuery._queueHooks( elem, "fx" );
+ if ( hooks.unqueued == null ) {
+ hooks.unqueued = 0;
+ oldfire = hooks.empty.fire;
+ hooks.empty.fire = function() {
+ if ( !hooks.unqueued ) {
+ oldfire();
+ }
+ };
+ }
+ hooks.unqueued++;
+
+ anim.always( function() {
+
+ // Ensure the complete handler is called before this completes
+ anim.always( function() {
+ hooks.unqueued--;
+ if ( !jQuery.queue( elem, "fx" ).length ) {
+ hooks.empty.fire();
+ }
+ } );
+ } );
+ }
+
+ // Detect show/hide animations
+ for ( prop in props ) {
+ value = props[ prop ];
+ if ( rfxtypes.test( value ) ) {
+ delete props[ prop ];
+ toggle = toggle || value === "toggle";
+ if ( value === ( hidden ? "hide" : "show" ) ) {
+
+ // Pretend to be hidden if this is a "show" and
+ // there is still data from a stopped show/hide
+ if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
+ hidden = true;
+
+ // Ignore all other no-op show/hide data
+ } else {
+ continue;
+ }
+ }
+ orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
+ }
+ }
+
+ // Bail out if this is a no-op like .hide().hide()
+ propTween = !jQuery.isEmptyObject( props );
+ if ( !propTween && jQuery.isEmptyObject( orig ) ) {
+ return;
+ }
+
+ // Restrict "overflow" and "display" styles during box animations
+ if ( isBox && elem.nodeType === 1 ) {
+
+ // Support: IE <=9 - 11, Edge 12 - 15
+ // Record all 3 overflow attributes because IE does not infer the shorthand
+ // from identically-valued overflowX and overflowY and Edge just mirrors
+ // the overflowX value there.
+ opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
+
+ // Identify a display type, preferring old show/hide data over the CSS cascade
+ restoreDisplay = dataShow && dataShow.display;
+ if ( restoreDisplay == null ) {
+ restoreDisplay = dataPriv.get( elem, "display" );
+ }
+ display = jQuery.css( elem, "display" );
+ if ( display === "none" ) {
+ if ( restoreDisplay ) {
+ display = restoreDisplay;
+ } else {
+
+ // Get nonempty value(s) by temporarily forcing visibility
+ showHide( [ elem ], true );
+ restoreDisplay = elem.style.display || restoreDisplay;
+ display = jQuery.css( elem, "display" );
+ showHide( [ elem ] );
+ }
+ }
+
+ // Animate inline elements as inline-block
+ if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
+ if ( jQuery.css( elem, "float" ) === "none" ) {
+
+ // Restore the original display value at the end of pure show/hide animations
+ if ( !propTween ) {
+ anim.done( function() {
+ style.display = restoreDisplay;
+ } );
+ if ( restoreDisplay == null ) {
+ display = style.display;
+ restoreDisplay = display === "none" ? "" : display;
+ }
+ }
+ style.display = "inline-block";
+ }
+ }
+ }
+
+ if ( opts.overflow ) {
+ style.overflow = "hidden";
+ anim.always( function() {
+ style.overflow = opts.overflow[ 0 ];
+ style.overflowX = opts.overflow[ 1 ];
+ style.overflowY = opts.overflow[ 2 ];
+ } );
+ }
+
+ // Implement show/hide animations
+ propTween = false;
+ for ( prop in orig ) {
+
+ // General show/hide setup for this element animation
+ if ( !propTween ) {
+ if ( dataShow ) {
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+ } else {
+ dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
+ }
+
+ // Store hidden/visible for toggle so `.stop().toggle()` "reverses"
+ if ( toggle ) {
+ dataShow.hidden = !hidden;
+ }
+
+ // Show elements before animating them
+ if ( hidden ) {
+ showHide( [ elem ], true );
+ }
+
+ /* eslint-disable no-loop-func */
+
+ anim.done( function() {
+
+ /* eslint-enable no-loop-func */
+
+ // The final step of a "hide" animation is actually hiding the element
+ if ( !hidden ) {
+ showHide( [ elem ] );
+ }
+ dataPriv.remove( elem, "fxshow" );
+ for ( prop in orig ) {
+ jQuery.style( elem, prop, orig[ prop ] );
+ }
+ } );
+ }
+
+ // Per-property setup
+ propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
+ if ( !( prop in dataShow ) ) {
+ dataShow[ prop ] = propTween.start;
+ if ( hidden ) {
+ propTween.end = propTween.start;
+ propTween.start = 0;
+ }
+ }
+ }
+}
+
+function propFilter( props, specialEasing ) {
+ var index, name, easing, value, hooks;
+
+ // camelCase, specialEasing and expand cssHook pass
+ for ( index in props ) {
+ name = camelCase( index );
+ easing = specialEasing[ name ];
+ value = props[ index ];
+ if ( Array.isArray( value ) ) {
+ easing = value[ 1 ];
+ value = props[ index ] = value[ 0 ];
+ }
+
+ if ( index !== name ) {
+ props[ name ] = value;
+ delete props[ index ];
+ }
+
+ hooks = jQuery.cssHooks[ name ];
+ if ( hooks && "expand" in hooks ) {
+ value = hooks.expand( value );
+ delete props[ name ];
+
+ // Not quite $.extend, this won't overwrite existing keys.
+ // Reusing 'index' because we have the correct "name"
+ for ( index in value ) {
+ if ( !( index in props ) ) {
+ props[ index ] = value[ index ];
+ specialEasing[ index ] = easing;
+ }
+ }
+ } else {
+ specialEasing[ name ] = easing;
+ }
+ }
+}
+
+function Animation( elem, properties, options ) {
+ var result,
+ stopped,
+ index = 0,
+ length = Animation.prefilters.length,
+ deferred = jQuery.Deferred().always( function() {
+
+ // Don't match elem in the :animated selector
+ delete tick.elem;
+ } ),
+ tick = function() {
+ if ( stopped ) {
+ return false;
+ }
+ var currentTime = fxNow || createFxNow(),
+ remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
+
+ // Support: Android 2.3 only
+ // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
+ temp = remaining / animation.duration || 0,
+ percent = 1 - temp,
+ index = 0,
+ length = animation.tweens.length;
+
+ for ( ; index < length; index++ ) {
+ animation.tweens[ index ].run( percent );
+ }
+
+ deferred.notifyWith( elem, [ animation, percent, remaining ] );
+
+ // If there's more to do, yield
+ if ( percent < 1 && length ) {
+ return remaining;
+ }
+
+ // If this was an empty animation, synthesize a final progress notification
+ if ( !length ) {
+ deferred.notifyWith( elem, [ animation, 1, 0 ] );
+ }
+
+ // Resolve the animation and report its conclusion
+ deferred.resolveWith( elem, [ animation ] );
+ return false;
+ },
+ animation = deferred.promise( {
+ elem: elem,
+ props: jQuery.extend( {}, properties ),
+ opts: jQuery.extend( true, {
+ specialEasing: {},
+ easing: jQuery.easing._default
+ }, options ),
+ originalProperties: properties,
+ originalOptions: options,
+ startTime: fxNow || createFxNow(),
+ duration: options.duration,
+ tweens: [],
+ createTween: function( prop, end ) {
+ var tween = jQuery.Tween( elem, animation.opts, prop, end,
+ animation.opts.specialEasing[ prop ] || animation.opts.easing );
+ animation.tweens.push( tween );
+ return tween;
+ },
+ stop: function( gotoEnd ) {
+ var index = 0,
+
+ // If we are going to the end, we want to run all the tweens
+ // otherwise we skip this part
+ length = gotoEnd ? animation.tweens.length : 0;
+ if ( stopped ) {
+ return this;
+ }
+ stopped = true;
+ for ( ; index < length; index++ ) {
+ animation.tweens[ index ].run( 1 );
+ }
+
+ // Resolve when we played the last frame; otherwise, reject
+ if ( gotoEnd ) {
+ deferred.notifyWith( elem, [ animation, 1, 0 ] );
+ deferred.resolveWith( elem, [ animation, gotoEnd ] );
+ } else {
+ deferred.rejectWith( elem, [ animation, gotoEnd ] );
+ }
+ return this;
+ }
+ } ),
+ props = animation.props;
+
+ propFilter( props, animation.opts.specialEasing );
+
+ for ( ; index < length; index++ ) {
+ result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
+ if ( result ) {
+ if ( isFunction( result.stop ) ) {
+ jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
+ result.stop.bind( result );
+ }
+ return result;
+ }
+ }
+
+ jQuery.map( props, createTween, animation );
+
+ if ( isFunction( animation.opts.start ) ) {
+ animation.opts.start.call( elem, animation );
+ }
+
+ // Attach callbacks from options
+ animation
+ .progress( animation.opts.progress )
+ .done( animation.opts.done, animation.opts.complete )
+ .fail( animation.opts.fail )
+ .always( animation.opts.always );
+
+ jQuery.fx.timer(
+ jQuery.extend( tick, {
+ elem: elem,
+ anim: animation,
+ queue: animation.opts.queue
+ } )
+ );
+
+ return animation;
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+ tweeners: {
+ "*": [ function( prop, value ) {
+ var tween = this.createTween( prop, value );
+ adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
+ return tween;
+ } ]
+ },
+
+ tweener: function( props, callback ) {
+ if ( isFunction( props ) ) {
+ callback = props;
+ props = [ "*" ];
+ } else {
+ props = props.match( rnothtmlwhite );
+ }
+
+ var prop,
+ index = 0,
+ length = props.length;
+
+ for ( ; index < length; index++ ) {
+ prop = props[ index ];
+ Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
+ Animation.tweeners[ prop ].unshift( callback );
+ }
+ },
+
+ prefilters: [ defaultPrefilter ],
+
+ prefilter: function( callback, prepend ) {
+ if ( prepend ) {
+ Animation.prefilters.unshift( callback );
+ } else {
+ Animation.prefilters.push( callback );
+ }
+ }
+} );
+
+jQuery.speed = function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+ complete: fn || !fn && easing ||
+ isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !isFunction( easing ) && easing
+ };
+
+ // Go to the end state if fx are off
+ if ( jQuery.fx.off ) {
+ opt.duration = 0;
+
+ } else {
+ if ( typeof opt.duration !== "number" ) {
+ if ( opt.duration in jQuery.fx.speeds ) {
+ opt.duration = jQuery.fx.speeds[ opt.duration ];
+
+ } else {
+ opt.duration = jQuery.fx.speeds._default;
+ }
+ }
+ }
+
+ // Normalize opt.queue - true/undefined/null -> "fx"
+ if ( opt.queue == null || opt.queue === true ) {
+ opt.queue = "fx";
+ }
+
+ // Queueing
+ opt.old = opt.complete;
+
+ opt.complete = function() {
+ if ( isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+
+ if ( opt.queue ) {
+ jQuery.dequeue( this, opt.queue );
+ }
+ };
+
+ return opt;
+};
+
+jQuery.fn.extend( {
+ fadeTo: function( speed, to, easing, callback ) {
+
+ // Show any hidden elements after setting opacity to 0
+ return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
+
+ // Animate to the value specified
+ .end().animate( { opacity: to }, speed, easing, callback );
+ },
+ animate: function( prop, speed, easing, callback ) {
+ var empty = jQuery.isEmptyObject( prop ),
+ optall = jQuery.speed( speed, easing, callback ),
+ doAnimation = function() {
+
+ // Operate on a copy of prop so per-property easing won't be lost
+ var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+
+ // Empty animations, or finishing resolves immediately
+ if ( empty || dataPriv.get( this, "finish" ) ) {
+ anim.stop( true );
+ }
+ };
+
+ doAnimation.finish = doAnimation;
+
+ return empty || optall.queue === false ?
+ this.each( doAnimation ) :
+ this.queue( optall.queue, doAnimation );
+ },
+ stop: function( type, clearQueue, gotoEnd ) {
+ var stopQueue = function( hooks ) {
+ var stop = hooks.stop;
+ delete hooks.stop;
+ stop( gotoEnd );
+ };
+
+ if ( typeof type !== "string" ) {
+ gotoEnd = clearQueue;
+ clearQueue = type;
+ type = undefined;
+ }
+ if ( clearQueue ) {
+ this.queue( type || "fx", [] );
+ }
+
+ return this.each( function() {
+ var dequeue = true,
+ index = type != null && type + "queueHooks",
+ timers = jQuery.timers,
+ data = dataPriv.get( this );
+
+ if ( index ) {
+ if ( data[ index ] && data[ index ].stop ) {
+ stopQueue( data[ index ] );
+ }
+ } else {
+ for ( index in data ) {
+ if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
+ stopQueue( data[ index ] );
+ }
+ }
+ }
+
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this &&
+ ( type == null || timers[ index ].queue === type ) ) {
+
+ timers[ index ].anim.stop( gotoEnd );
+ dequeue = false;
+ timers.splice( index, 1 );
+ }
+ }
+
+ // Start the next in the queue if the last step wasn't forced.
+ // Timers currently will call their complete callbacks, which
+ // will dequeue but only if they were gotoEnd.
+ if ( dequeue || !gotoEnd ) {
+ jQuery.dequeue( this, type );
+ }
+ } );
+ },
+ finish: function( type ) {
+ if ( type !== false ) {
+ type = type || "fx";
+ }
+ return this.each( function() {
+ var index,
+ data = dataPriv.get( this ),
+ queue = data[ type + "queue" ],
+ hooks = data[ type + "queueHooks" ],
+ timers = jQuery.timers,
+ length = queue ? queue.length : 0;
+
+ // Enable finishing flag on private data
+ data.finish = true;
+
+ // Empty the queue first
+ jQuery.queue( this, type, [] );
+
+ if ( hooks && hooks.stop ) {
+ hooks.stop.call( this, true );
+ }
+
+ // Look for any active animations, and finish them
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+ timers[ index ].anim.stop( true );
+ timers.splice( index, 1 );
+ }
+ }
+
+ // Look for any animations in the old queue and finish them
+ for ( index = 0; index < length; index++ ) {
+ if ( queue[ index ] && queue[ index ].finish ) {
+ queue[ index ].finish.call( this );
+ }
+ }
+
+ // Turn off finishing flag
+ delete data.finish;
+ } );
+ }
+} );
+
+jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
+ var cssFn = jQuery.fn[ name ];
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return speed == null || typeof speed === "boolean" ?
+ cssFn.apply( this, arguments ) :
+ this.animate( genFx( name, true ), speed, easing, callback );
+ };
+} );
+
+// Generate shortcuts for custom animations
+jQuery.each( {
+ slideDown: genFx( "show" ),
+ slideUp: genFx( "hide" ),
+ slideToggle: genFx( "toggle" ),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+} );
+
+jQuery.timers = [];
+jQuery.fx.tick = function() {
+ var timer,
+ i = 0,
+ timers = jQuery.timers;
+
+ fxNow = Date.now();
+
+ for ( ; i < timers.length; i++ ) {
+ timer = timers[ i ];
+
+ // Run the timer and safely remove it when done (allowing for external removal)
+ if ( !timer() && timers[ i ] === timer ) {
+ timers.splice( i--, 1 );
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+ jQuery.timers.push( timer );
+ jQuery.fx.start();
+};
+
+jQuery.fx.interval = 13;
+jQuery.fx.start = function() {
+ if ( inProgress ) {
+ return;
+ }
+
+ inProgress = true;
+ schedule();
+};
+
+jQuery.fx.stop = function() {
+ inProgress = null;
+};
+
+jQuery.fx.speeds = {
+ slow: 600,
+ fast: 200,
+
+ // Default speed
+ _default: 400
+};
+
+
+// Based off of the plugin by Clint Helfers, with permission.
+// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
+jQuery.fn.delay = function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function( next, hooks ) {
+ var timeout = window.setTimeout( next, time );
+ hooks.stop = function() {
+ window.clearTimeout( timeout );
+ };
+ } );
+};
+
+
+( function() {
+ var input = document.createElement( "input" ),
+ select = document.createElement( "select" ),
+ opt = select.appendChild( document.createElement( "option" ) );
+
+ input.type = "checkbox";
+
+ // Support: Android <=4.3 only
+ // Default value for a checkbox should be "on"
+ support.checkOn = input.value !== "";
+
+ // Support: IE <=11 only
+ // Must access selectedIndex to make default options select
+ support.optSelected = opt.selected;
+
+ // Support: IE <=11 only
+ // An input loses its value after becoming a radio
+ input = document.createElement( "input" );
+ input.value = "t";
+ input.type = "radio";
+ support.radioValue = input.value === "t";
+} )();
+
+
+var boolHook,
+ attrHandle = jQuery.expr.attrHandle;
+
+jQuery.fn.extend( {
+ attr: function( name, value ) {
+ return access( this, jQuery.attr, name, value, arguments.length > 1 );
+ },
+
+ removeAttr: function( name ) {
+ return this.each( function() {
+ jQuery.removeAttr( this, name );
+ } );
+ }
+} );
+
+jQuery.extend( {
+ attr: function( elem, name, value ) {
+ var ret, hooks,
+ nType = elem.nodeType;
+
+ // Don't get/set attributes on text, comment and attribute nodes
+ if ( nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( typeof elem.getAttribute === "undefined" ) {
+ return jQuery.prop( elem, name, value );
+ }
+
+ // Attribute hooks are determined by the lowercase version
+ // Grab necessary hook if one is defined
+ if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
+ hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
+ ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
+ }
+
+ if ( value !== undefined ) {
+ if ( value === null ) {
+ jQuery.removeAttr( elem, name );
+ return;
+ }
+
+ if ( hooks && "set" in hooks &&
+ ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
+ return ret;
+ }
+
+ elem.setAttribute( name, value + "" );
+ return value;
+ }
+
+ if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
+ return ret;
+ }
+
+ ret = jQuery.find.attr( elem, name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret == null ? undefined : ret;
+ },
+
+ attrHooks: {
+ type: {
+ set: function( elem, value ) {
+ if ( !support.radioValue && value === "radio" &&
+ nodeName( elem, "input" ) ) {
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ }
+ },
+
+ removeAttr: function( elem, value ) {
+ var name,
+ i = 0,
+
+ // Attribute names can contain non-HTML whitespace characters
+ // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
+ attrNames = value && value.match( rnothtmlwhite );
+
+ if ( attrNames && elem.nodeType === 1 ) {
+ while ( ( name = attrNames[ i++ ] ) ) {
+ elem.removeAttribute( name );
+ }
+ }
+ }
+} );
+
+// Hooks for boolean attributes
+boolHook = {
+ set: function( elem, value, name ) {
+ if ( value === false ) {
+
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr( elem, name );
+ } else {
+ elem.setAttribute( name, name );
+ }
+ return name;
+ }
+};
+
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
+ var getter = attrHandle[ name ] || jQuery.find.attr;
+
+ attrHandle[ name ] = function( elem, name, isXML ) {
+ var ret, handle,
+ lowercaseName = name.toLowerCase();
+
+ if ( !isXML ) {
+
+ // Avoid an infinite loop by temporarily removing this function from the getter
+ handle = attrHandle[ lowercaseName ];
+ attrHandle[ lowercaseName ] = ret;
+ ret = getter( elem, name, isXML ) != null ?
+ lowercaseName :
+ null;
+ attrHandle[ lowercaseName ] = handle;
+ }
+ return ret;
+ };
+} );
+
+
+
+
+var rfocusable = /^(?:input|select|textarea|button)$/i,
+ rclickable = /^(?:a|area)$/i;
+
+jQuery.fn.extend( {
+ prop: function( name, value ) {
+ return access( this, jQuery.prop, name, value, arguments.length > 1 );
+ },
+
+ removeProp: function( name ) {
+ return this.each( function() {
+ delete this[ jQuery.propFix[ name ] || name ];
+ } );
+ }
+} );
+
+jQuery.extend( {
+ prop: function( elem, name, value ) {
+ var ret, hooks,
+ nType = elem.nodeType;
+
+ // Don't get/set properties on text, comment and attribute nodes
+ if ( nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
+
+ // Fix name and attach hooks
+ name = jQuery.propFix[ name ] || name;
+ hooks = jQuery.propHooks[ name ];
+ }
+
+ if ( value !== undefined ) {
+ if ( hooks && "set" in hooks &&
+ ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
+ return ret;
+ }
+
+ return ( elem[ name ] = value );
+ }
+
+ if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
+ return ret;
+ }
+
+ return elem[ name ];
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function( elem ) {
+
+ // Support: IE <=9 - 11 only
+ // elem.tabIndex doesn't always return the
+ // correct value when it hasn't been explicitly set
+ // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ // Use proper attribute retrieval(#12072)
+ var tabindex = jQuery.find.attr( elem, "tabindex" );
+
+ if ( tabindex ) {
+ return parseInt( tabindex, 10 );
+ }
+
+ if (
+ rfocusable.test( elem.nodeName ) ||
+ rclickable.test( elem.nodeName ) &&
+ elem.href
+ ) {
+ return 0;
+ }
+
+ return -1;
+ }
+ }
+ },
+
+ propFix: {
+ "for": "htmlFor",
+ "class": "className"
+ }
+} );
+
+// Support: IE <=11 only
+// Accessing the selectedIndex property
+// forces the browser to respect setting selected
+// on the option
+// The getter ensures a default option is selected
+// when in an optgroup
+// eslint rule "no-unused-expressions" is disabled for this code
+// since it considers such accessions noop
+if ( !support.optSelected ) {
+ jQuery.propHooks.selected = {
+ get: function( elem ) {
+
+ /* eslint no-unused-expressions: "off" */
+
+ var parent = elem.parentNode;
+ if ( parent && parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ return null;
+ },
+ set: function( elem ) {
+
+ /* eslint no-unused-expressions: "off" */
+
+ var parent = elem.parentNode;
+ if ( parent ) {
+ parent.selectedIndex;
+
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ }
+ };
+}
+
+jQuery.each( [
+ "tabIndex",
+ "readOnly",
+ "maxLength",
+ "cellSpacing",
+ "cellPadding",
+ "rowSpan",
+ "colSpan",
+ "useMap",
+ "frameBorder",
+ "contentEditable"
+], function() {
+ jQuery.propFix[ this.toLowerCase() ] = this;
+} );
+
+
+
+
+ // Strip and collapse whitespace according to HTML spec
+ // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
+ function stripAndCollapse( value ) {
+ var tokens = value.match( rnothtmlwhite ) || [];
+ return tokens.join( " " );
+ }
+
+
+function getClass( elem ) {
+ return elem.getAttribute && elem.getAttribute( "class" ) || "";
+}
+
+function classesToArray( value ) {
+ if ( Array.isArray( value ) ) {
+ return value;
+ }
+ if ( typeof value === "string" ) {
+ return value.match( rnothtmlwhite ) || [];
+ }
+ return [];
+}
+
+jQuery.fn.extend( {
+ addClass: function( value ) {
+ var classes, elem, cur, curValue, clazz, j, finalValue,
+ i = 0;
+
+ if ( isFunction( value ) ) {
+ return this.each( function( j ) {
+ jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
+ } );
+ }
+
+ classes = classesToArray( value );
+
+ if ( classes.length ) {
+ while ( ( elem = this[ i++ ] ) ) {
+ curValue = getClass( elem );
+ cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
+
+ if ( cur ) {
+ j = 0;
+ while ( ( clazz = classes[ j++ ] ) ) {
+ if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+ cur += clazz + " ";
+ }
+ }
+
+ // Only assign if different to avoid unneeded rendering.
+ finalValue = stripAndCollapse( cur );
+ if ( curValue !== finalValue ) {
+ elem.setAttribute( "class", finalValue );
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classes, elem, cur, curValue, clazz, j, finalValue,
+ i = 0;
+
+ if ( isFunction( value ) ) {
+ return this.each( function( j ) {
+ jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
+ } );
+ }
+
+ if ( !arguments.length ) {
+ return this.attr( "class", "" );
+ }
+
+ classes = classesToArray( value );
+
+ if ( classes.length ) {
+ while ( ( elem = this[ i++ ] ) ) {
+ curValue = getClass( elem );
+
+ // This expression is here for better compressibility (see addClass)
+ cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
+
+ if ( cur ) {
+ j = 0;
+ while ( ( clazz = classes[ j++ ] ) ) {
+
+ // Remove *all* instances
+ while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
+ cur = cur.replace( " " + clazz + " ", " " );
+ }
+ }
+
+ // Only assign if different to avoid unneeded rendering.
+ finalValue = stripAndCollapse( cur );
+ if ( curValue !== finalValue ) {
+ elem.setAttribute( "class", finalValue );
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value,
+ isValidValue = type === "string" || Array.isArray( value );
+
+ if ( typeof stateVal === "boolean" && isValidValue ) {
+ return stateVal ? this.addClass( value ) : this.removeClass( value );
+ }
+
+ if ( isFunction( value ) ) {
+ return this.each( function( i ) {
+ jQuery( this ).toggleClass(
+ value.call( this, i, getClass( this ), stateVal ),
+ stateVal
+ );
+ } );
+ }
+
+ return this.each( function() {
+ var className, i, self, classNames;
+
+ if ( isValidValue ) {
+
+ // Toggle individual class names
+ i = 0;
+ self = jQuery( this );
+ classNames = classesToArray( value );
+
+ while ( ( className = classNames[ i++ ] ) ) {
+
+ // Check each className given, space separated list
+ if ( self.hasClass( className ) ) {
+ self.removeClass( className );
+ } else {
+ self.addClass( className );
+ }
+ }
+
+ // Toggle whole class name
+ } else if ( value === undefined || type === "boolean" ) {
+ className = getClass( this );
+ if ( className ) {
+
+ // Store className if set
+ dataPriv.set( this, "__className__", className );
+ }
+
+ // If the element has a class name or if we're passed `false`,
+ // then remove the whole classname (if there was one, the above saved it).
+ // Otherwise bring back whatever was previously saved (if anything),
+ // falling back to the empty string if nothing was stored.
+ if ( this.setAttribute ) {
+ this.setAttribute( "class",
+ className || value === false ?
+ "" :
+ dataPriv.get( this, "__className__" ) || ""
+ );
+ }
+ }
+ } );
+ },
+
+ hasClass: function( selector ) {
+ var className, elem,
+ i = 0;
+
+ className = " " + selector + " ";
+ while ( ( elem = this[ i++ ] ) ) {
+ if ( elem.nodeType === 1 &&
+ ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+} );
+
+
+
+
+var rreturn = /\r/g;
+
+jQuery.fn.extend( {
+ val: function( value ) {
+ var hooks, ret, valueIsFunction,
+ elem = this[ 0 ];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.type ] ||
+ jQuery.valHooks[ elem.nodeName.toLowerCase() ];
+
+ if ( hooks &&
+ "get" in hooks &&
+ ( ret = hooks.get( elem, "value" ) ) !== undefined
+ ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ // Handle most common string cases
+ if ( typeof ret === "string" ) {
+ return ret.replace( rreturn, "" );
+ }
+
+ // Handle cases where value is null/undef or number
+ return ret == null ? "" : ret;
+ }
+
+ return;
+ }
+
+ valueIsFunction = isFunction( value );
+
+ return this.each( function( i ) {
+ var val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( valueIsFunction ) {
+ val = value.call( this, i, jQuery( this ).val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+
+ } else if ( typeof val === "number" ) {
+ val += "";
+
+ } else if ( Array.isArray( val ) ) {
+ val = jQuery.map( val, function( value ) {
+ return value == null ? "" : value + "";
+ } );
+ }
+
+ hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ } );
+ }
+} );
+
+jQuery.extend( {
+ valHooks: {
+ option: {
+ get: function( elem ) {
+
+ var val = jQuery.find.attr( elem, "value" );
+ return val != null ?
+ val :
+
+ // Support: IE <=10 - 11 only
+ // option.text throws exceptions (#14686, #14858)
+ // Strip and collapse whitespace
+ // https://html.spec.whatwg.org/#strip-and-collapse-whitespace
+ stripAndCollapse( jQuery.text( elem ) );
+ }
+ },
+ select: {
+ get: function( elem ) {
+ var value, option, i,
+ options = elem.options,
+ index = elem.selectedIndex,
+ one = elem.type === "select-one",
+ values = one ? null : [],
+ max = one ? index + 1 : options.length;
+
+ if ( index < 0 ) {
+ i = max;
+
+ } else {
+ i = one ? index : 0;
+ }
+
+ // Loop through all the selected options
+ for ( ; i < max; i++ ) {
+ option = options[ i ];
+
+ // Support: IE <=9 only
+ // IE8-9 doesn't update selected after form reset (#2551)
+ if ( ( option.selected || i === index ) &&
+
+ // Don't return options that are disabled or in a disabled optgroup
+ !option.disabled &&
+ ( !option.parentNode.disabled ||
+ !nodeName( option.parentNode, "optgroup" ) ) ) {
+
+ // Get the specific value for the option
+ value = jQuery( option ).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ },
+
+ set: function( elem, value ) {
+ var optionSet, option,
+ options = elem.options,
+ values = jQuery.makeArray( value ),
+ i = options.length;
+
+ while ( i-- ) {
+ option = options[ i ];
+
+ /* eslint-disable no-cond-assign */
+
+ if ( option.selected =
+ jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
+ ) {
+ optionSet = true;
+ }
+
+ /* eslint-enable no-cond-assign */
+ }
+
+ // Force browsers to behave consistently when non-matching value is set
+ if ( !optionSet ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ }
+} );
+
+// Radios and checkboxes getter/setter
+jQuery.each( [ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = {
+ set: function( elem, value ) {
+ if ( Array.isArray( value ) ) {
+ return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
+ }
+ }
+ };
+ if ( !support.checkOn ) {
+ jQuery.valHooks[ this ].get = function( elem ) {
+ return elem.getAttribute( "value" ) === null ? "on" : elem.value;
+ };
+ }
+} );
+
+
+
+
+// Return jQuery for attributes-only inclusion
+
+
+support.focusin = "onfocusin" in window;
+
+
+var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+ stopPropagationCallback = function( e ) {
+ e.stopPropagation();
+ };
+
+jQuery.extend( jQuery.event, {
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+
+ var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
+ eventPath = [ elem || document ],
+ type = hasOwn.call( event, "type" ) ? event.type : event,
+ namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
+
+ cur = lastElement = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+ return;
+ }
+
+ if ( type.indexOf( "." ) > -1 ) {
+
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split( "." );
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+ ontype = type.indexOf( ":" ) < 0 && "on" + type;
+
+ // Caller can pass in a jQuery.Event object, Object, or just an event type string
+ event = event[ jQuery.expando ] ?
+ event :
+ new jQuery.Event( type, typeof event === "object" && event );
+
+ // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+ event.isTrigger = onlyHandlers ? 2 : 3;
+ event.namespace = namespaces.join( "." );
+ event.rnamespace = event.namespace ?
+ new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
+ null;
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ if ( !event.target ) {
+ event.target = elem;
+ }
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data == null ?
+ [ event ] :
+ jQuery.makeArray( data, [ event ] );
+
+ // Allow special events to draw outside the lines
+ special = jQuery.event.special[ type ] || {};
+ if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
+ return;
+ }
+
+ // Determine event propagation path in advance, per W3C events spec (#9951)
+ // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+ if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {
+
+ bubbleType = special.delegateType || type;
+ if ( !rfocusMorph.test( bubbleType + type ) ) {
+ cur = cur.parentNode;
+ }
+ for ( ; cur; cur = cur.parentNode ) {
+ eventPath.push( cur );
+ tmp = cur;
+ }
+
+ // Only add window if we got to document (e.g., not plain obj or detached DOM)
+ if ( tmp === ( elem.ownerDocument || document ) ) {
+ eventPath.push( tmp.defaultView || tmp.parentWindow || window );
+ }
+ }
+
+ // Fire handlers on the event path
+ i = 0;
+ while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
+ lastElement = cur;
+ event.type = i > 1 ?
+ bubbleType :
+ special.bindType || type;
+
+ // jQuery handler
+ handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &&
+ dataPriv.get( cur, "handle" );
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Native handler
+ handle = ontype && cur[ ontype ];
+ if ( handle && handle.apply && acceptData( cur ) ) {
+ event.result = handle.apply( cur, data );
+ if ( event.result === false ) {
+ event.preventDefault();
+ }
+ }
+ }
+ event.type = type;
+
+ // If nobody prevented the default action, do it now
+ if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+ if ( ( !special._default ||
+ special._default.apply( eventPath.pop(), data ) === false ) &&
+ acceptData( elem ) ) {
+
+ // Call a native DOM method on the target with the same name as the event.
+ // Don't do default actions on window, that's where global variables be (#6170)
+ if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {
+
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ tmp = elem[ ontype ];
+
+ if ( tmp ) {
+ elem[ ontype ] = null;
+ }
+
+ // Prevent re-triggering of the same event, since we already bubbled it above
+ jQuery.event.triggered = type;
+
+ if ( event.isPropagationStopped() ) {
+ lastElement.addEventListener( type, stopPropagationCallback );
+ }
+
+ elem[ type ]();
+
+ if ( event.isPropagationStopped() ) {
+ lastElement.removeEventListener( type, stopPropagationCallback );
+ }
+
+ jQuery.event.triggered = undefined;
+
+ if ( tmp ) {
+ elem[ ontype ] = tmp;
+ }
+ }
+ }
+ }
+
+ return event.result;
+ },
+
+ // Piggyback on a donor event to simulate a different one
+ // Used only for `focus(in | out)` events
+ simulate: function( type, elem, event ) {
+ var e = jQuery.extend(
+ new jQuery.Event(),
+ event,
+ {
+ type: type,
+ isSimulated: true
+ }
+ );
+
+ jQuery.event.trigger( e, null, elem );
+ }
+
+} );
+
+jQuery.fn.extend( {
+
+ trigger: function( type, data ) {
+ return this.each( function() {
+ jQuery.event.trigger( type, data, this );
+ } );
+ },
+ triggerHandler: function( type, data ) {
+ var elem = this[ 0 ];
+ if ( elem ) {
+ return jQuery.event.trigger( type, data, elem, true );
+ }
+ }
+} );
+
+
+// Support: Firefox <=44
+// Firefox doesn't have focus(in | out) events
+// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
+//
+// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
+// focus(in | out) events fire after focus & blur events,
+// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
+// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
+if ( !support.focusin ) {
+ jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function( event ) {
+ jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+
+ // Handle: regular nodes (via `this.ownerDocument`), window
+ // (via `this.document`) & document (via `this`).
+ var doc = this.ownerDocument || this.document || this,
+ attaches = dataPriv.access( doc, fix );
+
+ if ( !attaches ) {
+ doc.addEventListener( orig, handler, true );
+ }
+ dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
+ },
+ teardown: function() {
+ var doc = this.ownerDocument || this.document || this,
+ attaches = dataPriv.access( doc, fix ) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener( orig, handler, true );
+ dataPriv.remove( doc, fix );
+
+ } else {
+ dataPriv.access( doc, fix, attaches );
+ }
+ }
+ };
+ } );
+}
+var location = window.location;
+
+var nonce = { guid: Date.now() };
+
+var rquery = ( /\?/ );
+
+
+
+// Cross-browser xml parsing
+jQuery.parseXML = function( data ) {
+ var xml, parserErrorElem;
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+
+ // Support: IE 9 - 11 only
+ // IE throws on parseFromString with invalid input.
+ try {
+ xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
+ } catch ( e ) {}
+
+ parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ];
+ if ( !xml || parserErrorElem ) {
+ jQuery.error( "Invalid XML: " + (
+ parserErrorElem ?
+ jQuery.map( parserErrorElem.childNodes, function( el ) {
+ return el.textContent;
+ } ).join( "\n" ) :
+ data
+ ) );
+ }
+ return xml;
+};
+
+
+var
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+ rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+function buildParams( prefix, obj, traditional, add ) {
+ var name;
+
+ if ( Array.isArray( obj ) ) {
+
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional || rbracket.test( prefix ) ) {
+
+ // Treat each array item as a scalar.
+ add( prefix, v );
+
+ } else {
+
+ // Item is non-scalar (array or object), encode its numeric index.
+ buildParams(
+ prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
+ v,
+ traditional,
+ add
+ );
+ }
+ } );
+
+ } else if ( !traditional && toType( obj ) === "object" ) {
+
+ // Serialize object item.
+ for ( name in obj ) {
+ buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+ }
+
+ } else {
+
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+}
+
+// Serialize an array of form elements or a set of
+// key/values into a query string
+jQuery.param = function( a, traditional ) {
+ var prefix,
+ s = [],
+ add = function( key, valueOrFunction ) {
+
+ // If value is a function, invoke it and use its return value
+ var value = isFunction( valueOrFunction ) ?
+ valueOrFunction() :
+ valueOrFunction;
+
+ s[ s.length ] = encodeURIComponent( key ) + "=" +
+ encodeURIComponent( value == null ? "" : value );
+ };
+
+ if ( a == null ) {
+ return "";
+ }
+
+ // If an array was passed in, assume that it is an array of form elements.
+ if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+
+ // Serialize the form elements
+ jQuery.each( a, function() {
+ add( this.name, this.value );
+ } );
+
+ } else {
+
+ // If traditional, encode the "old" way (the way 1.3.2 or older
+ // did it), otherwise encode params recursively.
+ for ( prefix in a ) {
+ buildParams( prefix, a[ prefix ], traditional, add );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join( "&" );
+};
+
+jQuery.fn.extend( {
+ serialize: function() {
+ return jQuery.param( this.serializeArray() );
+ },
+ serializeArray: function() {
+ return this.map( function() {
+
+ // Can add propHook for "elements" to filter or add form elements
+ var elements = jQuery.prop( this, "elements" );
+ return elements ? jQuery.makeArray( elements ) : this;
+ } ).filter( function() {
+ var type = this.type;
+
+ // Use .is( ":disabled" ) so that fieldset[disabled] works
+ return this.name && !jQuery( this ).is( ":disabled" ) &&
+ rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
+ ( this.checked || !rcheckableType.test( type ) );
+ } ).map( function( _i, elem ) {
+ var val = jQuery( this ).val();
+
+ if ( val == null ) {
+ return null;
+ }
+
+ if ( Array.isArray( val ) ) {
+ return jQuery.map( val, function( val ) {
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ } );
+ }
+
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ } ).get();
+ }
+} );
+
+
+var
+ r20 = /%20/g,
+ rhash = /#.*$/,
+ rantiCache = /([?&])_=[^&]*/,
+ rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
+
+ // #7653, #8125, #8152: local protocol detection
+ rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+ rnoContent = /^(?:GET|HEAD)$/,
+ rprotocol = /^\/\//,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {},
+
+ // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+ allTypes = "*/".concat( "*" ),
+
+ // Anchor tag for parsing the document origin
+ originAnchor = document.createElement( "a" );
+
+originAnchor.href = location.href;
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ var dataType,
+ i = 0,
+ dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];
+
+ if ( isFunction( func ) ) {
+
+ // For each dataType in the dataTypeExpression
+ while ( ( dataType = dataTypes[ i++ ] ) ) {
+
+ // Prepend if requested
+ if ( dataType[ 0 ] === "+" ) {
+ dataType = dataType.slice( 1 ) || "*";
+ ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
+
+ // Otherwise append
+ } else {
+ ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
+ }
+ }
+ }
+ };
+}
+
+// Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
+
+ var inspected = {},
+ seekingTransport = ( structure === transports );
+
+ function inspect( dataType ) {
+ var selected;
+ inspected[ dataType ] = true;
+ jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
+ var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
+ if ( typeof dataTypeOrTransport === "string" &&
+ !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
+
+ options.dataTypes.unshift( dataTypeOrTransport );
+ inspect( dataTypeOrTransport );
+ return false;
+ } else if ( seekingTransport ) {
+ return !( selected = dataTypeOrTransport );
+ }
+ } );
+ return selected;
+ }
+
+ return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
+}
+
+// A special extend for ajax options
+// that takes "flat" options (not to be deep extended)
+// Fixes #9887
+function ajaxExtend( target, src ) {
+ var key, deep,
+ flatOptions = jQuery.ajaxSettings.flatOptions || {};
+
+ for ( key in src ) {
+ if ( src[ key ] !== undefined ) {
+ ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
+ }
+ }
+ if ( deep ) {
+ jQuery.extend( true, target, deep );
+ }
+
+ return target;
+}
+
+/* Handles responses to an ajax request:
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+
+ var ct, type, finalDataType, firstDataType,
+ contents = s.contents,
+ dataTypes = s.dataTypes;
+
+ // Remove auto dataType and get content-type in the process
+ while ( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
+ }
+ }
+
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
+ }
+ }
+
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
+ }
+
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
+
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
+ }
+ return responses[ finalDataType ];
+ }
+}
+
+/* Chain conversions given the request and the original response
+ * Also sets the responseXXX fields on the jqXHR instance
+ */
+function ajaxConvert( s, response, jqXHR, isSuccess ) {
+ var conv2, current, conv, tmp, prev,
+ converters = {},
+
+ // Work with a copy of dataTypes in case we need to modify it for conversion
+ dataTypes = s.dataTypes.slice();
+
+ // Create converters map with lowercased keys
+ if ( dataTypes[ 1 ] ) {
+ for ( conv in s.converters ) {
+ converters[ conv.toLowerCase() ] = s.converters[ conv ];
+ }
+ }
+
+ current = dataTypes.shift();
+
+ // Convert to each sequential dataType
+ while ( current ) {
+
+ if ( s.responseFields[ current ] ) {
+ jqXHR[ s.responseFields[ current ] ] = response;
+ }
+
+ // Apply the dataFilter if provided
+ if ( !prev && isSuccess && s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ prev = current;
+ current = dataTypes.shift();
+
+ if ( current ) {
+
+ // There's only work to do if current dataType is non-auto
+ if ( current === "*" ) {
+
+ current = prev;
+
+ // Convert response if prev dataType is non-auto and differs from current
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Seek a direct converter
+ conv = converters[ prev + " " + current ] || converters[ "* " + current ];
+
+ // If none found, seek a pair
+ if ( !conv ) {
+ for ( conv2 in converters ) {
+
+ // If conv2 outputs current
+ tmp = conv2.split( " " );
+ if ( tmp[ 1 ] === current ) {
+
+ // If prev can be converted to accepted input
+ conv = converters[ prev + " " + tmp[ 0 ] ] ||
+ converters[ "* " + tmp[ 0 ] ];
+ if ( conv ) {
+
+ // Condense equivalence converters
+ if ( conv === true ) {
+ conv = converters[ conv2 ];
+
+ // Otherwise, insert the intermediate dataType
+ } else if ( converters[ conv2 ] !== true ) {
+ current = tmp[ 0 ];
+ dataTypes.unshift( tmp[ 1 ] );
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ // Apply converter (if not an equivalence)
+ if ( conv !== true ) {
+
+ // Unless errors are allowed to bubble, catch and return them
+ if ( conv && s.throws ) {
+ response = conv( response );
+ } else {
+ try {
+ response = conv( response );
+ } catch ( e ) {
+ return {
+ state: "parsererror",
+ error: conv ? e : "No conversion from " + prev + " to " + current
+ };
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { state: "success", data: response };
+}
+
+jQuery.extend( {
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajaxSettings: {
+ url: location.href,
+ type: "GET",
+ isLocal: rlocalProtocol.test( location.protocol ),
+ global: true,
+ processData: true,
+ async: true,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ throws: false,
+ traditional: false,
+ headers: {},
+ */
+
+ accepts: {
+ "*": allTypes,
+ text: "text/plain",
+ html: "text/html",
+ xml: "application/xml, text/xml",
+ json: "application/json, text/javascript"
+ },
+
+ contents: {
+ xml: /\bxml\b/,
+ html: /\bhtml/,
+ json: /\bjson\b/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText",
+ json: "responseJSON"
+ },
+
+ // Data converters
+ // Keys separate source (or catchall "*") and destination types with a single space
+ converters: {
+
+ // Convert anything to text
+ "* text": String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": JSON.parse,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ },
+
+ // For options that shouldn't be deep extended:
+ // you can add your own custom options here if
+ // and when you create one that shouldn't be
+ // deep extended (see ajaxExtend)
+ flatOptions: {
+ url: true,
+ context: true
+ }
+ },
+
+ // Creates a full fledged settings object into target
+ // with both ajaxSettings and settings fields.
+ // If target is omitted, writes into ajaxSettings.
+ ajaxSetup: function( target, settings ) {
+ return settings ?
+
+ // Building a settings object
+ ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
+
+ // Extending ajaxSettings
+ ajaxExtend( jQuery.ajaxSettings, target );
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If url is an object, simulate pre-1.5 signature
+ if ( typeof url === "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var transport,
+
+ // URL without anti-cache param
+ cacheURL,
+
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+
+ // timeout handle
+ timeoutTimer,
+
+ // Url cleanup var
+ urlAnchor,
+
+ // Request state (becomes false upon send and true upon completion)
+ completed,
+
+ // To know if global events are to be dispatched
+ fireGlobals,
+
+ // Loop variable
+ i,
+
+ // uncached part of the url
+ uncached,
+
+ // Create the final options object
+ s = jQuery.ajaxSetup( {}, options ),
+
+ // Callbacks context
+ callbackContext = s.context || s,
+
+ // Context for global events is callbackContext if it is a DOM node or jQuery collection
+ globalEventContext = s.context &&
+ ( callbackContext.nodeType || callbackContext.jquery ) ?
+ jQuery( callbackContext ) :
+ jQuery.event,
+
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery.Callbacks( "once memory" ),
+
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ requestHeadersNames = {},
+
+ // Default abort message
+ strAbort = "canceled",
+
+ // Fake xhr
+ jqXHR = {
+ readyState: 0,
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( completed ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
+ responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
+ ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
+ .concat( match[ 2 ] );
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() + " " ];
+ }
+ return match == null ? null : match.join( ", " );
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return completed ? responseHeadersString : null;
+ },
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ if ( completed == null ) {
+ name = requestHeadersNames[ name.toLowerCase() ] =
+ requestHeadersNames[ name.toLowerCase() ] || name;
+ requestHeaders[ name ] = value;
+ }
+ return this;
+ },
+
+ // Overrides response content-type header
+ overrideMimeType: function( type ) {
+ if ( completed == null ) {
+ s.mimeType = type;
+ }
+ return this;
+ },
+
+ // Status-dependent callbacks
+ statusCode: function( map ) {
+ var code;
+ if ( map ) {
+ if ( completed ) {
+
+ // Execute the appropriate callbacks
+ jqXHR.always( map[ jqXHR.status ] );
+ } else {
+
+ // Lazy-add the new callbacks in a way that preserves old ones
+ for ( code in map ) {
+ statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+ }
+ }
+ }
+ return this;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ var finalText = statusText || strAbort;
+ if ( transport ) {
+ transport.abort( finalText );
+ }
+ done( 0, finalText );
+ return this;
+ }
+ };
+
+ // Attach deferreds
+ deferred.promise( jqXHR );
+
+ // Add protocol if not provided (prefilters might expect it)
+ // Handle falsy url in the settings object (#10093: consistency with old signature)
+ // We also use the url parameter if available
+ s.url = ( ( url || s.url || location.href ) + "" )
+ .replace( rprotocol, location.protocol + "//" );
+
+ // Alias method option to type as per ticket #12004
+ s.type = options.method || options.type || s.method || s.type;
+
+ // Extract dataTypes list
+ s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
+
+ // A cross-domain request is in order when the origin doesn't match the current origin.
+ if ( s.crossDomain == null ) {
+ urlAnchor = document.createElement( "a" );
+
+ // Support: IE <=8 - 11, Edge 12 - 15
+ // IE throws exception on accessing the href property if url is malformed,
+ // e.g. http://example.com:80x/
+ try {
+ urlAnchor.href = s.url;
+
+ // Support: IE <=8 - 11 only
+ // Anchor's host property isn't correctly set when s.url is relative
+ urlAnchor.href = urlAnchor.href;
+ s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
+ urlAnchor.protocol + "//" + urlAnchor.host;
+ } catch ( e ) {
+
+ // If there is an error parsing the URL, assume it is crossDomain,
+ // it can be rejected by the transport if it is invalid
+ s.crossDomain = true;
+ }
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+ // If request was aborted inside a prefilter, stop there
+ if ( completed ) {
+ return jqXHR;
+ }
+
+ // We can fire global events as of now if asked to
+ // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
+ fireGlobals = jQuery.event && s.global;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger( "ajaxStart" );
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ // Remove hash to simplify url manipulation
+ cacheURL = s.url.replace( rhash, "" );
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // Remember the hash so we can put it back
+ uncached = s.url.slice( cacheURL.length );
+
+ // If data is available and should be processed, append data to url
+ if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
+ cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
+
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add or update anti-cache param if needed
+ if ( s.cache === false ) {
+ cacheURL = cacheURL.replace( rantiCache, "$1" );
+ uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) +
+ uncached;
+ }
+
+ // Put hash and anti-cache on the URL that will be requested (gh-1732)
+ s.url = cacheURL + uncached;
+
+ // Change '%20' to '+' if this is encoded form body content (gh-2658)
+ } else if ( s.data && s.processData &&
+ ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
+ s.data = s.data.replace( r20, "+" );
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ jqXHR.setRequestHeader( "Content-Type", s.contentType );
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ jqXHR.setRequestHeader(
+ "Accept",
+ s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
+ s.accepts[ s.dataTypes[ 0 ] ] +
+ ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+ s.accepts[ "*" ]
+ );
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ jqXHR.setRequestHeader( i, s.headers[ i ] );
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend &&
+ ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
+
+ // Abort if not done already and return
+ return jqXHR.abort();
+ }
+
+ // Aborting is no longer a cancellation
+ strAbort = "abort";
+
+ // Install callbacks on deferreds
+ completeDeferred.add( s.complete );
+ jqXHR.done( s.success );
+ jqXHR.fail( s.error );
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ jqXHR.readyState = 1;
+
+ // Send global event
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+ }
+
+ // If request was aborted inside ajaxSend, stop there
+ if ( completed ) {
+ return jqXHR;
+ }
+
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = window.setTimeout( function() {
+ jqXHR.abort( "timeout" );
+ }, s.timeout );
+ }
+
+ try {
+ completed = false;
+ transport.send( requestHeaders, done );
+ } catch ( e ) {
+
+ // Rethrow post-completion exceptions
+ if ( completed ) {
+ throw e;
+ }
+
+ // Propagate others as results
+ done( -1, e );
+ }
+ }
+
+ // Callback for when everything is done
+ function done( status, nativeStatusText, responses, headers ) {
+ var isSuccess, success, error, response, modified,
+ statusText = nativeStatusText;
+
+ // Ignore repeat invocations
+ if ( completed ) {
+ return;
+ }
+
+ completed = true;
+
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ window.clearTimeout( timeoutTimer );
+ }
+
+ // Dereference transport for early garbage collection
+ // (no matter how long the jqXHR object will be used)
+ transport = undefined;
+
+ // Cache response headers
+ responseHeadersString = headers || "";
+
+ // Set readyState
+ jqXHR.readyState = status > 0 ? 4 : 0;
+
+ // Determine if successful
+ isSuccess = status >= 200 && status < 300 || status === 304;
+
+ // Get response data
+ if ( responses ) {
+ response = ajaxHandleResponses( s, jqXHR, responses );
+ }
+
+ // Use a noop converter for missing script but not if jsonp
+ if ( !isSuccess &&
+ jQuery.inArray( "script", s.dataTypes ) > -1 &&
+ jQuery.inArray( "json", s.dataTypes ) < 0 ) {
+ s.converters[ "text script" ] = function() {};
+ }
+
+ // Convert no matter what (that way responseXXX fields are always set)
+ response = ajaxConvert( s, response, jqXHR, isSuccess );
+
+ // If successful, handle type chaining
+ if ( isSuccess ) {
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ modified = jqXHR.getResponseHeader( "Last-Modified" );
+ if ( modified ) {
+ jQuery.lastModified[ cacheURL ] = modified;
+ }
+ modified = jqXHR.getResponseHeader( "etag" );
+ if ( modified ) {
+ jQuery.etag[ cacheURL ] = modified;
+ }
+ }
+
+ // if no content
+ if ( status === 204 || s.type === "HEAD" ) {
+ statusText = "nocontent";
+
+ // if not modified
+ } else if ( status === 304 ) {
+ statusText = "notmodified";
+
+ // If we have data, let's convert it
+ } else {
+ statusText = response.state;
+ success = response.data;
+ error = response.error;
+ isSuccess = !error;
+ }
+ } else {
+
+ // Extract error from statusText and normalize for non-aborts
+ error = statusText;
+ if ( status || !statusText ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
+
+ // Set data for the fake xhr object
+ jqXHR.status = status;
+ jqXHR.statusText = ( nativeStatusText || statusText ) + "";
+
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
+ }
+
+ // Status-dependent callbacks
+ jqXHR.statusCode( statusCode );
+ statusCode = undefined;
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
+ [ jqXHR, s, isSuccess ? success : error ] );
+ }
+
+ // Complete
+ completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
+
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ }
+ }
+
+ return jqXHR;
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get( url, data, callback, "json" );
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get( url, undefined, callback, "script" );
+ }
+} );
+
+jQuery.each( [ "get", "post" ], function( _i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+
+ // Shift arguments if data argument was omitted
+ if ( isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = undefined;
+ }
+
+ // The url can be an options object (which then must have .url)
+ return jQuery.ajax( jQuery.extend( {
+ url: url,
+ type: method,
+ dataType: type,
+ data: data,
+ success: callback
+ }, jQuery.isPlainObject( url ) && url ) );
+ };
+} );
+
+jQuery.ajaxPrefilter( function( s ) {
+ var i;
+ for ( i in s.headers ) {
+ if ( i.toLowerCase() === "content-type" ) {
+ s.contentType = s.headers[ i ] || "";
+ }
+ }
+} );
+
+
+jQuery._evalUrl = function( url, options, doc ) {
+ return jQuery.ajax( {
+ url: url,
+
+ // Make this explicit, since user can override this through ajaxSetup (#11264)
+ type: "GET",
+ dataType: "script",
+ cache: true,
+ async: false,
+ global: false,
+
+ // Only evaluate the response if it is successful (gh-4126)
+ // dataFilter is not invoked for failure responses, so using it instead
+ // of the default converter is kludgy but it works.
+ converters: {
+ "text script": function() {}
+ },
+ dataFilter: function( response ) {
+ jQuery.globalEval( response, options, doc );
+ }
+ } );
+};
+
+
+jQuery.fn.extend( {
+ wrapAll: function( html ) {
+ var wrap;
+
+ if ( this[ 0 ] ) {
+ if ( isFunction( html ) ) {
+ html = html.call( this[ 0 ] );
+ }
+
+ // The elements to wrap the target around
+ wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
+
+ if ( this[ 0 ].parentNode ) {
+ wrap.insertBefore( this[ 0 ] );
+ }
+
+ wrap.map( function() {
+ var elem = this;
+
+ while ( elem.firstElementChild ) {
+ elem = elem.firstElementChild;
+ }
+
+ return elem;
+ } ).append( this );
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ if ( isFunction( html ) ) {
+ return this.each( function( i ) {
+ jQuery( this ).wrapInner( html.call( this, i ) );
+ } );
+ }
+
+ return this.each( function() {
+ var self = jQuery( this ),
+ contents = self.contents();
+
+ if ( contents.length ) {
+ contents.wrapAll( html );
+
+ } else {
+ self.append( html );
+ }
+ } );
+ },
+
+ wrap: function( html ) {
+ var htmlIsFunction = isFunction( html );
+
+ return this.each( function( i ) {
+ jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
+ } );
+ },
+
+ unwrap: function( selector ) {
+ this.parent( selector ).not( "body" ).each( function() {
+ jQuery( this ).replaceWith( this.childNodes );
+ } );
+ return this;
+ }
+} );
+
+
+jQuery.expr.pseudos.hidden = function( elem ) {
+ return !jQuery.expr.pseudos.visible( elem );
+};
+jQuery.expr.pseudos.visible = function( elem ) {
+ return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
+};
+
+
+
+
+jQuery.ajaxSettings.xhr = function() {
+ try {
+ return new window.XMLHttpRequest();
+ } catch ( e ) {}
+};
+
+var xhrSuccessStatus = {
+
+ // File protocol always yields status code 0, assume 200
+ 0: 200,
+
+ // Support: IE <=9 only
+ // #1450: sometimes IE returns 1223 when it should be 204
+ 1223: 204
+ },
+ xhrSupported = jQuery.ajaxSettings.xhr();
+
+support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+support.ajax = xhrSupported = !!xhrSupported;
+
+jQuery.ajaxTransport( function( options ) {
+ var callback, errorCallback;
+
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( support.cors || xhrSupported && !options.crossDomain ) {
+ return {
+ send: function( headers, complete ) {
+ var i,
+ xhr = options.xhr();
+
+ xhr.open(
+ options.type,
+ options.url,
+ options.async,
+ options.username,
+ options.password
+ );
+
+ // Apply custom fields if provided
+ if ( options.xhrFields ) {
+ for ( i in options.xhrFields ) {
+ xhr[ i ] = options.xhrFields[ i ];
+ }
+ }
+
+ // Override mime type if needed
+ if ( options.mimeType && xhr.overrideMimeType ) {
+ xhr.overrideMimeType( options.mimeType );
+ }
+
+ // X-Requested-With header
+ // For cross-domain requests, seeing as conditions for a preflight are
+ // akin to a jigsaw puzzle, we simply never set it to be sure.
+ // (it can always be set on a per-request basis or even using ajaxSetup)
+ // For same-domain requests, won't change header if already provided.
+ if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
+ headers[ "X-Requested-With" ] = "XMLHttpRequest";
+ }
+
+ // Set headers
+ for ( i in headers ) {
+ xhr.setRequestHeader( i, headers[ i ] );
+ }
+
+ // Callback
+ callback = function( type ) {
+ return function() {
+ if ( callback ) {
+ callback = errorCallback = xhr.onload =
+ xhr.onerror = xhr.onabort = xhr.ontimeout =
+ xhr.onreadystatechange = null;
+
+ if ( type === "abort" ) {
+ xhr.abort();
+ } else if ( type === "error" ) {
+
+ // Support: IE <=9 only
+ // On a manual native abort, IE9 throws
+ // errors on any property access that is not readyState
+ if ( typeof xhr.status !== "number" ) {
+ complete( 0, "error" );
+ } else {
+ complete(
+
+ // File: protocol always yields status 0; see #8605, #14207
+ xhr.status,
+ xhr.statusText
+ );
+ }
+ } else {
+ complete(
+ xhrSuccessStatus[ xhr.status ] || xhr.status,
+ xhr.statusText,
+
+ // Support: IE <=9 only
+ // IE9 has no XHR2 but throws on binary (trac-11426)
+ // For XHR2 non-text, let the caller handle it (gh-2498)
+ ( xhr.responseType || "text" ) !== "text" ||
+ typeof xhr.responseText !== "string" ?
+ { binary: xhr.response } :
+ { text: xhr.responseText },
+ xhr.getAllResponseHeaders()
+ );
+ }
+ }
+ };
+ };
+
+ // Listen to events
+ xhr.onload = callback();
+ errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );
+
+ // Support: IE 9 only
+ // Use onreadystatechange to replace onabort
+ // to handle uncaught aborts
+ if ( xhr.onabort !== undefined ) {
+ xhr.onabort = errorCallback;
+ } else {
+ xhr.onreadystatechange = function() {
+
+ // Check readyState before timeout as it changes
+ if ( xhr.readyState === 4 ) {
+
+ // Allow onerror to be called first,
+ // but that will not handle a native abort
+ // Also, save errorCallback to a variable
+ // as xhr.onerror cannot be accessed
+ window.setTimeout( function() {
+ if ( callback ) {
+ errorCallback();
+ }
+ } );
+ }
+ };
+ }
+
+ // Create the abort callback
+ callback = callback( "abort" );
+
+ try {
+
+ // Do send the request (this may raise an exception)
+ xhr.send( options.hasContent && options.data || null );
+ } catch ( e ) {
+
+ // #14683: Only rethrow if this hasn't been notified as an error yet
+ if ( callback ) {
+ throw e;
+ }
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+} );
+
+
+
+
+// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
+jQuery.ajaxPrefilter( function( s ) {
+ if ( s.crossDomain ) {
+ s.contents.script = false;
+ }
+} );
+
+// Install script dataType
+jQuery.ajaxSetup( {
+ accepts: {
+ script: "text/javascript, application/javascript, " +
+ "application/ecmascript, application/x-ecmascript"
+ },
+ contents: {
+ script: /\b(?:java|ecma)script\b/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
+} );
+
+// Handle cache's special case and crossDomain
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ }
+} );
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function( s ) {
+
+ // This transport only deals with cross domain or forced-by-attrs requests
+ if ( s.crossDomain || s.scriptAttrs ) {
+ var script, callback;
+ return {
+ send: function( _, complete ) {
+ script = jQuery( "<script>" )
+ .attr( s.scriptAttrs || {} )
+ .prop( { charset: s.scriptCharset, src: s.url } )
+ .on( "load error", callback = function( evt ) {
+ script.remove();
+ callback = null;
+ if ( evt ) {
+ complete( evt.type === "error" ? 404 : 200, evt.type );
+ }
+ } );
+
+ // Use native DOM manipulation to avoid our domManip AJAX trickery
+ document.head.appendChild( script[ 0 ] );
+ },
+ abort: function() {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+} );
+
+
+
+
+var oldCallbacks = [],
+ rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup( {
+ jsonp: "callback",
+ jsonpCallback: function() {
+ var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
+ this[ callback ] = true;
+ return callback;
+ }
+} );
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+ var callbackName, overwritten, responseContainer,
+ jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
+ "url" :
+ typeof s.data === "string" &&
+ ( s.contentType || "" )
+ .indexOf( "application/x-www-form-urlencoded" ) === 0 &&
+ rjsonp.test( s.data ) && "data"
+ );
+
+ // Handle iff the expected data type is "jsonp" or we have a parameter to set
+ if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+ // Get callback name, remembering preexisting value associated with it
+ callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
+ s.jsonpCallback() :
+ s.jsonpCallback;
+
+ // Insert callback into url or form data
+ if ( jsonProp ) {
+ s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
+ } else if ( s.jsonp !== false ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
+ }
+
+ // Use data converter to retrieve json after script execution
+ s.converters[ "script json" ] = function() {
+ if ( !responseContainer ) {
+ jQuery.error( callbackName + " was not called" );
+ }
+ return responseContainer[ 0 ];
+ };
+
+ // Force json dataType
+ s.dataTypes[ 0 ] = "json";
+
+ // Install callback
+ overwritten = window[ callbackName ];
+ window[ callbackName ] = function() {
+ responseContainer = arguments;
+ };
+
+ // Clean-up function (fires after converters)
+ jqXHR.always( function() {
+
+ // If previous value didn't exist - remove it
+ if ( overwritten === undefined ) {
+ jQuery( window ).removeProp( callbackName );
+
+ // Otherwise restore preexisting value
+ } else {
+ window[ callbackName ] = overwritten;
+ }
+
+ // Save back as free
+ if ( s[ callbackName ] ) {
+
+ // Make sure that re-using the options doesn't screw things around
+ s.jsonpCallback = originalSettings.jsonpCallback;
+
+ // Save the callback name for future use
+ oldCallbacks.push( callbackName );
+ }
+
+ // Call if it was a function and we have a response
+ if ( responseContainer && isFunction( overwritten ) ) {
+ overwritten( responseContainer[ 0 ] );
+ }
+
+ responseContainer = overwritten = undefined;
+ } );
+
+ // Delegate to script
+ return "script";
+ }
+} );
+
+
+
+
+// Support: Safari 8 only
+// In Safari 8 documents created via document.implementation.createHTMLDocument
+// collapse sibling forms: the second one becomes a child of the first one.
+// Because of that, this security measure has to be disabled in Safari 8.
+// https://bugs.webkit.org/show_bug.cgi?id=137337
+support.createHTMLDocument = ( function() {
+ var body = document.implementation.createHTMLDocument( "" ).body;
+ body.innerHTML = "<form></form><form></form>";
+ return body.childNodes.length === 2;
+} )();
+
+
+// Argument "data" should be string of html
+// context (optional): If specified, the fragment will be created in this context,
+// defaults to document
+// keepScripts (optional): If true, will include scripts passed in the html string
+jQuery.parseHTML = function( data, context, keepScripts ) {
+ if ( typeof data !== "string" ) {
+ return [];
+ }
+ if ( typeof context === "boolean" ) {
+ keepScripts = context;
+ context = false;
+ }
+
+ var base, parsed, scripts;
+
+ if ( !context ) {
+
+ // Stop scripts or inline event handlers from being executed immediately
+ // by using document.implementation
+ if ( support.createHTMLDocument ) {
+ context = document.implementation.createHTMLDocument( "" );
+
+ // Set the base href for the created document
+ // so any parsed elements with URLs
+ // are based on the document's URL (gh-2965)
+ base = context.createElement( "base" );
+ base.href = document.location.href;
+ context.head.appendChild( base );
+ } else {
+ context = document;
+ }
+ }
+
+ parsed = rsingleTag.exec( data );
+ scripts = !keepScripts && [];
+
+ // Single tag
+ if ( parsed ) {
+ return [ context.createElement( parsed[ 1 ] ) ];
+ }
+
+ parsed = buildFragment( [ data ], context, scripts );
+
+ if ( scripts && scripts.length ) {
+ jQuery( scripts ).remove();
+ }
+
+ return jQuery.merge( [], parsed.childNodes );
+};
+
+
+/**
+ * Load a url into a page
+ */
+jQuery.fn.load = function( url, params, callback ) {
+ var selector, type, response,
+ self = this,
+ off = url.indexOf( " " );
+
+ if ( off > -1 ) {
+ selector = stripAndCollapse( url.slice( off ) );
+ url = url.slice( 0, off );
+ }
+
+ // If it's a function
+ if ( isFunction( params ) ) {
+
+ // We assume that it's the callback
+ callback = params;
+ params = undefined;
+
+ // Otherwise, build a param string
+ } else if ( params && typeof params === "object" ) {
+ type = "POST";
+ }
+
+ // If we have elements to modify, make the request
+ if ( self.length > 0 ) {
+ jQuery.ajax( {
+ url: url,
+
+ // If "type" variable is undefined, then "GET" method will be used.
+ // Make value of this field explicit since
+ // user can override it through ajaxSetup method
+ type: type || "GET",
+ dataType: "html",
+ data: params
+ } ).done( function( responseText ) {
+
+ // Save response for use in complete callback
+ response = arguments;
+
+ self.html( selector ?
+
+ // If a selector was specified, locate the right elements in a dummy div
+ // Exclude scripts to avoid IE 'Permission Denied' errors
+ jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
+
+ // Otherwise use the full result
+ responseText );
+
+ // If the request succeeds, this function gets "data", "status", "jqXHR"
+ // but they are ignored because response was set above.
+ // If it fails, this function gets "jqXHR", "status", "error"
+ } ).always( callback && function( jqXHR, status ) {
+ self.each( function() {
+ callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
+ } );
+ } );
+ }
+
+ return this;
+};
+
+
+
+
+jQuery.expr.pseudos.animated = function( elem ) {
+ return jQuery.grep( jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ } ).length;
+};
+
+
+
+
+jQuery.offset = {
+ setOffset: function( elem, options, i ) {
+ var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
+ position = jQuery.css( elem, "position" ),
+ curElem = jQuery( elem ),
+ props = {};
+
+ // Set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ curOffset = curElem.offset();
+ curCSSTop = jQuery.css( elem, "top" );
+ curCSSLeft = jQuery.css( elem, "left" );
+ calculatePosition = ( position === "absolute" || position === "fixed" ) &&
+ ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
+
+ // Need to be able to calculate position if either
+ // top or left is auto and position is either absolute or fixed
+ if ( calculatePosition ) {
+ curPosition = curElem.position();
+ curTop = curPosition.top;
+ curLeft = curPosition.left;
+
+ } else {
+ curTop = parseFloat( curCSSTop ) || 0;
+ curLeft = parseFloat( curCSSLeft ) || 0;
+ }
+
+ if ( isFunction( options ) ) {
+
+ // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
+ options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
+ }
+
+ if ( options.top != null ) {
+ props.top = ( options.top - curOffset.top ) + curTop;
+ }
+ if ( options.left != null ) {
+ props.left = ( options.left - curOffset.left ) + curLeft;
+ }
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+jQuery.fn.extend( {
+
+ // offset() relates an element's border box to the document origin
+ offset: function( options ) {
+
+ // Preserve chaining for setter
+ if ( arguments.length ) {
+ return options === undefined ?
+ this :
+ this.each( function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ } );
+ }
+
+ var rect, win,
+ elem = this[ 0 ];
+
+ if ( !elem ) {
+ return;
+ }
+
+ // Return zeros for disconnected and hidden (display: none) elements (gh-2310)
+ // Support: IE <=11 only
+ // Running getBoundingClientRect on a
+ // disconnected node in IE throws an error
+ if ( !elem.getClientRects().length ) {
+ return { top: 0, left: 0 };
+ }
+
+ // Get document-relative position by adding viewport scroll to viewport-relative gBCR
+ rect = elem.getBoundingClientRect();
+ win = elem.ownerDocument.defaultView;
+ return {
+ top: rect.top + win.pageYOffset,
+ left: rect.left + win.pageXOffset
+ };
+ },
+
+ // position() relates an element's margin box to its offset parent's padding box
+ // This corresponds to the behavior of CSS absolute positioning
+ position: function() {
+ if ( !this[ 0 ] ) {
+ return;
+ }
+
+ var offsetParent, offset, doc,
+ elem = this[ 0 ],
+ parentOffset = { top: 0, left: 0 };
+
+ // position:fixed elements are offset from the viewport, which itself always has zero offset
+ if ( jQuery.css( elem, "position" ) === "fixed" ) {
+
+ // Assume position:fixed implies availability of getBoundingClientRect
+ offset = elem.getBoundingClientRect();
+
+ } else {
+ offset = this.offset();
+
+ // Account for the *real* offset parent, which can be the document or its root element
+ // when a statically positioned element is identified
+ doc = elem.ownerDocument;
+ offsetParent = elem.offsetParent || doc.documentElement;
+ while ( offsetParent &&
+ ( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
+ jQuery.css( offsetParent, "position" ) === "static" ) {
+
+ offsetParent = offsetParent.parentNode;
+ }
+ if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {
+
+ // Incorporate borders into its offset, since they are outside its content origin
+ parentOffset = jQuery( offsetParent ).offset();
+ parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
+ parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
+ }
+ }
+
+ // Subtract parent offsets and element margins
+ return {
+ top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
+ left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
+ };
+ },
+
+ // This method will return documentElement in the following cases:
+ // 1) For the element inside the iframe without offsetParent, this method will return
+ // documentElement of the parent window
+ // 2) For the hidden or detached element
+ // 3) For body or html element, i.e. in case of the html node - it will return itself
+ //
+ // but those exceptions were never presented as a real life use-cases
+ // and might be considered as more preferable results.
+ //
+ // This logic, however, is not guaranteed and can change at any point in the future
+ offsetParent: function() {
+ return this.map( function() {
+ var offsetParent = this.offsetParent;
+
+ while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+
+ return offsetParent || documentElement;
+ } );
+ }
+} );
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
+ var top = "pageYOffset" === prop;
+
+ jQuery.fn[ method ] = function( val ) {
+ return access( this, function( elem, method, val ) {
+
+ // Coalesce documents and windows
+ var win;
+ if ( isWindow( elem ) ) {
+ win = elem;
+ } else if ( elem.nodeType === 9 ) {
+ win = elem.defaultView;
+ }
+
+ if ( val === undefined ) {
+ return win ? win[ prop ] : elem[ method ];
+ }
+
+ if ( win ) {
+ win.scrollTo(
+ !top ? val : win.pageXOffset,
+ top ? val : win.pageYOffset
+ );
+
+ } else {
+ elem[ method ] = val;
+ }
+ }, method, val, arguments.length );
+ };
+} );
+
+// Support: Safari <=7 - 9.1, Chrome <=37 - 49
+// Add the top/left cssHooks using jQuery.fn.position
+// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
+// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
+// getComputedStyle returns percent when specified for top/left/bottom/right;
+// rather than make the css module depend on the offset module, just check for it here
+jQuery.each( [ "top", "left" ], function( _i, prop ) {
+ jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
+ function( elem, computed ) {
+ if ( computed ) {
+ computed = curCSS( elem, prop );
+
+ // If curCSS returns percentage, fallback to offset
+ return rnumnonpx.test( computed ) ?
+ jQuery( elem ).position()[ prop ] + "px" :
+ computed;
+ }
+ }
+ );
+} );
+
+
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+ jQuery.each( {
+ padding: "inner" + name,
+ content: type,
+ "": "outer" + name
+ }, function( defaultExtra, funcName ) {
+
+ // Margin is only for outerHeight, outerWidth
+ jQuery.fn[ funcName ] = function( margin, value ) {
+ var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+ extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+ return access( this, function( elem, type, value ) {
+ var doc;
+
+ if ( isWindow( elem ) ) {
+
+ // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
+ return funcName.indexOf( "outer" ) === 0 ?
+ elem[ "inner" + name ] :
+ elem.document.documentElement[ "client" + name ];
+ }
+
+ // Get document width or height
+ if ( elem.nodeType === 9 ) {
+ doc = elem.documentElement;
+
+ // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
+ // whichever is greatest
+ return Math.max(
+ elem.body[ "scroll" + name ], doc[ "scroll" + name ],
+ elem.body[ "offset" + name ], doc[ "offset" + name ],
+ doc[ "client" + name ]
+ );
+ }
+
+ return value === undefined ?
+
+ // Get width or height on the element, requesting but not forcing parseFloat
+ jQuery.css( elem, type, extra ) :
+
+ // Set width or height on the element
+ jQuery.style( elem, type, value, extra );
+ }, type, chainable ? margin : undefined, chainable );
+ };
+ } );
+} );
+
+
+jQuery.each( [
+ "ajaxStart",
+ "ajaxStop",
+ "ajaxComplete",
+ "ajaxError",
+ "ajaxSuccess",
+ "ajaxSend"
+], function( _i, type ) {
+ jQuery.fn[ type ] = function( fn ) {
+ return this.on( type, fn );
+ };
+} );
+
+
+
+
+jQuery.fn.extend( {
+
+ bind: function( types, data, fn ) {
+ return this.on( types, null, data, fn );
+ },
+ unbind: function( types, fn ) {
+ return this.off( types, null, fn );
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.on( types, selector, data, fn );
+ },
+ undelegate: function( selector, types, fn ) {
+
+ // ( namespace ) or ( selector, types [, fn] )
+ return arguments.length === 1 ?
+ this.off( selector, "**" ) :
+ this.off( types, selector || "**", fn );
+ },
+
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ }
+} );
+
+jQuery.each(
+ ( "blur focus focusin focusout resize scroll click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup contextmenu" ).split( " " ),
+ function( _i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ return arguments.length > 0 ?
+ this.on( name, null, data, fn ) :
+ this.trigger( name );
+ };
+ }
+);
+
+
+
+
+// Support: Android <=4.0 only
+// Make sure we trim BOM and NBSP
+var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
+
+// Bind a function to a context, optionally partially applying any
+// arguments.
+// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
+// However, it is not slated for removal any time soon
+jQuery.proxy = function( fn, context ) {
+ var tmp, args, proxy;
+
+ if ( typeof context === "string" ) {
+ tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ args = slice.call( arguments, 2 );
+ proxy = function() {
+ return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+ return proxy;
+};
+
+jQuery.holdReady = function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+};
+jQuery.isArray = Array.isArray;
+jQuery.parseJSON = JSON.parse;
+jQuery.nodeName = nodeName;
+jQuery.isFunction = isFunction;
+jQuery.isWindow = isWindow;
+jQuery.camelCase = camelCase;
+jQuery.type = toType;
+
+jQuery.now = Date.now;
+
+jQuery.isNumeric = function( obj ) {
+
+ // As of jQuery 3.0, isNumeric is limited to
+ // strings and numbers (primitives or objects)
+ // that can be coerced to finite numbers (gh-2662)
+ var type = jQuery.type( obj );
+ return ( type === "number" || type === "string" ) &&
+
+ // parseFloat NaNs numeric-cast false positives ("")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ !isNaN( obj - parseFloat( obj ) );
+};
+
+jQuery.trim = function( text ) {
+ return text == null ?
+ "" :
+ ( text + "" ).replace( rtrim, "" );
+};
+
+
+
+// Register as a named AMD module, since jQuery can be concatenated with other
+// files that may use define, but not via a proper concatenation script that
+// understands anonymous AMD modules. A named AMD is safest and most robust
+// way to register. Lowercase jquery is used because AMD module names are
+// derived from file names, and jQuery is normally delivered in a lowercase
+// file name. Do this after creating the global so that if an AMD module wants
+// to call noConflict to hide this version of jQuery, it will work.
+
+// Note that for maximum portability, libraries that are not jQuery should
+// declare themselves as anonymous modules, and avoid setting a global if an
+// AMD loader is present. jQuery is a special case. For more information, see
+// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
+
+if ( typeof define === "function" && define.amd ) {
+ define( "jquery", [], function() {
+ return jQuery;
+ } );
+}
+
+
+
+
+var
+
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$;
+
+jQuery.noConflict = function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+};
+
+// Expose jQuery and $ identifiers, even in AMD
+// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
+// and CommonJS for browser emulators (#13566)
+if ( typeof noGlobal === "undefined" ) {
+ window.jQuery = window.$ = jQuery;
+}
+
+
+
+
+return jQuery;
+} );
diff --git a/op25/gr-op25_repeater/www/www-static/live.html b/op25/gr-op25_repeater/www/www-static/live.html
new file mode 100644
index 0000000..60afd48
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/live.html
@@ -0,0 +1,61 @@
+<html>
+<head>
+<title>OP25 Live</title>
+<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
+<script src="http://localhost:8081/hls.js"></script>
+<script>
+ var videoSrc = 'http://localhost:8081/live.m3u8';
+ var hls;
+
+function onload1() {
+ attach_hls();
+}
+function attach_hls() {
+ var video = document.getElementById('video');
+ document.getElementById('div1').innerHTML = 'Initialization state 1<br>';
+ if (Hls.isSupported()) {
+ document.getElementById('div1').innerHTML = 'Initialization state 1a<br>';
+ hls = new Hls();
+ hls.loadSource(videoSrc);
+ hls.attachMedia(video);
+ document.getElementById('div1').innerHTML = 'Initialization state 1b<br>';
+ hls.on(Hls.Events.MANIFEST_PARSED, function() {
+ document.getElementById('div1').innerHTML = 'Initialization state 1c<br>';
+ video.play();
+ document.getElementById('div1').innerHTML = 'Initialization state 1d: load completed OK<br>';
+ });
+ }
+ // hls.js is not supported on platforms that do not have Media Source
+ // Extensions (MSE) enabled.
+ //
+ // When the browser has built-in HLS support (check using `canPlayType`),
+ // we can provide an HLS manifest (i.e. .m3u8 URL) directly to the video
+ // element through the `src` property. This is using the built-in support
+ // of the plain video element, without using hls.js.
+ //
+ // Note: it would be more normal to wait on the 'canplay' event below however
+ // on Safari (where you are most likely to find built-in HLS support) the
+ // video.src URL must be on the user-driven white-list before a 'canplay'
+ // event will be emitted; the last video event that can be reliably
+ // listened-for when the URL is not on the white-list is 'loadedmetadata'.
+ else if (video.canPlayType('application/vnd.apple.mpegurl')) {
+ document.getElementById('div1').innerHTML = 'Initialization state 2<br>';
+ video.src = videoSrc;
+ video.addEventListener('loadedmetadata', function() {
+ document.getElementById('div1').innerHTML = 'Initialization state 2a<br>';
+ video.play();
+ document.getElementById('div1').innerHTML = 'Initialization state 2b: load completed OK<br>';
+ });
+ } else {
+ document.getElementById('div1').innerHTML = 'Unable to initialize HLS: failed to detect and enable media source or mp4 support<br>';
+ }
+} // end of attach_hls()
+</script>
+</head>
+<body onload="javascript:onload1();">
+<video id="video" controls height=600 width=800></video>
+<br>
+<hr>
+<div id="div1">Initialization state 0<br></div>
+</body>
+</html>
diff --git a/op25/gr-op25_repeater/www/www-static/live.m3u8 b/op25/gr-op25_repeater/www/www-static/live.m3u8
new file mode 100644
index 0000000..badeda4
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/live.m3u8
@@ -0,0 +1,3 @@
+#EXTM3U
+#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=68800,CODECS="mp4a.40.5,avc1.42000d",RESOLUTION=400x300,NAME="240"
+http://localhost:8081/hls/stream.m3u8
diff --git a/op25/gr-op25_repeater/www/www-static/main.css b/op25/gr-op25_repeater/www/www-static/main.css
new file mode 100644
index 0000000..93572c9
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/main.css
@@ -0,0 +1,1413 @@
+/*
+
+ Copyright 2020, 2021 Michael Rose
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+*/
+
+/* ------------- LIGHT MODE -------------------- */
+:root { /* default */
+ --logo: url("op25.png");
+ --cbox: url("cx-lite.png");
+ --sysmsg-text: #666;
+ --label-hold: #c00;
+ --syscrptro: #f00000; /* encrypted text */
+
+ --bg-color: #fff; /* main page background color */
+ --sysmsg-background: #f9f9f9;
+ --div-border-1: grey; /* border color for a main div */
+ --div-border-2: #ccc; /* a lighter div border (sysMsg) */
+ --div-background-1: #eee;
+
+ --button-grad-1: #31687e; /* button fades (skip, hold, home, config, etc) */
+ --button-grad-2: #56a0bd;
+ --button-bord-1: gray;
+ --button-text-1: white;
+ --button-text-2: black;
+
+ --table-grad-1: #31687e; /* table headers gradient */
+ --table-grad-2: #56a0bd;
+ --table-header-text: #fff;
+
+ --hover-1: #ddd; /* Table hover */
+
+ --status-grad-1: white; /* main display border fade effect */
+ --status-grad-2: silver;
+ --status-border: #f00; /* intended for no gradient browser, not used */
+
+ --nav-grad-1: #bbb;
+ --nav-grad-2: #ccc;
+ --nav-background: #bbb; /* no grad browser support */
+
+ --display-grad-1: LightGray; /* the main tg/system display bg fade */
+ --display-grad-2: White; /* 2 is the middle, 1 is the upper/lower */
+
+ --red-value: #f00000; /* red text, others */
+ --value: #000060; /* main display, tg id, source, freq, and others */
+
+ --system-text: #000060; /* main display, system, talkgroup */
+ --gray-text-1: #999;
+
+ --default-text: #000;
+
+
+ --label: #484848; /* misc lables */
+ --label-sm: #444;
+
+ --input-background: #fff;
+ --input-background-2: #eee;
+ --input-text: #000;
+
+ /* talkgroup colors: */
+ --c1: #0066ff; /* blue - SmartColor 1 */
+ --c2: #ff0000; /* red - SmartColor 2 */
+ --c3: #ff6600; /* orange - SmartColor 3 */
+ --c4: #000; /* black */
+ --c5: #800080; /* purple */
+ --c6: #00cc00; /* lime green */
+ --c7: #009933; /* green */
+ --c8: #cc9900; /* yellow */
+ --c9: #a6a6a6; /* gray */
+ --c10: #ff6666; /* pink (!) */
+ --c11: #005580; /* lighter blue */
+}
+
+/* ------------- DARK MODE -------------------- */
+
+[data-theme="dark"] {
+ --logo: url("op25-dark.png");
+ --cbox: url("cx.png");
+ --sysmsg-text: #666;
+ --label-hold: #ff0000;
+ --syscrptro: #f00000; /* encrypted text */
+
+ --bg-color: Black; /* main page background color */
+ --sysmsg-background: #060606;
+ --div-border-1: #444; /* border color for any old div */
+ --div-border-2: #ccc; /* a lighter div border (sysMsg) */
+ --div-background-1: #eee;
+
+ --button-grad-1: #444; /* button fades (skip, hold, home, config, etc) */
+ --button-grad-2: black;
+ --button-bord-1: gray;
+ --button-text-1: yellow;
+ --button-text-2: white;
+
+ --table-grad-1: #444; /* table headers */
+ --table-grad-2: black;
+ --table-header-text: #ddd;
+
+ --hover-1: #333; /* Table hover */
+
+ --status-grad-1: #cca300; /* main display border fade effect */
+ --status-grad-2: #0c0;
+ --status-border: #f00; /* intended for no gradient browser, not used */
+
+ --nav-grad-1: #225; /* nav menu fade effect */
+ --nav-grad-2: #444;
+ --nav-background: #222; /* no grad browser support */
+
+ --display-grad-1: #222; /* the main tg/system display bg fade */
+ --display-grad-2: black; /* 2 is the middle, 1 is the upper/lower */
+
+ --red-value: #ff0000; /* red text, others */
+ --value: #66ff66; /* main display, tg id, source, freq, and others */
+
+ --system-text: #66ff66; /* main display, system, talkgroup */
+ --gray-text-1: #eee;
+
+ --default-text: #ddd;
+
+ --label: #eee; /* misc lables */
+ --label-sm: #eee;
+
+ --input-background: #000;
+ --input-background-2: #111;
+ --input-text: #fff;
+
+
+ /* talkgroup & tag colors: */
+ --c1: #0066ff; /* blue - SmartColor 1 */
+ --c2: #ff0000; /* red - SmartColor 2 */
+ --c3: #ff6600; /* orange */
+ --c4: #fff; /* white */
+ --c5: #9966ff; /* purple */
+ --c6: #00ff00; /* lime green */
+ --c7: #009933; /* green */
+ --c8: #ffff00; /* yellow */
+ --c9: #eee; /* gray */
+ --c10: #ff3355; /* pink (!) */
+ --c11: #0080C0; /* lighter blue */
+
+}
+
+/* END DARK MODE */
+
+
+body {
+ background-color: var(--bg-color);
+}
+
+/* BEGIN 2 COLUMN LAYOUT ELEMENTS */
+
+ * {
+ box-sizing: border-box;
+ }
+
+ /* Create two equal columns that floats next to each other */
+ .column {
+ float: left;
+ width: 50%;
+ padding: 5px;
+/* height: 300px; /* Should be removed. Only for demonstration */ */
+ }
+
+ /* Clear floats after the columns */
+ .row:after {
+ content: "";
+ display: table;
+ clear: both;
+ }
+
+ /* Responsive layout - makes the two columns stack on top of each other instead of next to each other */
+ @media screen and (max-width: 740px) {
+ .column {
+ width: 100%;
+ }
+ }
+
+
+/* END 2 COLUMN LAYOUT ELEMENTS */
+
+
+.main {
+ margin-top: 5px;
+/* make margin-top 60px for fixed nav-bar, see also .nav-bar below. */
+
+}
+
+a {
+ color: var(--red-value);
+}
+
+
+/*
+#div_status body {
+
+ background-color: var(--bg-color);
+ font-family: Arial, Helvetica, sans-serif;
+}
+ */
+
+header {
+ /* empty */
+}
+
+#div_status table { /* rx screen */
+ border-collapse: collapse;
+/* font-family: "Courier New", Courier, Monospace; */
+/* font-family: Arial, Helvetica, sans-serif; */
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ border: 1px solid var(--div-border-1);
+ width: 100%;
+}
+
+
+#div_status th {
+
+ border: 1px solid var(--div-border-1);
+ padding: 3px;
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--table-header-text);
+ font-weight: bold;
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--table-grad-1), var(--table-grad-2));
+}
+
+#div_status td {
+ border: 0px solid var(--div-border-1);
+ padding: 3px;
+ font-size: 10pt;
+}
+
+#div_images table {
+ width: 730px;
+ border: 1px solid var(--div-border-1);
+ background-color: black;
+}
+
+#div_s2 table {
+ border: 0px solid var(--div-border-1);
+ }
+
+#div_s2 td {
+ border-bottom: 1px solid var(--div-border-1);
+ border-top: 1px solid var(--div-border-1);
+ border-left: 0px;
+ border-right: 0px;
+ padding: 3px;
+ background: transparent;
+}
+
+.tt {
+ font-family:'Lucida Console', monospace;
+}
+
+.colorPicker {
+ /* use this to set the background color
+ of the color picker widget, default for now */
+}
+
+.colorReplacer {
+ /* just the color picker button */
+ background: var(--div-border-2);
+}
+
+input[type="checkbox"] {
+ display:none;
+}
+
+input[type="checkbox"] + label {
+ color: var(--default-text);
+ font-family:Arial, sans-serif;
+ font-size:14px;
+}
+
+input[type="checkbox"] + label span {
+ display:inline-block;
+ width:19px;
+ height:19px;
+ margin:-1px 4px 0 0;
+ vertical-align:middle;
+ background:var(--cbox) left top no-repeat;
+ cursor:pointer;
+}
+
+input[type="checkbox"]:checked + label span {
+ background:var(--cbox) -19px top no-repeat;
+}
+
+
+select {
+ margin: 0px 10px 0px 0px;
+ width: 150px;
+ padding: 2px 2px 2px 2px;
+ font-size: 14px;
+ border: 0px solid var(--div-border-2);
+ height: 20px;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+ color: var(--default-text);
+ background: url(da.png) 100% / 20% no-repeat var(--sysmsg-background);
+}
+
+button {
+ border-color: var(--button-bord-1);
+ color: var(--button-text-1);
+ padding: 4px 6px 8px 6px;
+ text-decoration: none;
+ margin: 1px 1px 1px 1px;
+ cursor: pointer;
+ font-size: 14px;
+ box-shadow: 0 1px 1px 0 rgba(0,0,0,0.2), 0 2px 5px 0 rgba(0,0,0,0.19);
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--button-grad-1), var(--button-grad-2));
+}
+
+button:hover {
+ background: linear-gradient(var(--button-grad-2), var(--button-grad-1));
+}
+
+.btn {
+ color: var(--button-text-1);
+}
+
+.btnExp {
+ color: var(--button-text-2);
+ background-color: var(--bg-color);
+ background: none;
+ float: right;
+ border: 0px solid var(--div-border-1);
+ cursor: pointer;
+}
+
+/* CAUTION: IE hackery ahead */
+select::-ms-expand {
+ display: none; /* remove default arrow on ie10 and ie11 */
+}
+
+/* target Internet Explorer 9 to undo the custom arrow */
+@media screen and (min-width:0\0) {
+ select {
+ background:none\9;
+ padding: 5px\9;
+ }
+}
+
+.time { /* 24 hour time hh:mm:ss -- not currently used */
+ text-overflow: hidden;
+ max-width: 8ch;
+}
+
+.historyLabel {
+ width: 725px;
+/*
+ background: linear-gradient(
+ 180deg, var(--bg-color) calc(50% - 1px),
+ var(--div-border-1) calc(50%),
+ var(--bg-color) calc(50% + 1px)
+ );
+ */
+
+ vertical-align: bottom;
+ border-collapse: collapse;
+/* height: 48px; */
+ border: 0px solid var(--div-border-1);
+ margin: 0px 0px 0px 1px;
+ padding: 0px 6px 4px 6px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+}
+
+.hlabel {
+ background-color: var(--bg-color);
+}
+
+.history {
+ width: 705px;
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ padding: 3px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+}
+
+.history th, td {
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ color: var(--default-text);
+ padding: 3px;
+}
+
+.history th {
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--table-grad-1), var(--table-grad-2));
+ color: var(--table-header-text);
+/* fixed table heading */
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 2;
+}
+
+.history td {
+ font-size: 10pt;
+}
+
+.plot td {
+ text-align: center;
+}
+
+#div_logs {
+ width: 730px;
+}
+
+#bandplan th, td {
+/* background: none; */
+ border: 0px solid;
+}
+
+hr {
+ width: 718px;
+ float: left;
+ padding: 0px;
+}
+
+.control-button { /* skip/hold/lockout buttons */
+ border-color: var(--button-bord-1);
+ height: 42px;
+ color: var(--button-text-1);
+ padding: 10px 10px;
+ text-decoration: none;
+ margin: 1px 1px;
+ cursor: pointer;
+ width: 98px;
+ font-size: 14px;
+ font-weight: bold;
+ box-shadow: 0 1px 1px 0 rgba(0,0,0,0.2), 0 2px 5px 0 rgba(0,0,0,0.19);
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--button-grad-1), var(--button-grad-2));
+}
+
+.control-button:hover {
+ background: linear-gradient(var(--button-grad-2), var(--button-grad-1));
+}
+
+.controlsDisplay { /* holds buttons, and display */
+ width: 725px; /* 730 */
+ border: 0px solid var(--div-border-1);
+ vertical-align: top;
+ height: 178px;
+ padding: 2px;
+ box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2), 0 3px 10px 0 rgba(0,0,0,0.19);
+ background: var(--status-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--status-grad-1), var(--status-grad-2));
+}
+
+.controls { /* skip/hold/lockout buttons (1) */
+
+ border: 1px solid var(--button-bord-1);
+ width: 100px;
+ float: left;
+ height: 100%;
+ text-align: center;
+}
+
+.cfg_list {
+ border: 1px solid var(--div-border-1);
+ padding: 5px;
+ width: 260px;
+}
+
+.displaySettings {
+ border: 1px solid var(--div-border-1);
+ padding: 0px;
+ width: 720px;
+
+}
+
+.statDisplay { /* main display - freq, sys, tgid (2) */
+ padding: 0px;
+ width: 522px;
+ float: left;
+ position: relative;
+ display: inline-block;
+ border: 1px solid (var(--div-border-1));
+ height: 100%;
+ background: var(--display-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--display-grad-1), var(--display-grad-2), var(--display-grad-1));
+}
+
+.sysMsg { /* OP25 logo and message box on right (3) */
+ padding: 0px;
+ /* display: inline-block; */
+ float: right; /* works left or right, right gives margin in between this & 2 */
+ width: 95px;
+ height: 99%;
+ background-color: var(--sysmsg-background);
+ background-image: var(--logo);
+ background-repeat: no-repeat;
+ background-position: right;
+ border: 1px solid var(--div-border-1);
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--sysmsg-text);
+ font-size: 8pt;
+}
+
+.aboutMsg { /* OP25 logo and message box on right (3) */
+ padding: 0px;
+ /* display: inline-block; */
+ float: right; /* works left or right, right gives margin in between this & 2 */
+ width: 95px;
+ height: 99%;
+ background-color: var(--sysmsg-background);
+ background-image: var(--logo);
+ background-repeat: no-repeat;
+ background-position: right;
+ border: 0px solid var(--div-border-2);
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--sysmsg-text);
+ font-size: 8pt;
+}
+
+div.info { /* main info container for the two tables */
+ width: 730px;
+ border: 0px solid var(--div-border-1);
+ display: inline-block;
+}
+
+
+div.system { /* system frequencies container that holds the table */
+ float: left;
+ width: 48%;
+ height: auto;
+ border: 0px solid var(--div-border-1);
+}
+
+div.adjacent { /* adjacent sites container that holds the table */
+ margin-left: 29px;
+ float: left;
+ width: 48%;
+ height: auto;
+ border: 0px solid var(--div-border-1);
+}
+
+/* labels, values, system and tg text */
+
+.copyr {
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 14px;
+ color: var(--label);
+ float: right;
+ margin-top: 22px;
+ margin-right: 4px;
+}
+
+.label {
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--label);
+}
+
+.label-hold {
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--label-hold);
+ font-size: 8pt;
+ font-weight: bold;
+ text-align: center;
+ vertical-align: center;
+ height: 50%;
+}
+
+.label-sm {
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--label-sm);
+ font-size: 8pt;
+ padding: 2px;
+}
+
+.label-lc { /* Last Command text */
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--label-sm);
+ font-size: 8pt;
+ padding: 2px;
+ text-align: center;
+}
+
+.red_value {
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--red-value);
+ font-weight: bold;
+}
+
+.value {
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--value);
+ font-weight: bold;
+}
+
+.systgid { /* System and Talkgroup Text */
+ font-family: Arial, Helvetica, sans-serif;
+/* color: var(--system-text); */
+ font-weight: bold;
+ font-size: 24px;
+}
+
+.syscrypto { /* alg/key text */
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--syscrypto);
+ font-size: 24px;
+}
+
+.boxtitle {
+ font-weight: bold;
+ text-align: left;
+}
+
+.nac { /* the whole NAC string... NAC, freq tsbks, etc. */
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--system-text);
+ font-weight: bold;
+ font-size: 20px;
+}
+
+.s1 {
+ border: 0px solid var(--gray-text-1);
+ width: 730px;
+}
+
+.s2 {
+ border: 0px solid var(--gray-text-1);
+ position: relative;
+ display: inline-block;
+ max-height: 112px;
+ width: 512px;
+ padding: 5px;
+ margin: 0 0 0 2px;
+}
+
+.copyright-text {
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--system-text);
+/* font-size: 10px; */
+}
+
+.nav-ul {
+ list-style-type: none;
+ margin: 0;
+ padding: 0;
+ overflow: hidden;
+ background-color: var(--nav-background);
+ background: linear-gradient(var(--nav-grad-1), var(--nav-grad-2));
+}
+
+.nav-li {
+ float: left;
+ border-right: 1px solid var(--div-border-1);
+ background: linear-gradient(var(--nav-grad-1), var(--nav-grad-2));
+
+}
+
+.nav-li-active {
+ float: left;
+ border-right: 1px solid var(--div-border-1);
+}
+
+.nav-bar {
+ width: 730px;
+ padding: 0;
+ border: 1px solid var(--div-border-1);
+
+
+/* uncomment below for fixed top nav-bar */
+/*
+ position: fixed;
+ top: 5px;
+ z-index: 99;
+ */
+}
+
+.psbutton { /* Preset buttons */
+ width: 95px;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: "";
+}
+
+
+.nav-button {
+ background-color: var(--nav-background);
+ background: linear-gradient(var(--nav-grad-1), var(--nav-grad-2));
+ color: var(--button-text-2);
+ width: 85px;
+ border: 0px;
+ padding: 8px; /* 20 */
+ display: block;
+ font-size: 14px;
+ font-weight: bold;
+}
+
+.nav-button2 {
+ background-color: var(--nav-background);
+ background: linear-gradient(var(--nav-grad-1), var(--nav-grad-2));
+ color: var(--button-text-2);
+ width: 15px;
+ border: 0px;
+ padding: 8px; /* 20 */
+ display: block;
+ font-size: 14px;
+ font-weight: bold;
+}
+
+.nav-button-active {
+ background-color: var(--button-grad-2);
+ background: linear-gradient(var(--button-grad-2), var(--button-grad-1));
+ color: var(--button-text-1);
+ width: 85px;
+ border: 0px;
+ padding: 8px; /* 20 */
+ display: block;
+ font-size: 14px;
+ font-weight: bold;
+}
+
+.nav-button:hover {
+ background-color: var(--button-grad-2);
+ background: linear-gradient(var(--button-grad-2), var(--button-grad-1));
+ color: var(--button-text-1);
+ cursor: pointer;
+}
+
+.nav-button-active:hover {
+ background-color: var(--button-grad-1);
+ background: linear-gradient(var(--button-grad-1), var(--button-grad-2));
+ color: var(--button-text-1);
+}
+/*
+
+#div_settings table {
+ border-color: var(--div-border-1);
+}
+
+#div_settings tr {
+ border-top: none;
+ border-bottom: solid;
+}
+
+#div_settings th.boxtitle-th {
+ text-align: left;
+}
+
+.div_settings th {
+ max-width: 75px;
+ border-style: none;
+ padding: 3px;
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 12px;
+ background: var (--div-background-1);
+ color: var(--default-text);
+ text-align: right;
+ font-weight: normal;
+}
+
+#div_settings td {
+ max-width: 75px;
+ border-style: none;
+ font-weight: bold;
+ text-align: right;
+}
+ */
+
+
+.dsettings {
+ width: 730px;
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ padding: 3px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+}
+
+.dsettings th, td {
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ color: var(--default-text);
+ padding: 5px;
+}
+
+.dsettings th {
+ color: var(--table-header-text);
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--table-grad-1), var(--table-grad-2));
+}
+
+.dsettings td {
+ padding: 10px;
+ font-size: 10pt;
+ border: 1px solid var(--div-border-1);
+}
+
+.dsettings input[type="text"] {
+ height: 14px;
+ width: 75%;
+ padding: 4px;
+ font-size: 12pt;
+ background-color: var(--input-background-2);
+ color: var(--input-text);
+ border: 0px solid var( --div-border-1);
+ border-radius: 4px;
+}
+
+
+.editor {
+ width: 705px;
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ padding: 3px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+
+}
+
+.editor th, td {
+ border-collapse: collapse;
+ border: 1px solid var(--div-border-1);
+ color: var(--default-text);
+ padding: 3px;
+}
+
+.editor th {
+ color: var(--table-header-text);
+ background: var(--button-grad-1); /* For browsers that do not support gradients */
+ background: linear-gradient(var(--table-grad-1), var(--table-grad-2));
+
+/* fixed table heading */
+ position: -webkit-sticky;
+ position: sticky;
+ top: 0;
+ z-index: 2;
+}
+
+.editor td {
+ font-size: 10pt;
+ border: 1px solid var(--div-border-1);
+}
+
+#editor input {
+ height: 28px;
+ width: 95%;
+ padding: 4px;
+ font-size: 12pt;
+ background-color: var(--input-background);
+ color: var(--input-text);
+ border: 0px solid var( --div-border-1);
+ border-radius: 4px;
+}
+
+input[type="file"] {
+ height: 28px;
+ padding: 4px;
+ background-color: var(--input-background);
+ color: var(--input-text);
+ border: 1px solid var( --div-border-1);
+ border-radius: 4px;
+}
+
+#editor .delbutton {
+ color: var(--red-value);
+ background-color: var(--input-background);
+}
+
+#editor-help {
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ width: 696px;
+ padding: 4px;
+ background-color: var(--input-background);
+ color: var(--default-text);
+ border: 1px solid var( --div-border-1);
+ border-radius: 4px;
+}
+
+.tsv-controls {
+/* position: fixed; */
+ background-color: var(--bg-color);
+ width: 100%;
+}
+
+#save-div {
+ position: fixed;
+ bottom: 0;
+ right: 0;
+ background-color: var(--bg-color);
+}
+
+#editor .savebutton {
+ /* empty */
+}
+
+#editor .newtg {
+ color: var(--system-text:);
+ animation: blinker 2s linear infinite;
+}
+
+.tsv {
+ width: 705px;
+ border-collapse: collapse;
+ border: 0px solid var(--bg-color);
+ padding: 3px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+}
+
+.tsv td, tr {
+ border-collapse: collapse;
+ border: 0px;
+}
+
+
+.footer {
+ position: fixed;
+ left: 5;
+ border: 2px solid var(--div-border-1);
+ bottom: 0;
+ width: 702px;
+ background-color: var(--sysmsg-background);
+ color: white;
+ text-align: center;
+ height: 4rem;
+}
+
+
+#displaySettings input[type=text] {
+ width: 400px;
+ height: 24px;
+ padding: 4px;
+ background-color: var(--input-background);
+ color: var(--input-text);
+ border: 1px solid var( --div-border-1);
+ border-radius: 4px;
+}
+
+.scolor {
+ width: 500px;
+ border-collapse: collapse;
+ border: 0px solid var(--div-border-1);
+ padding: 3px;
+ font-family: Verdana, Arial, Helvetica, sans-serif;
+ color: var(--default-text);
+ font-weight: normal;
+
+}
+
+.scolor th, td {
+ border-collapse: collapse;
+ border: 0px solid var(--div-border-1);
+ color: var(--default-text);
+ padding: 3px;
+}
+
+/*
+#div_settings input[type=text] {
+ max-width: 200px;
+ border-top: none;
+ border-bottom-width: 1px;
+ border-bottom: dotted;
+ border-right: none;
+ border-left: none;
+ text-align: right;
+}
+ */
+
+#div_settings input[type=button] {
+ max-width: 75px;
+ padding: 10px;
+ color: var(--red-value);
+ border: 0;
+}
+
+#div_settings select {
+ max-width: 100px;
+ padding: 0;
+ border: 0;
+}
+
+#div_settings option {
+ max-width: 100px;
+ padding: 0;
+ border: 0;
+}
+
+.boxtitle {
+ text-align: left;
+}
+
+div#cfg_list_area select {
+ width: 250px;
+ max-width: 250px;
+}
+
+#div_rx_opts td {
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 12px;
+ border-style: none;
+}
+
+#div_rx_opts input[type=text] {
+ max-width: 75px;
+ border-top: none;
+ border-bottom-width: 1px;
+ border-bottom: dotted;
+ border-right: none;
+ border-left: none;
+ text-align: right;
+}
+
+.help {
+ max-width: 640px;
+ font-family: Arial, Helvetica, sans-serif;
+ color: var(--default-text);``
+}
+
+
+.aboutTable {
+ width: 730px;
+ border: 1px solid var(--div-border-1);
+ vertical-align: top;
+ height: 178px;
+ padding: 2px;
+ box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2), 0 3px 10px 0 rgba(0,0,0,0.19);
+ background: var(--sysmsg-background); /* For browsers that do not support gradients */
+/* background: linear-gradient(var(--display-grad-1), var(--display-grad-2), var(--display-grad-1)); */
+}
+
+.aboutLogo {
+ height: 178px;
+ background-image: var(--logo);
+}
+
+.c {
+ /* no color selected */
+}
+
+@keyframes blinker {
+ 50% {
+ opacity: 0;
+ }
+}
+
+/*
+.example_blinker {
+ color: var(--c1);
+ background-color: var(--c3);
+ animation: blinker 1s linear infinite;
+}
+*/
+
+.enc { /* the enc symbol in the freq table */
+ font-size: 9pt;
+ color: var (--default-text);
+ animation: blinker 1s linear infinite;
+}
+
+.c0 {
+ /* no color, leave blank so parent can color the element */
+}
+/*
+
+.c1 {
+ color: var(--c1);
+}
+
+.c2 {
+ color: var(--c2);
+}
+
+.c3 {
+ color: var(--c3);
+}
+
+.c4 {
+ color: var(--c4);
+}
+
+.c5 {
+ color: var(--c5);
+}
+
+.c6 {
+ color: var(--c6);
+}
+
+.c7 {
+ color: var(--c7);
+}
+
+.c8 {
+ color: var(--c8);
+}
+
+.c9 {
+ color: var(--c9);
+}
+
+.c10 {
+ color: var(--c10);
+}
+
+.c11 {
+ color: var(--c11);
+}
+
+.c97 {
+ color: var(--c8);
+ background-color: var(--c1);
+ animation: blinker 1.5s linear infinite;
+}
+
+.c98 {
+ color: white;
+ background-color: var(--c1);
+ animation: blinker 1.5s linear infinite;
+}
+
+.c99 {
+ color: var(--c4);
+ background-color: var(--c10);
+ animation: blinker 1.5s linear infinite;
+}
+ */
+
+table.fixed {
+ table-layout: fixed;
+ border-collapse: collapse;
+}
+
+table.fixed td {
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+table.fixed tr {
+ border-bottom: 1px solid var(--hover-1);
+}
+
+
+table.fixed tr:hover {
+ background-color: var(--hover-1);
+}
+
+
+table.rxsys {
+ table-layout: fixed;
+}
+
+table.rxsys td {
+/*
+ overflow: hidden;
+ white-space: nowrap;
+ */
+}
+
+table.rxsys tr:hover {
+ background-color: var(--hover-1);
+}
+
+
+#searchInput {
+ background-image: url('search.png');
+ background-position: 10px 10px;
+ background-repeat: no-repeat;
+ background-color: var(--sysgmsg-background);
+ color: var(--default-text);
+ width: 100%;
+ font-size: 16px;
+ padding: 12px 20px 12px 40px;
+ border: 1px solid var(--div-border-1);
+ margin-bottom: 12px;
+}
+
+#searchTable {
+ border-collapse: collapse;
+ width: 100%;
+ border: 1px solid var(--div-border-1);
+ font-size: 18px;
+}
+
+#searchTable th, #myTable td {
+ text-align: left;
+ padding: 12px;
+}
+
+#searchTable tr {
+ border-bottom: 1px solid var(--div-border-1);
+}
+
+#searchTable tr.header, #searchTable tr:hover {
+ background-color: var(--div-border-1);
+}
+
+/* these are the little divs for the search box and css download icon in the search windows */
+.stc {
+ height: auto;
+ overflow: hidden;
+}
+
+.sr {
+ width: 40px;
+ float: right;
+
+}
+
+.sl {
+ width: auto;
+ overflow: hidden;
+}
+
+
+/* Custom dialog styles */
+#popup_title {
+ font-size: 14px;
+ font-weight: bold;
+ text-align: center;
+ line-height: 1.75em;
+ color: #FFFFFF;
+ background: #006699;
+ border: solid 1px #006699;
+ border-bottom: solid 1px #006699;
+ cursor: default;
+ padding: 0em;
+ margin: 0em;
+}
+
+#popup_container {
+ font-family: AntipastoRegular, sans-serif;
+ font-size: 14px;
+ min-width: 300px; /* Dialog will be no smaller than this */
+ max-width: 600px; /* Dialog will wrap after this width */
+ background: #FFFFFF;
+ border: solid 5px #006699;
+ color: #000000;
+ -moz-border-radius: 5px;
+ -webkit-border-radius: 5px;
+ border-radius: 5px;
+}
+
+#popup_content {
+ /*background: 16px 16px no-repeat url(images/info.gif);*/
+ padding: 1em 1.75em;
+ margin: 0em;
+}
+
+/*
+#popup_content.alert {
+ background-image: url(images/info.gif);
+}
+
+#popup_content.confirm {
+ background-image: url(images/important.gif);
+}
+
+#popup_content.prompt {
+ background-image: url(images/help.gif);
+}
+*/
+
+#popup_message {
+ /*padding-left: 10px;*/
+ margin:0px auto;
+}
+
+#popup_panel {
+ text-align: center;
+ margin: 1em 0em 0em 1em;
+}
+
+#popup_prompt {
+ margin: .5em 0em;
+}
+
+
+#popup_container INPUT[type='button'] {
+ width: 100px;
+ height: 30px;
+ border: outset 2px #006699;
+ color: #FFFFFF;
+ background: #006699;
+}
+
+
+/* some expiremental stuff below, not being used. */
+
+
+/* signal stuff is for a signal strength indicator (3 bars) */
+/* not currently used */
+
+.signal-icon {
+ height: 18px;
+ width: 18px;
+ /* To show you the power of flexbox! */
+ display: flex;
+ /* Bars should be placed left to right */
+ flex-direction: row;
+ /* Evenly space the bars with space in between */
+ justify-content: space-between;
+ /* Sink the bars to the bottom, so they go up in steps */
+ align-items: baseline;
+}
+.signal-icon .signal-bar {
+ /* 4 + 3 + 4 + 3 + 4 = 18px (as set above)
+ 4px per bar and 3px margins between */
+ width: 4px;
+ /* All bars faded by default */
+ opacity: 30%;
+ /* Choose a color */
+ background: #aa2200;
+}
+
+/* 3 different heights for 3 different bars */
+.signal-icon .signal-bar:nth-child(1) { height: 40%; }
+.signal-icon .signal-bar:nth-child(2) { height: 70%; }
+.signal-icon .signal-bar:nth-child(3) { height: 100%; }
+
+/* Emphasize different bars depending on
+ weak/medium/strong classes */
+.signal-icon.weak .signal-bar:nth-child(1),
+.signal-icon.medium .signal-bar:nth-child(1),
+.signal-icon.medium .signal-bar:nth-child(2),
+.signal-icon.strong .signal-bar:nth-child(1),
+.signal-icon.strong .signal-bar:nth-child(2),
+.signal-icon.strong .signal-bar:nth-child(3)
+{ opacity: 100%; }
+
+
+/* spinner */
+.loader {
+ display: block;
+ margin-left: 350px;
+ margin-right: auto;
+ position: absolute;
+ display: none;
+ width: 40%;
+ border: 8px solid var(--div-border-1);
+ border-radius: 50%;
+ border-top: 8px solid var(--div-border-2);
+ width: 25px;
+ height: 25px;
+ -webkit-animation: spin 2s linear infinite; /* Safari */
+ animation: spin 2s linear infinite;
+}
+
+/* Safari */
+@-webkit-keyframes spin {
+ 0% { -webkit-transform: rotate(0deg); }
+ 100% { -webkit-transform: rotate(360deg); }
+}
+
+@keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+}
+
+
+/*
+Start by setting display:none to make this hidden.
+ Then we position it in relation to the viewport window
+ with position:fixed. Width, height, top and left speak
+ for themselves. Background we set to 80% white with
+ our animation centered, and no-repeating
+.modal {
+ display: none;
+ position: fixed;
+ z-index: 1000;
+ top: 0;
+ left: 0;
+ height: 100%;
+ width: 100%;
+ background: rgba( 255, 255, 255, .8 )
+ url('FhHRx.gif')
+ 50% 50%
+ no-repeat;
+}
+
+When the body has the loading class, we turn
+ the scrollbar off with overflow:hiddenbody.loading .modal {
+ overflow: hidden;
+}
+
+Anytime the body has the loading class, our
+ modal element will be visiblebody.loading .modal {
+ display: block;
+}
+ */
diff --git a/op25/gr-op25_repeater/www/www-static/main.js b/op25/gr-op25_repeater/www/www-static/main.js
new file mode 100644
index 0000000..9acf00e
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/main.js
@@ -0,0 +1,2851 @@
+// Copyright 2017, 2018, 2019, 2020, 2021, 2022 Max H. Parke KA1RBI
+// Copyright 2020, 2021, 2022 Michael Rose
+//
+// This file is part of OP25
+//
+// OP25 is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 3, or (at your option)
+// any later version.
+//
+// OP25 is distributed in the hope that it will be useful, but WITHOUT
+// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+// License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with OP25; see the file COPYING. If not, write to the Free
+// Software Foundation, Inc., 51 Franklin Street, Boston, MA
+// 02110-1301, USA.
+
+var lastUpdated = "28-Oct-2022";
+
+var d_debug = 0;
+var http_req = new XMLHttpRequest();
+var counter1 = 0;
+var error_val = null;
+var current_tgid = null;
+var active_tgid = null;
+var active_nac = null;
+var send_busy = 0;
+var send_qfull = 0;
+var send_queue = [];
+var req_cb_count = 0;
+var request_count = 0;
+var nfinal_count = 0;
+var n200_count = 0;
+var r200_count = 0;
+var SEND_QLIMIT = 5;
+var summary_mode = true;
+var enable_changed = false;
+var enable_status = [];
+var last_srcaddr = [];
+var last_srctag = [];
+var last_alg = [];
+var last_algid = [];
+var last_keyid = [];
+var tgid_files = {};
+var srcid_files = {};
+var channel_id = {};
+var freqTable = true;
+var chsize = 1;
+var evsize = 1;
+var ersize = 1;
+var event_source = null; // must be in global scope for Babysitter to work.
+
+window.g_change_freq = [];
+window.g_cc_event = [];
+window.src = [];
+
+var intvAlias = null;
+var intvCss = null;
+localStorage.AliasTableUpdated == true;
+localStorage.ColorsTableUpdated == true;
+
+var encsym = "&#x2205;";
+
+const zeroPad = (num, places) => String(num).padStart(places, '0'); // leading zeros for single digit time values
+
+function do_onload() {
+ $('#div_status').show(window.animateSpeed);
+ $('#babysitter').hide();
+ $('#b1').addClass('nav-button-active');
+ $('#uiupdated').html(lastUpdated);
+ document.documentElement.setAttribute('data-theme', 'dark');
+ window.siteAlias = null;
+
+ intvAlias = setInterval(getSiteAlias, 5000);
+ intvCss = setInterval(generateCSS, 4000);
+ resetFileReload = setInterval(rstFileReload, 12000)
+
+ connect();
+ generateCSS();
+ getSiteAlias();
+ beginJsonSettings();
+
+ accColorSel();
+ for (i = 1; i < 100; i ++) {
+ $('#unk_default').append(new Option(i, i));
+ }
+ window.animateSpeed = $('#ani_speed').val();
+}
+
+// vars set when saving things...
+// localStorage.AliasTableUpdated == true;
+// localStorage.ColorsTableUpdated == true;
+
+$(document).ready(function() {
+// // populate url into oplog url field
+// var x = window.location.origin.split( ':' );
+// var y = x[0] + ':' + x[1] + ':5000';
+// $('#oplogUrl').val(y);
+ loadHelp();
+});
+
+function connect() {
+ event_source = new EventSource('./stream');
+ event_source.addEventListener('message', eventsource_listener);
+ event_source.onerror = function() {
+ event_source.close();
+ }
+ setReconnect();
+}
+
+function eventsource_listener(event) {
+ dispatch_commands(event.data);
+}
+
+// Watchdog - watches /stream, reacts when lost/restored
+function setReconnect() {
+ // readyState values: 0 = connecting, 1 = open, 2 = closed
+ var reconnecting = false;
+
+ // do we need to setInterval with a var here since we call setReconnect again?
+
+ setInterval(() => {
+ if (event_source.readyState == 2) {
+ reconnecting = true;
+ $('#babysitter').show();
+ $('#estat').html(event_source.readyState);
+ connect();
+ } else if (reconnecting) {
+ reconnecting = false
+ $('#estat').html(event_source.readyState);
+ if (!event_source.readyState == 0)
+ $('#estat').html('OK');
+ $('#babysitter').hide();
+ }
+ }, 3000);
+}
+
+
+function rstFileReload() {
+ if (event_source == null || event_source.readyState != 1)
+ return;
+ // forces the alias and colors info to reload in case user
+ // makes changes to them from another browser.
+ localStorage.AliasTableUpdated == true;
+ localStorage.ColorsTableUpdated == true;
+}
+
+function navOplog() {
+ window.open($('#oplogUrl').val());
+}
+
+function phaseType(nac) {
+ // reset the UI to a Phase 1 display (untested)
+ window[nac + 'flavor'] = null;
+}
+
+function nav_update(command) {
+ var names = [
+ 'b1',
+ 'b2',
+ 'b3',
+ 'b4',
+ 'b5',
+ 'b7'
+ ];
+ var bmap = {
+ 'status': 'b1',
+ 'settings': 'b2',
+ 'rx': 'b3',
+ 'help': 'b4',
+ 'view': 'b5',
+ 'about': 'b7'
+ };
+ var id = bmap[command];
+ for (var id1 in names) {
+ b = document.getElementById(names[id1]);
+ if (names[id1] == id) {
+ b.className = 'nav-button-active';
+ } else {
+ b.className = 'nav-button';
+ }
+ }
+}
+
+function f_select(command) {
+ var div_list = [
+ 'status',
+ 'settings',
+ 'rx',
+ 'help',
+ 'about'
+ ];
+
+ var orig_command = command;
+
+ if (command == 'rx') {
+ $('#div_logs').show(window.animateSpeed);
+ command = 'status';
+ summary_mode = false;
+ } else {
+ summary_mode = true;
+ $('#div_logs').hide(window.animateSpeed);
+ }
+
+ for (var i = 0; i < div_list.length; i++) {
+ (command == div_list[i]) ? $('#div_' + div_list[i]).show(window.animateSpeed) : $('#div_' + div_list[i]).hide(window.animateSpeed);
+ }
+
+ (command == 'status' && summary_mode == true) ? $('#div_images').show(window.animateSpeed) : $('#div_images').hide(window.animateSpeed);
+
+ (command == 'status') ? $('#controls').show() : $('#controls').hide();
+
+ nav_update(orig_command);
+
+ if (command == 'settings')
+ f_list();
+}
+
+function rx_update(d) {
+ if (d['files'].length > 0) {
+ for (var i = 0; i < d['files'].length; i++) {
+ var img = document.getElementById('img' + i);
+ if (img['src'] != d['files'][i]) {
+ img['src'] = d['files'][i];
+ img.style['display'] = '';
+ }
+ }
+ }
+ error_val = d['error'];
+ fine_tune = d['fine_tune'];
+}
+
+// frequency, system, and talkgroup display
+function change_freq(d) { // d json_type = change_freq
+ t = 'TDMA';
+ var t = 'FDMA'; // TODO: t= wtf??
+
+ if ((d['tdma'] == 0) || (d['tdma'] == 1)) {
+ t = '<span style="color: lime;">TDMA ' + d['tdma'] + '</span>';
+ }
+
+ $('#stx').html(t);
+
+ var displayTgid = '&mdash;';
+ var displayTag = '&nbsp;';
+ var display_src = '&mdash;';
+ var display_alg = '&mdash;';
+ var display_keyid = '&mdash;';
+ var display_srctag = '';
+ var e_class = 'value';
+ var trunc = $('#valTruncate').val();
+
+ last_srcaddr[d['nac']] = d['srcaddr'];
+ last_alg[d['nac']] = d['alg'];
+ last_algid[d['nac']] = d['algid'];
+ last_keyid[d['nac']] = d['keyid'];
+ last_srctag[d['nac']] = d['srcaddr.tag'];
+
+ if (d['tgid'] != null) {
+ displayTgid = d['tgid'];
+ displayTag = d['tag'].substring(0, trunc);
+
+
+ if (d['srcaddr'] != null && d['srcaddr'] > 0) {
+ display_src = d['srcaddr'];
+ display_srctag = d['srcaddr_tag'];
+ }
+
+ display_alg = d['alg'];
+
+ if (d['algid'] != 128) {
+ display_keyid = hex(d['keyid']);
+ e_class = 'red_value';
+ }
+ }
+
+ // main display - system, talkgroup, encryption, keyid, source addr display
+
+ var d_sys = 'system' in d ? d['system'].substring(0, trunc) : 'Undefined';
+ var html = '<table style="width: 510px; height: 168px;">'; // (3 columns, 3 or 4 rows)
+
+// row 1
+ html += '<tr>';
+//col 1
+ html += '<td style="width: 422px;" colspan=2><span class="systgid" id="dSys">' + d_sys + '</span></td>';
+// col 2
+ html += '<td> </td>';
+// col 3
+ html += '<td align="center" style="width: 88px;">';
+ html += '<span class="label-sm">Frequency</span><br><span class="value">' + freqDisplay(d['freq'] / 1000000) + '</span></td>';
+ html += '</tr>';
+
+// row 2
+ html += '<tr>';
+// col 1
+ html += '<td style="width: 422px;" colspan=2><span class="systgid" id="dTag">' + displayTag + '</span></td>';
+// col 2
+ html += '<td align="center" style="width: 88px;"> </td>';
+// col 3
+ html += '<td align="center"><span class="label-sm">Talkgroup</span><br><span class="value" id="dTgid">' + displayTgid + '</span>';
+ html += '</td>';
+ html += '</tr>';
+
+// row 3
+ html += '<tr>';
+// col 1
+ html += '<td style="width: 422px;" colspan=2><span class="systgid" id="dSrcTag">' + display_srctag + '</span></td>';
+// col 2
+ html += '<td align="center" style="width: 88px;">';
+ html += '&nbsp;';
+ html += '</td>';
+// col 3
+ html += '<td align="center" style="width: 88px;">';
+ html += '<span class="label-sm">Source</span><br><span class="value" id="dSrc">' + display_src + '</span>';
+ html += '</td>';
+ html += '</tr>';
+
+// row 4 - encryption info block
+ if (cbState('showEnc')) {
+ html += '<tr>';
+ // col 1
+ html += '<td>Encryption <span class="' + e_class + '" id="dAlg">' + display_alg + '</span>'
+ html += '</td>';
+ // col 2
+ html += '<td> </td>';
+ // col 3
+ html += '<td style="text-align:right;">Key ID</td>';
+ html += '<td style="text-align:center;"><span class="value" id="dKey">' + display_keyid + '</span>';
+ html += '</tr>';
+ }
+
+// end encryption info block
+
+ $('#div_s2').html(html).show();
+
+// "Go To" Presets
+ if (cbState('usePresets')) {
+ $('#div_presets').show();
+ for (let i = 1; i < 8; i++) {
+ $('#btnPreset' + i).css('color', $('#psc' + i).val()).html($('#preset-tag' + i).val());
+ }
+ } else {
+ $('#div_presets').hide();
+ }
+
+ active_nac = d['nac'];
+ active_tgid = d['tgid'];
+ if (d['tgid'] != null) {
+ current_tgid = d['tgid'];
+ }
+
+ // color/style for main display
+
+ var fontStyle = $('#valFontStyle').val();
+ var tgSize = parseInt($('#valTagFont').val());
+ var sysSize = parseInt($('#valSystemFont').val());
+ var defColor = $('#sysColor').val(); // default color
+ var sysColor = "";
+ var tagColor = "";
+ var srcColor = "";
+ var clr = getProperty('.c' + d.tag_color, 'color', 'tgcolors');
+ var srcClr = getProperty('.c' + d.srcaddr_color, 'color', 'tgcolors');
+
+ var ani = getProperty('.c' + d.tag_color, 'animation', 'tgcolors');
+ var bg = getProperty('.c' + d.tag_color, 'backgroundColor', 'tgcolors');
+
+ sysColor = (cbState('color_main_sys') && d['tag_color']) ? clr : defColor;
+ tagColor = (cbState('color_main_tag') && d['tag_color']) ? clr : defColor;
+ srcColor = (cbState('color_main_tag') && d['srcaddr_color']) ? srcClr : defColor;
+
+// console.log(d['srcaddr_tag'] + '---' + d['srcaddr_color']);
+
+ $('#dSys').css({"color": sysColor, "font-size": sysSize, "font-weight": fontStyle});
+ $('#dTag').css({"color": tagColor, "font-size": tgSize, "font-weight": fontStyle, "animation": ani, "background-color": bg});
+// console.log(srcColor);
+ $('#dSrcTag').css({"color": srcColor, "font-size": tgSize, "font-weight": fontStyle, "animation": ani, "background-color": bg});
+
+} // end change_freq
+
+function trunk_summary(d) { // d json_type = trunk_update
+ var nacs = [];
+ for (var nac in d) {
+ if (!is_digit(nac.charAt(0)))
+ continue;
+ nacs[nac] = 1;
+ }
+ var html = '';
+ html += '<br><div class="summary">';
+ html += '<form>';
+ html += '<table border=1 width=732 border width=0 cellpadding=0 cellspacing=0>';
+ html += '<tr><th>Enabled</th><th>NAC</th><th>System</th><th>Last TSBK</th><th>TSBK Count</th><th>Alias TSV</tr>';
+ for (nac in d) {
+ if (!is_digit(nac.charAt(0)))
+ continue;
+ last_srcaddr[nac] = d[nac]['srcaddr'];
+ last_srctag[nac] = d[nac]['srcaddr_tag'];
+ last_alg[nac] = d[nac]['alg'];
+ last_algid[nac] = d[nac]['algid'];
+ last_keyid[nac] = d[nac]['keyid'];
+ if (!(nac in enable_status))
+ enable_status[nac] = true;
+ var times = [];
+ var last_tsbk = d[nac]['last_tsbk'] * 1000;
+ var display_last_tsbk = getTime(last_tsbk);
+ times.push(display_last_tsbk);
+ var min_t = 0;
+ if (times.length) {
+ for (var i = 0; i < times.length; i++) {
+ if (i == 0 || times[i] < min_t)
+ min_t = times[i];
+ }
+ times = min_t;
+ } else {
+ times = '&nbsp;';
+ }
+ var ns = parseInt(nac).toString(16);
+ html += '<tr>';
+ var tf = d[nac]['tgid_tags_file'];
+ var sf = d[nac]['unit_id_tags_file'];
+ var sysid = d[nac]['sysid'];
+ var checked = enable_status[nac] ? 'checked' : '';
+
+ html += '<td align=center><span class="value"><input type="checkbox" id="enabled-' + nac + '" ' + checked + ' onchange="javascript: f_enable_changed(this, ' + nac + ');">';
+ html += '<label for="enabled-' + nac + '"><span></span> ' + '</label></span></td>';
+ // checkbox styling nonsense above
+ html += '<td align=center><span class="value">' + ns.toUpperCase() + '</span></td>';
+ html += '<td align=center><span class="value">' + d[nac]['sysname'] + '</span></td>';
+ html += '<td align=center><span class="value">' + times + '</span></td>';
+ html += '<td align=center><span class="value">' + comma(d[nac]['tsbks']) + '</span></td>';
+ html += '<td align=center>&nbsp;';
+ if (tf)
+ html +='<a title="Talkgroups" style="text-decoration: none;" href="tsv-edit.html?file=' + tf + '&mode=tg&css=' + displayMode() + '&nac=' + nac + '" target="_new">TG</a>';
+ if (sf)
+ html +='&nbsp;&nbsp<a title="Source IDs" style="text-decoration: none;" href="tsv-edit.html?file=' + sf + '&mode=src&css=' + displayMode() + '&nac=' + nac + '" target="_blank">SRC</a>';
+ html += '&nbsp;&nbsp<a title="System Site Aliases" style="text-decoration: none;" href="alias-edit.html?file=site-alias.json&mode=alias&sys='+ (sysid) + '"&css=' + displayMode() +' target="_blank">SA</a>';
+ html += '</td>'
+ html += '</tr>';
+ }
+ var display = '';
+ if (!enable_changed)
+ display = 'none';
+ html += '<tr id="save_list_row" style="display: ' + display + ';"><td colspan=99>';
+ html += '<input type="button" name="save_list" value="Apply Settings" onclick="javascript:f_save_list(this);"></input>';
+ html += '</td></tr>';
+ html += '</table></form></div>';
+ return html;
+} // end trunk_summary()
+
+// additional system info: wacn, sysID, rfss, site id, freq table, adjc sites, secondary control channels, freq error
+function trunk_detail(d) { // d json_type = trunk_update
+ var html = '';
+ var alias, sysid, rfss, site;
+ var error_val = fine_tune = "&mdash;";
+ for (var nac in d) {
+ if (!is_digit(nac.charAt(0)))
+ continue;
+ var p2 = window[nac + 'flavor']; // if phase 2 was detected, add phase 2 layouts
+ var flavor = "Phase 1";
+ if (p2)
+ flavor = "Phase 2";
+ last_srcaddr[nac] = d[nac]['srcaddr'];
+ last_srctag[nac] = d[nac]['srcaddr_tag'];
+ last_alg[nac] = d[nac]['alg'];
+ last_algid[nac] = d[nac]['algid'];
+ last_keyid[nac] = d[nac]['keyid'];
+ error_val = sessionStorage.errorVal;
+ fine_tune = sessionStorage.fineTune;
+
+ sysid = d[nac]['sysid'];
+ rfss = d[nac]['rfid'];
+ site = d[nac]['stid'];
+
+ // use the Site Alias if defined, otherwise use d/nac/sysname
+ if (window.siteAlias != null && window.siteAlias[sysid] && window.siteAlias[sysid][rfss] && window.siteAlias[sysid][rfss][site]) {
+ alias = window.siteAlias[sysid][rfss][site]['alias'];
+ } else {
+ alias = d[nac]['sysname'];
+ }
+
+ html += '<br><div>';
+ html += '<table class="rxsys" border=1 border width=0 cellpadding=0 cellspacing=0 width=100%">';
+
+ html += '<col width="120px">'; // 1
+ html += '<col width="120px">'; // 2
+ html += '<col width="120px">'; // 3
+ html += '<col width="120px">'; // 4
+ html += '<col width="120px">'; // 5
+ html += '<col width="120px">'; // 6
+
+ html += '<th colspan="6">' + alias + '</th><tr>';
+
+ // 1
+ html += '<td align="center">';
+ html += 'System ID<br> <span class="value">' + '0x' + parseInt(d[nac]['sysid']).toString(16).toUpperCase();
+ html += '</td>';
+
+ // 2
+ html += '<td align="center">';
+ html += 'NAC<br> <span class="value">' + '0x' + parseInt(nac).toString(16).toUpperCase();
+ html += '</td>';
+
+ // 3
+ html += '<td align="center">';
+ html += 'WACN<br> <span class="value">' + '0x' + parseInt(d[nac]['wacn']).toString(16).toUpperCase();
+ html += '</td>';
+
+ // 4
+ html += '<td align="center">';
+ html += 'RFSS ID<br> <span class="value">' + d[nac]['rfid']
+ html += '</td>';
+
+ // 5
+ html += '<td align="center">';
+ html += 'Site ID<br> <span class="value">' + d[nac]['stid']
+ html += '</td>';
+
+
+ // 6
+ html += '<td align="center" id="ptype" ondblclick="phaseType(' + nac + ')">';
+ html += '<span>Type<br> <span class="value">' + flavor + '</span></span>';
+ html += '</td>';
+
+ html += '</tr>';
+
+ // row 2
+ html += '<tr>';
+
+ // 1
+ html += '<td align="center" style="white-space: nowrap;">';
+ html += 'Control Channel<br> <span class="value">' + freqDisplay(d[nac]['rxchan'] / 1000000);
+ html += '</td>';
+
+ // 2, 3, 4
+ scc = '';
+ for (i = 0; i < d[nac]['secondary'].length; i++) {
+ scc += freqDisplay(d[nac]['secondary'][i] / 1000000);
+ if ( (i+1) != d[nac]['secondary'].length)
+ scc += '&nbsp;&nbsp;&nbsp;'; // space between freqs
+ }
+
+ html += '<td title="' + scc + '" colspan="3" align="center" style="max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">';
+
+ html += 'Secondary Control Channels</span><br><span class="value"> ';
+
+ if (d[nac]['secondary'].length) {
+ html += scc;
+ } else {
+ html += '<span class="value">None';
+ }
+
+ html += '</td></span>';
+
+ // 5
+ html += '<td align="center">';
+ html += 'TSBK<br><span class="value">' + comma(d[nac]['tsbks']);
+ html += '</td>';
+
+ // 6
+ var last_tsbk = d[nac]['last_tsbk'] * 1000;
+ var display_last_tsbk = getTime(last_tsbk);
+ html += '<td align="center">';
+ html += 'Last TSBK<br> <span class="value">' + display_last_tsbk + '</span>';
+ html += '</td>';
+
+ html += '</tr>';
+
+ if (cbState('showBandPlan')) {
+
+ var zsys = d[nac]['sysid'];
+ html += '<tr><td colspan="6">';
+
+ html += '<table id="bandplan" title="Channel ID / Band Plan"><tr>';
+ html += '<th>ID</th>';
+ html += '<th>Type</th>';
+ html += '<th>Base Frequency</th>';
+ html += '<th>Tx Offset</th>';
+ html += '<th>Spacing (kHz)</th>';
+ html += '<th>Slots</th></tr>';
+ for (p in channel_id[d[nac]['sysid']]) {
+ html += '<tr>';
+ html += '<td style="text-align: center;">' + channel_id[zsys][p]['iden'] + '</td>';
+ html += '<td style="text-align: center;">' + channel_id[zsys][p]['type'] + '</td>';
+ html += '<td style="text-align: center;">' + freqDisplay(channel_id[zsys][p]['freq']) + '</td>';
+ html += '<td style="text-align: center;">' + freqDisplay(channel_id[zsys][p]['offset']) + '</td>';
+ html += '<td style="text-align: center;">' + (channel_id[zsys][p]['step'] * 100) + '</td>';
+ html += '<td style="text-align: center;">' + channel_id[zsys][p]['slots'] + '</td>';
+ html += '</tr>';
+ }
+ html += '</table>';
+
+ html += '</td></tr>';
+ }
+
+ html += '</table></div>';
+
+ // system frequencies table // d json_type = trunk_update
+ html += '<br>';
+
+ if (freqTable == true) { // show/hide table with F key
+
+ html += '<table class="fixed" id="sysfreq">';
+
+ html += '<col width="100px">'; // 1 Freq
+ if (cbState('showLast'))
+ html += '<col width=" 75px">'; // 2 Last
+ html += '<col width=" 80px">'; // 3 tgid
+ html += '<col width="175px">'; // 4 tgtag
+ html += '<col width=" 25px">'; // 5 enc
+ html += '<col width=" 80px">'; // 6 srcaddr
+ html += '<col width="195px">'; // 7 srctag
+
+ html += '<tr>';
+ html += '<th>Frequency </th>'; // 1
+ if (cbState('showLast'))
+ html += '<th>Last </th>'; // 2
+ html += '<th colspan="3">Talkgroup</th>'; // 3 / 4 / 5
+ html += '<th colspan="2">Source</th>'; // 6 / 7
+ html += '</tr>';
+
+ var c, src_c, sc_src, sf_freq, sf_last, sf_hits, sf_timeout;
+
+ // save keystrokes!
+ var fd = 'frequency_data';
+ var ft = 'frequency_tracking';
+ var td = 'talkgroup_data';
+ var ts = 'time_slot';
+ var calls = 'calls';
+
+ sf_timeout = 0; // delay before clearing the tg info
+
+ // 'sf' = system frequencies
+
+ // #frequency#
+
+ //calls
+ var sf_count = []; // "count"
+ var sf_lastactive = []; // "last_active"
+ var sf_protected = []; // "protected"
+ var sf_starttime = []; // "start_time"
+ var sf_endtime = []; // "end_time"
+
+ //tgid
+ var sf_tgid = []; // "tg_id"
+ var sf_tgtag = []; // "tag"
+ var sf_tgcolor = []; // "color"
+
+ //srcaddr
+ var sf_srcaddr = []; // "unit_id"
+ var sf_srctag = []; // "tag"
+ var sf_srccolor = []; // "color"
+
+ var slot, tgid, x, y;
+ var sf_enc = [];
+ var sf_la = [];
+
+ var sf_last = 0;
+
+ sf_tgid[0] = " ";
+ sf_tgtag[0] = " ";
+ sf_srcaddr[0] = " ";
+ sf_srctag[0] = " ";
+ sf_enc[0] = " ";
+ sf_tgcolor[0] = 0;
+ sf_srccolor[0] = 0;
+ sf_la[0] = 0;
+
+ sf_tgid[1] = " ";
+ sf_tgtag[1] = " ";
+ sf_srcaddr[1] = " ";
+ sf_srctag[1] = " ";
+ sf_enc[1] = " ";
+ sf_tgcolor[1] = 0;
+ sf_srccolor[1] = 0;
+ sf_la[1] = 0;
+
+ for (var freq in d[nac][ft]) {
+
+ // temp for testing -- semi-perm?
+ if ( d[nac][ft][freq]['tdma'] == true ) {
+ zt = "<span style='color: #070;'>T</span>";
+ } else {
+ zt = " ";
+ }
+ // end temp
+
+ slot = 0;
+
+ for (var call of d[nac][ft][freq][calls]) {
+
+ if (call == null) {
+
+ sf_tgid[slot] = " ";
+ sf_tgtag[slot] = " ";
+ sf_srcaddr[slot] = " ";
+ sf_srctag[slot] = " ";
+ sf_enc[slot] = " ";
+
+ slot++;
+ continue;
+ }
+
+ if (call.end_time == 0) { // if end_time != 0 then the call is dead and should not be displayed in Active Freq table
+
+ sf_tgid[slot] = call.tgid.tg_id;
+
+ if (call.tgid.tag) {
+ sf_tgtag[slot] = call.tgid.tag;
+ } else {
+ sf_tgtag[slot] = "Talkgroup " + call.tgid.tg_id;
+ call.tgid.color = $('#unk_default').val();
+ }
+
+ sf_tgcolor[slot] = call.tgid.color;
+
+ sf_srcaddr[slot] = call.srcaddr.unit_id ? call.srcaddr.unit_id : " ";
+ sf_srctag[slot] = call.srcaddr.tag ? call.srcaddr.tag : " ";
+ sf_srccolor[slot] = call.srcaddr.color;
+
+ sf_protected[slot] = call['protected']; // protected is a reserved word in JS so can't use dot notation here
+ sf_enc[slot] = (sf_protected[slot] == true) ? encsym : " ";
+
+ } // end if call.end_time
+
+ sf_count[slot] = call.count;
+ sf_lastactive[slot] = call.last_active;
+
+ sf_la[slot] = parseInt(d.time - sf_lastactive[slot], 10);
+
+ slot++;
+
+ } // end for var call in calls
+
+ sf_freq = freqDisplay(parseInt(freq) / 1000000);
+
+ sf_last = d[nac][ft][freq]['last_active'];
+ sf_last = parseFloat(sf_last).toFixed(0);
+
+ if (sf_la[0] > sf_timeout) {
+ sf_tgid[0] = " ";
+ sf_tgtag[0] = " ";
+ sf_srcaddr[0] = " ";
+ sf_srctag[0] = " ";
+ sf_enc[0] = " ";
+ }
+
+ if (sf_la[1] > sf_timeout) {
+ sf_tgid[1] = " ";
+ sf_tgtag[1] = " ";
+ sf_srcaddr[1] = " ";
+ sf_srctag[1] = " ";
+ sf_enc[1] = " ";
+ }
+
+ for (slot = 0; slot < 2; slot++ ) {
+
+ var c = 0;
+ var src_c = 0;
+
+ if (sf_tgcolor[slot]) {
+ c = sf_tgcolor[slot];
+ } else {
+ c = smartColor(sf_tgtag[slot])
+ }
+
+ if (sf_srccolor[slot]) {
+ src_c = sf_srccolor[slot];
+ } else {
+ src_c = smartColor(sf_srctag[slot])
+ }
+
+ sc_src = "<span class=\"c" + src_c + "\">";
+ sc = "<span class=\"c" + c + "\">";
+
+ var tfile = d[nac]['tgid_tags_file'];
+ var sfile = d[nac]['unit_id_tags_file'];
+
+ // Active Frequencies Table
+
+ if (sf_tgtag[slot] == $('#dTag').text()) {
+ sf_enc[slot] += ' A';
+ }
+ html += '<tr>';
+
+ if (slot == 0)
+ html += '<td style="cursor: crosshair;" title="' + sf_freq + ' Hits: ' + sf_count[slot] + '">' + sf_freq + ' ' + zt + '</td>'; // 1
+ if (slot == 1)
+ html += '<td align="right" style="cursor: crosshair;" title="' + sf_freq + ' Hits: ' + sf_count[slot] + '"> <span class="label-sm">/</span> 2 &nbsp;&nbsp;&nbsp; </td>'; // 1
+ if (cbState('showLast'))
+ html += '<td>' + sf_la[slot] + '</td>'; // 2
+ html += '<td name="tgid" ondblclick="editTsv(this, 1, \'' + tfile + '\', ' + nac +');">' + sc + sf_tgid[slot] + '</td>'; // 3
+ html += '<td name="tag" ondblclick="editTsv(this, 1, \'' + tfile + '\', ' + nac +');">' + sc + sf_tgtag[slot] + '</td>'; // 4
+ html += '<td><span class="enc">' + sf_enc[slot] + '</span></td>'; // 5
+ html += '<td name="srcid" ondblclick="editTsv(this, 1, \'' + sfile + '\', ' + nac +');">' + sc_src + sf_srcaddr[slot] + '</td>'; // 6
+ html += '<td name="srctag" ondblclick="editTsv(this, 1, \'' + sfile + '\', ' + nac +');">' + sc_src + sf_srctag[slot] + '</td>'; // 7
+
+ html += '</tr>';
+
+ // Sloppy Source ID Tag Hack 04/2022 -- this displays the source ID tag in the Main Display better than previous implementations.
+ // RID display is problematic when using 0x02 opcode, which the Main Display is sometimes populated with.
+
+ // Sloppy Source Tag Color Hack 10/2022 -- color is supposed to be set in change_freq() but sometimes it does not
+ // (src color might not be present in the json from python? not sure)
+
+ if (sf_srctag[slot].length == 1 && sf_srcaddr[slot] > 1 && cbState('showSourceId') ) {
+ sf_srctag[slot] = "ID: " + sf_srcaddr[slot];
+ }
+
+ if (sf_tgtag[slot] == $('#dTag').text()) {
+ if (sf_srcaddr[slot] == ' ') {
+ // something here to catch when no source address is present -- usually when a patch is used
+ // the display layout gets a little messed up when these vars are null.
+ sf_srcaddr[slot] = 'NO P25 ID';
+ }
+ $('#dSrcTag').text(sf_srctag[slot]);
+ $('#dSrc').text(sf_srcaddr[slot]);
+
+ // redo the color for the source tag
+ var fontStyle = $('#valFontStyle').val();
+ var tgSize = parseInt($('#valTagFont').val());
+ var sysSize = parseInt($('#valSystemFont').val());
+ var ani = getProperty('.c' + d.tag_color, 'animation', 'tgcolors');
+ var bg = getProperty('.c' + d.tag_color, 'backgroundColor', 'tgcolors');
+ var srcColor = getProperty('.c' + sf_srccolor[slot], 'color', 'tgcolors');
+ $('#dSrcTag').css({"color": srcColor, "font-size": tgSize, "font-weight": fontStyle, "animation": ani, "background-color": bg});
+ }
+ // end 'sloppy' -- not my proudest achievement... :(
+
+// if (!p2 || zt == " " ) break;
+ if (!p2 || zt == " " || ( sf_la[slot] > 120 && cbState('colSlot2')) ) break;
+ } // end for slot
+ } // end for freq
+
+ html += '</table>';
+ } // end (freqTable == true)
+
+ if (cbState('show_adj'))
+ html += adjacent_data(d[nac]['adjacent_data']);
+
+ } // end for nac in d
+
+ return html;
+
+} // end trunk_detail()
+
+function editTsv(click, source, file, nac) { // dbl click the ui to access the TSV editor
+ if (!click)
+ return;
+
+ // source
+ // 1 = Active Frequencies
+ // 2 = Call History
+
+ window.getSelection().removeAllRanges(); // unselect the text that was double-clicked on
+ var cname = click.attributes.name;
+ cname = (cname.value);
+
+
+ if (source == 2 && (cname == "tgid" || cname == "tag")) { // Call History Talkground dbl clicked
+ var sid = file;
+ file = tgid_files[sid];
+ }
+
+ if (source == 2 && (cname == "srcid" || cname == "srctag")) { // Call History Source dbl clicked
+ var sid = file;
+ file = srcid_files[sid];
+ }
+
+ if ( (cname =="tgid" || cname == "tag") && (!file || file == "null")) { // null is being stored as a string in window.tgid_files
+ jAlert ("Talkgroup tag TSV file not specified in config file. Cannot edit.", "Error");
+ return;
+ }
+
+ if ( (cname =="srcid" || cname == "srctag") && (!file || file == "null")) {
+ jAlert ("Source tag TSV file not specified in config file. Cannot edit.", "Error");
+ return;
+ }
+
+ var id = 0;
+ var url, x, y, tsv;
+
+ // Active Frequencies // Call History
+ // cellIndex[2] = Talkgroup ID // cellIndex[3] = Talkgroup ID
+ // cellIndex[3] = Talkgroup Tag // cellIndex[4] = Talkgroup Tag
+ // cellIndex[5] = Source ID // cellIndex[5] = Source ID
+ // cellIndex[6] = Source Tag // cellIndex[6] = Source Tag
+
+ switch (source) {
+ case 1: // sysfreq Table TD
+ x = 2; // the cell index of tgid
+ y = 5; // the cell index of srcid
+
+ switch (cname) {
+ case 'tgid':
+ id = click.innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=tg&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'tag':
+ id = click.parentElement.cells[x].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=tg&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'srcid':
+ id = click.innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=src&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'srctag':
+ id = click.parentElement.cells[y].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=src&id=' + id + '&&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+ }
+ break;
+
+ case 2: // Call History Table SPAN
+ x = 3; // the cell index of tgid
+ y = 5; // the cell index of srcid
+
+ switch (cname) {
+ case 'tgid':
+ id = click.parentElement.parentElement.cells[x].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=tg&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'tag':
+ id = click.parentElement.parentElement.cells[x].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=tg&id=' + id + '&nac=' + nac;;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'srcid':
+ id = click.parentElement.parentElement.cells[y].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=src&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+
+ case 'srctag':
+ id = click.parentElement.parentElement.cells[y].innerText;
+ url = 'tsv-edit.html?file=' + file + '&css=' + displayMode() + '&mode=src&id=' + id + '&nac=' + nac;
+ tsv = window.open(url, 'tsv');
+ break;
+ } // end switch cname
+ break;
+ } // end switch source
+} // end editTsv()
+
+// adjacent sites table
+function adjacent_data(d) {
+ // d json_type = trunk_update
+ if (Object.keys(d).length < 1)
+ return '';
+ // var html = "<div class=\"adjacent\">"; // open div-adjacent
+ var html = '<br><table class="fixed" id="adjacent-sites" width=100%>';
+
+ html += '<col width="220px">';
+ html += '<col width="130px">';
+ html += '<col width="100px">';
+ html += '<col width=" 75px">';
+ html += '<col width=" 75px">';
+ html += '<col width="130px">';
+
+ html += '<th>Adjacent Sites</th><th>Frequency</th><th>System ID</th><th>RFSS ID</th><th>Site ID</th><th>Uplink</th>';
+ var ct = 0;
+ var alias, sysid, rfss, site;
+ for (var freq in d) {
+ sysid = d[freq]['sysid'];
+ rfss = d[freq]['rfid'];
+ site = d[freq]['stid'];
+ alias = "-";
+ if (window.siteAlias != null && window.siteAlias[sysid] && window.siteAlias[sysid][rfss] && window.siteAlias[sysid][rfss][site]) {
+ alias = window.siteAlias[sysid][rfss][site]['alias'];
+ } else {
+ alias = 'Site ' + d[freq]['stid'];
+ }
+
+ html += '<tr><td>' + alias + '</td><td align="center">'+ freqDisplay(freq / 1000000) + '</td><td align="center">' + d[freq]['sysid'].toString(16).toUpperCase() + '</td>';
+ html += '<td align="center">' + d[freq]['rfid'] + '</td><td align="center">' + d[freq]['stid'] + '</td>';
+ html += '<td align="center">' + freqDisplay(d[freq]['uplink'] / 1000000) + '</td></tr>';
+ }
+ html += '</table>';
+ return html; // end adjacent sites table
+} // end adjacent_data()
+
+function trunk_update(d) {
+
+ var html;
+ if (summary_mode) {
+ html = trunk_summary(d); // home screen
+
+ // this is part of the 'sloppy' Source ID Tag display routine.
+ // Need trunk_detail to fire so the frequency table bits run even though they are not displayed.
+ // If trunk_detail() does not run, then the 'sloppy' implementation does not work on the RX tab.
+ trunk_detail(d);
+
+ } else {
+ html = trunk_detail(d); // RX screen
+
+ }
+
+ $('#div_s1').html(html);
+
+ if (!summary_mode)
+ sortTable('adjacent-sites', 4);
+
+ // display hold indicator
+ if (d['data']['hold_mode']) {
+ $('#holdIndicator').show();
+ } else {
+ $('#holdIndicator').hide();
+ }
+
+ // display last command unless it was more than 10 seconds ago
+ x2 = d['data']['last_command'];
+ if (x2=='skip') { x2 = 'scan'; }
+ if (x2 && d['data']['last_command_time'] > -10) {
+ $('#lastCommand').html('Last Command<br><b>' + x2.toUpperCase() + '</b><br>' + ' ' + d['data']['last_command_time'] * -1 + ' secs ago');
+ } else {
+ $('#lastCommand').html('');
+ }
+
+ update_data(d);
+} // end trunk_update()
+
+function update_data(d) { // d json type = trunk_update
+ if (active_nac == null || active_tgid == null)
+ return;
+
+ var display_src = '&mdash;';
+ var display_srctag = '&mdash;';
+ var display_alg = '&mdash;';
+ var display_keyid = '&mdash;';
+
+ var e_class = 'value';
+
+// if (last_srcaddr[active_nac] != null) {
+// display_src = last_srcaddr[active_nac];
+// var ele = document.getElementById('dSrc');
+// if (ele != null)
+// ele.innerHTML = display_src;
+// }
+
+ if (last_srctag[active_nac] != null) {
+ display_srctag = last_srctag[active_nac];
+ var ele = document.getElementById('dSrctag');
+ if (ele != null)
+ ele.innerHTML = display_srctag;
+ }
+
+ if (last_algid[active_nac] == null || last_alg[active_nac] == null || last_keyid[active_nac] == null)
+ return;
+ display_alg = last_alg[active_nac];
+ if (last_algid[active_nac] != 128) {
+ display_keyid = last_keyid[active_nac];
+ e_class = 'red_value';
+ }
+ ele = document.getElementById('dAlg');
+ if (ele != null) {
+ ele.innerHTML = display_alg;
+ ele.className = e_class;
+ }
+ ele = document.getElementById('dKey');
+ if (ele != null)
+ ele.innerHTML = display_keyid;
+
+} // end update_data()
+
+function error_tracking() {
+ return; // empty right now, handled in dispatch_commands switch block
+} // end error_tracking
+
+function dispatch_commands(txt) {
+ if (txt == '[]') {
+ return;
+ }
+
+ var dl = JSON.parse(txt);
+
+ var dispatch = {
+ 'trunk_update': trunk_update,
+ 'change_freq': change_freq,
+ 'rx_update': rx_update,
+ 'config_data': config_data,
+ 'config_list': config_list,
+ 'cc_event': cc_event,
+ 'freq_error_tracking': error_tracking
+ };
+
+ for (var i = 0; i < dl.length; i++) {
+ var d = dl[i];
+ if (!('json_type' in d))
+ continue;
+ if (!(d['json_type'] in dispatch))
+ continue;
+ var j_type = d['json_type'];
+ var time = getTime(new Date());
+ if (d.time)
+ time = getTime(d.time * 1000);
+
+ switch (j_type) {
+
+ case 'freq_error_tracking':
+
+ var ele, bx, cx, dx, ex, fx, gx;
+ $('#error_tracking').show();
+ bx = d.device;
+ cx = d.name;
+ dx = d.error_band;
+ ex = d.freq_correction;
+ fx = d.freq_error;
+ gx = d.tuning_error;
+ appendErrorTable (time, bx, cx, dx, ex, fx, gx, 'errors');
+ break;
+
+ case 'change_freq':
+
+ cb = cbState('log_cf');
+ time = getTime(d['effective_time'] * 1000);
+ if (d.tgid && !d.tag) {
+ d.tag = 'Talkgroup ' + d.tgid + ''; // talkgroup tag isn't in the tsv
+ d.tag_color = $('#unk_default').val();
+ }
+ sysid = d.sysid ? hex(d.sysid).toUpperCase() : "&mdash;"
+ var freq = d['freq'] / 1000000;
+ var srctag = "&mdash;";
+ var color, srccolor, srcaddr;
+
+
+ if (d['tag_color']) {
+ color = d['tag_color'];
+ } else {
+ color = smartColor(d.tag);
+ d['tag_color'] = color;
+ }
+
+ if (d['srcaddr_color']) {
+ srccolor = d['srcaddr_color'];
+ } else {
+ srccolor = smartColor(d.tag);
+ }
+
+ var tag = '<span class="c' + color + '">' + d.tag + '</span>';
+ var tgid = '<span class="c' + color + '">' + d.tgid + '</span>';
+
+ // TODO - cb not defined keeps coming up a couple times in the console, right at start up.
+ if (cb && d.tgid) {
+ appendJsonTable(time, j_type, sysid, tag, tgid, 'OP25', freq, '--', 'history');
+ }
+
+ if (d.tgid) {
+ srctag = (window['srct' + d.srcaddr]) ? '<span class="c' + srccolor + '">' + window['srct' + d.srcaddr] : "&mdash;";
+ srcaddr = '<span class="c' + srccolor + '">' + d.srcaddr;
+ }
+ window.g_change_freq = d;
+ break;
+
+ case 'trunk_update':
+
+ cb = cbState('log_tu');
+ var tf, sf, sid, a, z;
+ var sysid, site, rfid, color;
+ var grpaddr, c_grpaddr, srcaddr, c_srcaddr, talkgroup, c_talkgroup, srctag, c_srctag;
+ for (nac in d) {
+ if (Number.isInteger(parseInt(nac))) {
+ sysid = d[nac]['sysid'];
+ sid = sysid;
+ sysid = hex(sysid).toUpperCase();
+ site = d[nac]['stid'];
+ rfid = d[nac]['rfid'];
+ grpaddr = d[nac]['grpaddr'];
+ srcaddr = d[nac]['srcaddr'];
+
+ tf = d[nac]['tgid_tags_file'];
+ tgid_files[sid] = tf;
+
+ sf = d[nac]['unit_id_tags_file'];
+ srcid_files[sid] = sf;
+
+ if (window['tgidt' + grpaddr])
+ talkgroup = window['tgidt' + grpaddr];
+
+ srctag = (window['srct' + srcaddr]) ? (window['srct' + srcaddr]) : "&nbsp;";
+
+ color = smartColor(talkgroup);
+ srccolor = smartColor(talkgroup);
+
+ if (window['tgidc' + grpaddr])
+ color = window['tgidc' + grpaddr];
+
+ c_grpaddr = '<span class="c' + color + '">' + grpaddr + '</span>';
+ c_talkgroup = '<span class="c' + color + '">' + talkgroup + '</span>';
+
+ color = (window['srcc' + srcaddr]) ? window['srcc' + srcaddr] : "0";
+ c_srcaddr = '<span class="c' + srccolor + '">' + srcaddr + '</span>';
+ c_srctag = '<span class="c' + srccolor + '">' + srctag + '</span>';
+
+ var sr = "Site: " + site + " &nbsp;&nbsp;&nbsp; RFID: " + rfid;
+
+ var col_f = "OP25"; // empty for now
+
+ if (cb) {
+ if (grpaddr) { // do not append the table if no grpaddr is present - TU into Events table is pretty much useless anyway
+ appendJsonTable(time, j_type, sysid, sr, c_grpaddr, col_f, "Update", "--", "history");
+ }
+ } //end if cb
+ } // end if nac is number
+ } // end for nac in d
+ sources(d);
+ window.g_trunk_update = d;
+ break;
+
+ case 'rx_update':
+ cb = cbState('log_rx');
+ if (d['files'][0]) {
+ var ps = "Plots: True";
+ } else {
+ var ps = "Plots: False"
+ }
+ if (d['fine_tune']) {
+ var ft = d['fine_tune'];
+ } else {
+ var ft = "n/a";
+ }
+
+ if (cb) {
+ appendJsonTable(time, j_type, ps, 'Fine Tune: ' + ft, 'Tune Err: ' + d['error'], 'OP25', 'RX Update', '--', 'history');
+ } // this Events table entry doesn't add much value either.
+
+ sessionStorage.fineTune = d['fine_tune'] ? d['fine_tune'] : "&mdash;";
+ sessionStorage.errorVal = d['error'] ? d['error'] : "&mdash;";
+ break;
+
+ case 'cc_event':
+
+ time = getTime(d['time'] * 1000);
+ cb = cbState('log_cc');
+ var opcode, n_opcode, sysid, tag, target, source, srctag, src_c, color;
+ var logCall = 0;
+ var noLog = 0;
+ var xp = 0;
+
+ if (d.opcode !== null) {
+ opcode = d['opcode'].toString(16);
+ if (g_opcode[opcode]) {
+ n_opcode = g_opcode[opcode];
+ } else {
+ n_opcode = 'Opcode Not Found: ' + opcode;
+ }
+ }
+
+ tag = target = source = '&mdash;';
+ srctag = "&nbsp;"; // used
+
+ // [group] does not appear in every cc_event!
+ if (d.group) {
+
+ if (d.group && d.group.tag) {
+ tag = d.group.tag;
+ } else {
+ d.group.tag = 'Talkgroup ' + d.group.tg_id;
+ d.group.color = $('#unk_default').val();
+ }
+
+ } // end if d.group
+
+ if (d.reason) {
+ tag = getReason(hex(d.reason));
+ }
+
+ n_opcode = g_opcode[opcode] ? g_opcode[opcode] : opcode;
+
+ if (d['srcaddr']) {
+ source = (d.srcaddr.unit_id) ? d.srcaddr.unit_id : "&mdash; No ID"; // This condition is reached when there is traffic
+ srctag = (d.srcaddr.tag) ? d.srcaddr.tag : "&nbsp;"; // but no source unit id is present. on ebrcs, this
+ // happens when a u/vhf system is patched onto ebrcs.
+ }
+
+ // handle manufacturer opcodes:
+ // 0x10 = Relm/BK
+ // 0x68 = Kenwood
+ // 144(10) 0x90 = Motorola
+ // 164(10) 0xA4 = Harris
+ // 0xD8 = Tait
+ // 0xF8 = Vertex Standard
+ // trunking.py sends the following opcodes:
+ // -1, 0x00, 01, 02, 03, 09, 20, 24, 27, 28, 2a, 2b, 2c, 2d, 2f, 31, 33, 34, 3d
+
+ switch (opcode) {
+
+ case "-1": // end call (not a P25 standard)
+ tag = d.tgid.tag;
+ target = d.tgid.tg_id;
+ n_opcode = "End Call";
+ noLog = 1; // Events
+ // TODO - maybe nothing?
+ break;
+
+ case "0":
+ if (d.mfrid != null) {
+ switch (d.mfrid) {
+ case 0:
+ n_opcode = "Call"; // GRP_V_CH_GRANT
+ target = d['group']['tg_id'];
+ srctag = d['srcaddr']['tag'];
+ noLog = cbState('je_calls') ? 0 : 1; //events
+ logCall = 1; // callHistory
+ break;
+ case 144: // MOTOROLA
+ n_opcode = "XP Adds"; //mot_grg_add_cmd 0x00"
+ tag = d.sg.tag;
+ target = d.sg.tg_id;
+ noLog = 1; // chatty af
+ logCall = 0; // callHistory
+ break;
+ case "default":
+ n_opcode = "Call";
+ target = d['group']['tg_id'];
+ srctag = d['srcaddr']['tag'];
+ noLog = cbState('je_calls') ? 0 : 1;
+ logCall = 1; // callHistory
+ break;
+ } // end switch
+ } // end if
+ break;
+
+ case "1": // 0x01 - RESERVED
+ if (d.mfrid != null) {
+ switch (d.mfrid) {
+ case 0:
+ n_opcode = "Reserved 0x01";
+ break;
+ case 144: // MOTOROLA
+ n_opcode = "XP Drops";
+ tag = d.sg.tag;
+ target = d.sg.tg_id;
+ break;
+ } // end switch
+ } // end if
+ break;
+
+ case "2": // 0x02 - grp_v_ch_grant_updt
+ if (d.mfrid != null) {
+ switch (d.mfrid) {
+ case 0:
+ n_opcode = "grp_v_ch_grant_updt 0x02";
+ noLog = cbState('je_calls') ? 0 : 1;
+ break;
+ case 144: // MOTOROLA
+ d['group'] = d['sg'];
+ d['srcaddr'] = d['sa'];
+ srctag = d.sa.tag;
+ n_opcode = "XP Call"; // MOT XP Call mot_grg_cn_grant 0x02
+ tag = d.sg.tag;
+ target = d.sg.tg_id;
+ source = d.sa.unit_id;
+ noLog = cbState('je_calls') ? 0 : 1;
+ logCall = 1; // callHistory
+ xp = 1;
+ break;
+ } // end switch
+ } // end if
+ break;
+
+ case "3": // 0x03 - GRP_V_CH_GRANT_UPDT_EXP
+ if (d.mfrid != null) {
+ switch (d.mfrid) {
+ case 0:
+ n_opcode = "grp_v_ch_grant_updt_exp 0x03";
+ break;
+ case 144: // MOTOROLA
+ n_opcode = "mot_grg_cn_grant_updt 0x03";
+ tag = d.sg1.tag;
+ target = d.sg1.tg_id;
+ noLog = 1; // used for late entry, very chatty, probably should not log to JSON Events
+ break;
+ } // end switch
+ } // end if
+ break;
+
+ case "9": // MOT System Load ? Could be "Motorola Scan Marker"
+ if (d.mfrid != null) {
+ switch (d.mfrid) {
+ case 0:
+ n_opcode = "Opcode 0x03";
+ break;
+ case 144: // MOTOROLA
+ n_opcode = "System Load " + d.test1;
+ noLog = 1;
+ break;
+ } // end switch
+ } // end if
+ break;
+
+ case "20": // 0x20 - ACK_RSP_FNE
+ noLog = 1;
+ break;
+
+ case "24": // 0x24 - Extended Function Command (mostly inhibit commands)
+ var efclass = d.efclass;
+ var efoperand = d.efoperand;
+ var efargs = d.efargs;
+ var target = d.target;
+ n_opcode = "Ext Fnct Cmd: " + efoperand;
+ switch(efoperand) {
+ case 127:
+ n_opcode = "Radio Inhibit (7F)";
+ break;
+ case 126:
+ n_opcode = "Radio Uninhibit (7E)";
+ break;
+ case 125:
+ n_opcode = "Radio Detach (7D)";
+ break;
+ }
+ source = efargs['unit_id'];
+ noLog = cbState('je_extfunc') ? 0 : 1;
+ break;
+
+ case "27": // 0x27 - DENY_RSP
+ source = d.target.unit_id;
+ srctag = d.target.tag;
+ noLog = cbState('je_deny') ? 0 : 1;
+ break;
+
+ case "28": // 0x28 - GRP_AFF_RSP
+ source = d.target.unit_id;
+ target = d.group.tg_id;
+ noLog = cbState('je_joins') ? 0 : 1;
+ break;
+
+ case "2a": // 0x2A - GRP_AFF_Q - Group Affiliate Query
+ noLog = 1;
+ break;
+
+ case "2b": // 0x2B - LOC_REG_RSP - Location Registration Response
+ if (d['rv'] != null) {
+ switch (d['rv']) {
+ case 0:
+ n_opcode = "Joins";
+ target = d.group.tg_id;
+ source = d.target.unit_id;
+ srctag = d.target.tag;
+ noLog = cbState('je_joins') ? 0 : 1;
+ break;
+ case 1:
+ n_opcode = "Reg Fail";
+ target = d.group.tg_id;
+ source = d.target.unit_id;
+ srctag = d.target.tag;
+ noLog = cbState('je_deny') ? 0 : 1;
+ break;
+ case 2:
+ n_opcode = "Reg Denied";
+ target = d.group.tg_id;
+ source = d.target.unit_id;
+ srctag = d.target.tag;
+ noLog = cbState('je_deny') ? 0 : 1;
+ break;
+ case 3:
+ n_opcode = "Reg Refused";
+ target = d.group.tg_id;
+ source = d.target.unit_id;
+ srctag = d.target.tag;
+ noLog = cbState('je_deny') ? 0 : 1;
+ break;
+ } // end rv switch
+ } // end if
+ break;
+
+ case "2c": // 0x2C - U_REG_RSP - Login TODO: source and target are the same from the json
+ source = d.source.unit_id;
+ srctag = d.source.tag;
+ // target = d.target.unit_id;
+ // tag = d.target.tag;
+ noLog = cbState('je_log') ? 0 : 1;
+ break;
+
+ case "2d": // 0x2D - U_REG_CMD - Force SU Registration
+ source = d.source.unit_id;
+ srctag = d.source.tag;
+ target = d.target.unit_id;
+ tag = d.target.tag;
+ noLog = cbState('je_log') ? 0 : 1;
+ break;
+
+ case "2f": // 0x2F - U_DE_REG_ACK - Logout
+ source = d.source.unit_id;
+ srctag = d.source.tag;
+ noLog = cbState('je_log') ? 0 : 1;
+ break;
+
+ case "31": // 0x31 - AUTH_DMD - Authentication Demand
+ source = d.target_id.unit_id;
+ srctag = d.target_id.tag;
+ target = d.target_address.unit_id;
+ tag = d.target_address.tag;
+ break;
+
+ case "33": // 0x33 - iden up tdma
+ var sysid = d.sysid;
+ var iden = d.iden;
+ var freq = d.freq / 1000000;
+ var offset = d.offset / 1000000;
+ var step = d.step/100000;
+ var slots = d.slots;
+ var type = (slots == 1) ? 'FDMA' : 'TDMA';
+ channelId (sysid, iden, type, freq, offset, step, slots);
+ noLog = 1;
+ break;
+
+ case "34": // 0x34 - iden up vhf/uhf
+ // TODO - test this
+ var sysid = d.sysid;
+ var type = 'FDMA';
+ var iden = d.iden;
+ var freq = d.freq / 1000000;
+ var offset = d.offset / 1000000;
+ var step = d.step/100000;
+ var slots = 1;
+ channelId (sysid, iden, type, freq, offset, step, slots);
+ noLog = 1;
+ break;
+
+ case "3d": // 0x3D - iden up (7/800)
+ var sysid = d.sysid;
+ var type = 'FDMA';
+ var iden = d.iden;
+ var freq = d.freq / 1000000;
+ var offset = d.offset / 1000000;
+ var step = d.step/100000;
+ var slots = 1;
+ channelId (sysid, iden, type, freq, offset, step, slots);
+ noLog = 1;
+ break;
+
+ } // end switch - end handle manf opcodes
+
+ if (d.options) {
+ n_opcode = ( (d.options >> 6) & 1 ) ? n_opcode = n_opcode + "&nbsp;&nbsp;&nbsp;&#x2205;" : n_opcode; //encrypted
+ }
+
+ c = smartColor(tag);
+ src_c = 0;
+
+ if (d['group'])
+ c = (d['group']['color']) ? d['group']['color'] : c;
+
+ if (d['sg'])
+ c = (d['sg']['color']) ? d['sg']['color'] : c;
+
+ tag = "<span class=\"c" + c + "\">" + tag;
+ target = "<span class=\"c" + c + "\">" + target;
+
+
+ if (d['group']) {
+ src_c = d['group']['color'];
+ }
+
+ if (d['source']) {
+ src_c = d['source']['color'];
+ }
+
+ if (d['srcaddr']) { // present for voice calls, not present for other cc_events
+ src_c = (d['srcaddr']['color']) ? d['srcaddr']['color'] : src_c;
+ }
+
+
+
+ source = "<span class=\"c" + src_c + "\">" + source;
+ srctag = "<span class=\"c" + src_c + "\">" + srctag;
+
+ if (cb && noLog == 0) {
+ appendJsonTable(time, j_type, n_opcode, tag, target, source, srctag, opcode, 'history');
+ }
+
+ if (target != "&mdash;" && logCall) {
+
+ target = "<span name=\"tgid\" ondblclick=\"editTsv(this, 2, " + d.sysid + ", " + d.nac + ");\" class=\"c" + c + "\">" + target;
+ tag = "<span name=\"tag\" ondblclick=\"editTsv(this, 2, " + d.sysid + ", " + d.nac + ");\" class=\"c" + c + "\">" + tag;
+
+ source = "<span name=\"srcid\" ondblclick=\"editTsv(this, 2, " + d.sysid + ", " + d.nac + ");\" class=\"c" + src_c + "\">" + source;
+ srctag = "<span name=\"srctag\" ondblclick=\"editTsv(this, 2, " + d.sysid + ", " + d.nac + ");\" class=\"c" + src_c + "\">" + srctag;
+
+ var tdma_slot = d.tdma_slot; // s/b null if not running tdma
+
+ appendCallHistory(time, "--", target, tag, source, srctag, 'callHistory', d.options, xp, d.sysid, d.nac, tdma_slot);
+ }
+
+ window.g_cc_event = d;
+ break;
+ } // end switch
+
+ dispatch[d['json_type']](d); // correct function is called based on json type in the dataset
+ } // end for
+ f_debug(d);
+} // end dispatch_commands()
+
+function cc_event(d) {
+ // does nothing right now
+ return;
+} // end cc_event()
+
+function do_update() {
+ f_debug();
+} // do_update()
+
+function f_scan_button(command) {
+ if (current_tgid == null)
+ send_command(command, -1);
+ else
+ send_command(command, current_tgid);
+}
+
+function f_goto_button(command) {
+ var _tgid = 0;
+ if (command == 'goto') {
+ command = 'hold';
+ if (current_tgid != null)
+ _tgid = current_tgid;
+ _tgid = parseInt(prompt('Enter TGID to hold.', _tgid));
+
+ if (isNaN(_tgid) || _tgid < 0 || _tgid > 65535) {
+ return; // Cancel was pressed or invalid entry
+ }
+
+ // it's necessary to release current hold before trying to hold on a new tg
+ if ($('#holdIndicator').is(':visible') ){
+ send_command('skip', -1);
+ setTimeout(function() {
+ send_command(command, _tgid);
+ }, 500);
+ return;
+ }
+ send_command(command, _tgid);
+ }
+}
+
+function doPreset(ps) {
+
+ t = $('#preset-tg' + ps).val();
+
+ if (isNaN(t) || t < 0 || t > 65535) {
+ return; // Cancel was pressed or invalid entry
+ }
+
+ // it's necessary to release current hold before trying to hold on a new tg
+ if ($('#holdIndicator').is(':visible') ) {
+ send_command('skip', -1);
+ setTimeout(function() {
+ send_command('hold', parseInt(t));
+ }, 500);
+
+ return;
+ }
+ send_command('hold', parseInt(t));
+}
+
+function presetTable() {
+ (cbState('usePresets')) ? $('#configPresets').show() : $('#configPresets').hide();
+}
+
+function f_debug(d) {
+ if (!d_debug)
+ return;
+
+ var html = "<div class='label'>Debug:<br>";
+// html += 'window.g_nac = ' + window.g_nac;
+ html += '<br>';
+ html += 'json type: ' + d['json_type'];
+ html += '<br>';
+ html += "busy " + send_busy;
+ html += " qfull " + send_qfull;
+ html += " sendq size " + send_queue.length;
+ html += " requests " + request_count;
+ html += " <br>callbacks: ";
+ html += " total=" + req_cb_count;
+ html += " incomplete=" + nfinal_count;
+ html += " error=" + n200_count;
+ html += " OK=" + r200_count;
+ html += "</div>";
+
+ $('#div_debug').html(html);
+}
+
+function popOut() {
+ var myWindow = window.open(window.location.href, '', 'width=760,height=400');
+}
+
+function toggleCSS() {
+ $(document.documentElement).attr('data-theme') == 'light' ?
+ $(document.documentElement).attr('data-theme', 'dark') :
+ $(document.documentElement).attr('data-theme', 'light');
+ sdmode();
+}
+
+function comma(x) {
+ // add comma formatting to whatever you give it (xx,xxxx,xxxx)
+ return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
+document.onkeydown = function(evt) {
+// console.log(evt.altKey);
+ // keyboard shortcuts
+ evt = evt || window.event;
+ var x = document.activeElement.tagName;
+ if (x == "INPUT" || evt.altKey == true || evt.ctrlKey == true)
+ return; // don't do anything if user is typing in an input field or if alt, ctrl key is bing used
+
+ switch (evt.keyCode) {
+
+ case 70:
+ // 'f' key - show/hide frequency table
+ $('#lastCommand').html('F - Freq Tbl<br><br>').show();
+ freqTable = !freqTable;
+ setTimeout(function() {$('#lastCommand').html('').hide();}, 2000);
+ break;
+
+ case 71:
+ // 'g' key - GOTO
+ $('#lastCommand').html('G - GOTO<br><br>').show();
+ f_goto_button('goto');
+ break;
+ case 76:
+ // 'l' key - LOCKOUT
+ $('#lastCommand').html('L - LOCKOUT<br><br>').show();
+ f_scan_button('lockout');
+ break;
+ case 72:
+ // 'h' key - HOLD
+ $('#lastCommand').html('H - HOLD<br><br>').show();
+ f_scan_button('hold');
+ break;
+ case 80:
+ // 'p' show/hide plots
+ $('#lastCommand').html('P - Plots<br><br>').show();
+ minify('div_images');
+ break;
+ case 83:
+ // 's' key - SKIP
+ $('#lastCommand').html('S - Scan<br><br>').show();
+ f_scan_button('skip');
+ break;
+ case 86:
+ // 'v' key - VIEW (light/dark)
+ $('#lastCommand').html('V - View<br><br>').show();
+ toggleCSS();
+ break;
+ case 82:
+ // 'r' key - RX screen
+ f_select('rx');
+ break;
+ case 74:
+ // 'j' key - HOME screen
+ f_select('status');
+ break;
+ case 77:
+ // 'm' key - MINIFY
+ minify('nav-bar');
+ minify('div_images');
+ minify('div_s1');
+ break;
+ case 48: // '0' key - show/hide Main Display
+ minify('controlsDisplay');
+ break;
+ case 49: // '1' key - show/hide callHistory
+ $('#lastCommand').html('1 - Calls<br><br>').show();
+ minify('log_container_1');
+ break;
+ case 50:
+ $('#lastCommand').html('2 - Events<br><br>').show();
+ // '2' key - show/hide history (json log)
+ minify('log_container_2');
+ break;
+ case 51:
+ // '3' key - show/hide logs block
+ $('#lastCommand').html('3 - Logs<br><br>').show();
+ if ( $('#div_logs').is(":hidden") ) {
+ $('#div_logs').show(window.animateSpeed);
+ } else {
+ $('#div_logs').hide(window.animateSpeed);
+ }
+ break; // showBandPlan
+ case 52:
+ // '4' key - show/hide Band Plan
+ $('#lastCommand').html('4 - Bandplan<br><br>').show();
+ $('#showBandPlan').trigger('click');
+ setTimeout(function() {$('#lastCommand').html('').hide();}, 2000);
+ break;
+ case 65:
+ $('#lastCommand').html('A - Neighbors<br><br>').show();
+ $('#show_adj').trigger('click');
+ break;
+ case 66:
+ // 'b' key - bold
+ $('#valFontStyle').val('bold');
+ break;
+ case 78:
+ // 'n' key - normal
+ $('#valFontStyle').val('normal');
+ break;
+ } // end switch
+}; // end onkeydown
+
+function minify(div) {
+ $('#' + div).toggle(window.animateSpeed);
+}
+
+function appendJsonTable(a, b, c, d, e, f, srctag, opcode, target) {
+ var numRows = document.getElementById(target).rows.length;
+ var size = parseInt($('#log_len').val());
+ if (!Number.isInteger(size)) {
+ // entry in Config / Display Options must be a number
+ size = 1500;
+ }
+
+ // shorter friendly view
+ var fv = {
+ 'cc_event': "<font color='#ff3300'>CC</font>",
+ 'rx_update': 'RX',
+ 'change_freq': 'CF',
+ 'trunk_update': 'TU'
+ };
+
+ if (numRows > size)
+ document.getElementById(target).deleteRow(-1);
+ var table = document.getElementById(target);
+ var lastRowIndex = table.rows.length - 1;
+
+ $('#eh-count').html('&nbsp');
+ if (d_debug == 1)
+ $('#eh-count').html('&nbsp;&nbsp ' + comma(table.rows.length));
+ var skip = 0;
+
+ var prevTime = nohtml(table.rows[1].cells[0].innerHTML); // time
+
+ // do not duplicate history enteries - uses window object to store previous enteries and compares them with current data
+ // seems to work...
+
+ if (target == 'history' && b == 'trunk_update' && window.g_trunk_update_c && window.g_trunk_update_d) {
+ if (c == window.g_trunk_update_c && d == window.g_trunk_update_d && a == prevTime) {
+ skip = 1;
+ }
+ }
+ if (target == 'history' && b.includes('cc_event') && window.g_cc_event_c && window.g_cc_event_e) {
+ if (c == window.g_cc_event_c && (e == window.g_cc_event_e || f == window.g_cc_event_f) && a == prevTime) {
+ skip = 1;
+ }
+
+ }
+ if (target == 'history' && b.includes('change_freq') && window.g_change_freq_c && window.g_change_freq_e) {
+ if (c == window.g_change_freq_c && e == window.g_change_freq_e && a == prevTime) {
+ skip = 1;
+ }
+ }
+
+ if (!skip) {
+ var row = table.insertRow(1); // 2nd row insert
+
+ var cell0 = row.insertCell(0);
+ var cell1 = row.insertCell(1);
+ var cell2 = row.insertCell(2);
+ var cell3 = row.insertCell(3);
+ var cell4 = row.insertCell(4);
+ var cell5 = row.insertCell(5);
+ var cell6 = row.insertCell(6);
+ var cell7 = row.insertCell(7);
+
+ opcode = opcode.toString();
+ opcode = opcode.length == 1 ? "0" + opcode : opcode;
+
+ cell0.innerHTML = a; //time
+ cell1.innerHTML = (target == 'history') ? '<div align="center">' + fv[b] + '</div>' : '<div align="center">' + b + '</div>'; // type
+ cell2.innerHTML = f; // source id
+ cell3.innerHTML = srctag;
+ cell4.innerHTML = '<div align="center">' + opcode.toUpperCase() + '</div>'; // opcode
+ cell5.innerHTML = c; // n_coode (event)
+ cell6.innerHTML = e; // target
+ cell7.innerHTML = d; // tag
+
+ // only update the window globals if we haven't skipped, so do this inside if !skip
+ if (target == 'history' && b == 'trunk_update') {
+ window.g_trunk_update_c = c;
+ window.g_trunk_update_d = d;
+ }
+ if (target == 'history' && b.includes('cc_event')) {
+ window.g_cc_event_c = c;
+ window.g_cc_event_e = e;
+ window.g_cc_event_f = f;
+ }
+
+ if (target == 'history' && b.includes('change_freq')) {
+ window.g_change_freq_c = c;
+ window.g_change_freq_e = e;
+ }
+
+ } // end if !skip
+} // end appendJsonTable
+
+function appendCallHistory(a, b, c, d, e, f, target, options, xp, sysid, nac, tdma_slot) {
+ var numRows = document.getElementById(target).rows.length;
+// var size = document.getElementById('log_len').value;
+ var size = parseInt($('#log_len').val());
+ if (!Number.isInteger(size)) {
+ // entry in Config / Display Options must be a number
+ size = 1500;
+ }
+ if (numRows > size)
+ $('#' + target + ' tr:last').remove();
+ var table = document.getElementById(target);
+
+ $('#ch-count').html('&nbsp');
+ if (d_debug == 1)
+ $('#ch-count').html('&nbsp;&nbsp ' + comma((table.rows.length)));
+
+ var lastRowIndex = table.rows.length - 1;
+ var skip = 0;
+ var pri, enc, xpatch, x, y;
+
+
+ b = (options) ? options : "&nbsp;";
+ enc = ((b >> 6) & 1 ) ? "&#x2205; " : "";
+ pri = ((b >> 2) & 1).toString() + ((b >> 1) & 1).toString() + ((b >> 0) & 1).toString();
+ pri = parseInt(pri, 2);
+ pri = (xp) ? "XP " : pri;
+
+ var prevTime, prevTg, prevSrc;
+
+ // avoid duplicate channel grant enteries into Call History table.
+ // Search previous 9 rows, compares current data with existing tgid, srcaddr, and time
+ // if tgid and srcaddr are equal and time is within 2 seconds, skip the entry,
+ search: {
+ for (x = 1; x < 8; x++) {
+ if (!table.rows[x]) {
+ break search;
+ }
+ prevTime = nohtml(table.rows[x].cells[0].innerHTML); // time
+ prevTg = nohtml(table.rows[x].cells[3].innerHTML); // tgid
+ prevSrc = nohtml(table.rows[x].cells[5].innerHTML); // source addr
+
+ var psec = prevTime.slice(-1);
+ var asec = a.slice(-1);
+ var diff = Math.abs(psec - asec);
+ if (nohtml(c) == prevTg && nohtml(e) == prevSrc && (a == prevTime || diff <= 2)) {
+ skip = 1;
+ } // end if
+ } // end for
+ } // end search
+
+ if (((b >> 6) & 1) && cbState('hide_enc')) { // hide encrypted calls if selected in Config
+ skip = 1;
+ }
+
+ // do not append the Call History table if not enabled on Home tab
+ if (enable_status[nac] == false) {
+ skip = 1;
+ }
+
+ var tslot = '';
+ if (cbState('showSlot') == true && tdma_slot != null) {
+ tslot = 'S' + ( tdma_slot +1 ) + ' ';
+ }
+
+ if (!skip) {
+
+ var row = table.insertRow(1); // 2nd row insert
+
+ var cell0 = row.insertCell(0);
+ var cell1 = row.insertCell(1);
+ var cell2 = row.insertCell(2);
+ var cell3 = row.insertCell(3);
+ var cell4 = row.insertCell(4);
+ var cell5 = row.insertCell(5);
+ var cell6 = row.insertCell(6);
+
+ cell0.innerHTML = a;
+ cell1.innerHTML = '<div align="center">' + hex(sysid).toUpperCase() + '</div>';
+ cell2.innerHTML = '<div align="center">' + tslot + enc + pri + '</div>';
+ cell3.innerHTML = c;
+ cell4.innerHTML = d;
+ cell5.innerHTML = e;
+ cell6.innerHTML = f;
+
+ } // end if !skip
+} // end appendCallHistory
+
+function appendErrorTable(ax, bx, cx, dx, ex, fx, gx, target) {
+ var numRows = document.getElementById(target).rows.length;
+ var size = parseInt($('#log_len').val());
+ if (!Number.isInteger(size)) {
+ // entry in Config / Display Options must be a number
+ size = 1500;
+ }
+ if (numRows > size)
+ document.getElementById(target).deleteRow(-1);
+ var table = document.getElementById(target);
+ var lastRowIndex = table.rows.length - 1;
+ var skip = 0;
+
+ if (!skip) {
+ var row = table.insertRow(1); // 2nd row insert
+ var cell0 = row.insertCell(0);
+ var cell1 = row.insertCell(1);
+ var cell2 = row.insertCell(2);
+ var cell3 = row.insertCell(3);
+ var cell4 = row.insertCell(4);
+ var cell5 = row.insertCell(5);
+ var cell6 = row.insertCell(6);
+
+ cell0.innerHTML = ax; //time
+ cell1.innerHTML = bx;
+ cell2.innerHTML = cx;
+ cell3.innerHTML = dx;
+ cell4.innerHTML = ex;
+ cell5.innerHTML = fx;
+ cell6.innerHTML = gx;
+
+ } // end if !skip
+} // end appendErrorTable
+
+function update_freq(d) {
+ return; // not currently used
+}
+
+function channelId (sysid, iden, type, freq, offset, step, slots) {
+ !(sysid in channel_id) && (channel_id[sysid] = {});
+ !(iden in channel_id[sysid]) && (channel_id[sysid][iden] = {});
+ channel_id[sysid][iden] = {
+ 'iden': iden, 'type': type, 'freq': freq, 'offset': offset, 'step': step, 'slots': slots
+ };
+}
+
+function smartColor(t) {
+ // searches string t for items in sc1 and sc2, returns a color if found.
+
+ var z = 4; // number of smart colors - TOTO add the UI elements in index.html
+
+ if (!t || !cbState('smartcolors'))
+ return 0; // do nothing if there is no talkgroup name passed, or if the box is not checked (cb default is false!)
+ var tag = t.toString().toUpperCase(); // throws an error if t is an int
+ var color = 0;
+ var ele, x, i, sc, alen;
+
+ for (i = 1; i < (z+1); i++) {
+ ele = document.getElementById('sc'+i).value;
+ sc = ele.split(" ");
+ for (var x = 0; x < sc.length; x++) {
+ if (tag.includes(sc[x].toUpperCase())) {
+ color = i;
+ return color;
+ }
+ }
+ }
+ return color;
+} // end smartColor()
+
+function divExpand(div) {
+ console.log(div);
+ var h = $('#' + div).height();
+ console.log(typeof(h));
+ switch (true) {
+ case (h < 2):
+ console.log('case 1:' + h);
+ $('#' + div).height(301);
+ $('#' + div).show();
+ break;
+ case (h <= 301):
+ console.log('case 2:' + h);
+ $('#' + div).height(702);
+ break;
+ case (h < 9999):
+ console.log('case 3:' + h);
+ $('#' + div).height(1);
+ $('#' + div).hide();
+ break;
+ default:
+ console.log(h < 2);
+ console.log(h < 301);
+ console.log(h < 9999);
+ }
+}
+
+function openTable(div, ref) {
+ // popout window for review/search of log tables
+ var divText = $('#' + div).prop('outerHTML');
+ divText = divText.replace('table id="history"', 'table id="searchTable"');
+ divText = divText.replace('table id="callHistory"', 'table id="searchTable"');
+ divText = divText.replace('table id="errors"', 'table id="searchTable"');
+
+ var myWindow = window.open('', '', 'width=900,height=600');
+ var view = document.documentElement.getAttribute('data-theme');
+ var doc = myWindow.document;
+
+ doc.open();
+ doc.write('<script src="main.js"></script>');
+ doc.write('<script src="jquery.js"></script>');
+ doc.write('<script src="editor.js"></script>');
+ doc.write('<script>window.tgid_files = window.opener.tgid_files;</script>');
+ doc.write('<script>window.srcid_files = window.opener.srcid_files;</script>');
+ doc.write('<script>generateCSS(true);</script>');
+ // search icon &#x1F50E
+ doc.write('<span class="nac">' + ref.id + '</span><br><br>');
+ doc.write('<input type="text" id="searchInput" onkeyup="searchTable()" placeholder="Search" title="Search">');
+ doc.write('<div align="right"><a href="#" style="text-decoration: none;" onclick="csvTable(\'searchTable\');">');
+ doc.write('<img src="csv.png" width="30" title="Download CSV"></a></div><br>');
+ doc.write('<script>document.getElementById("searchInput").focus();</script>');
+ doc.write('<link rel="stylesheet" type="text/css" id="style" href="main.css">');
+ if (view == 'dark')
+ doc.documentElement.setAttribute('data-theme', 'dark');
+ doc.write(divText);
+ doc.close();
+}
+
+function searchTable() {
+ var input, filter, table, tr, i, x, s, cols;
+ var td = [];
+ cols = document.getElementById('searchTable').rows[1].cells.length;
+ input = document.getElementById('searchInput');
+ filter = input.value.toUpperCase();
+ table = document.getElementById('searchTable');
+ tr = table.getElementsByTagName('tr');
+ for (i = 1; i < tr.length; i++) {
+ var s = undefined;
+ for (x = 0; x < cols; x++) {
+ td[x] = tr[i].getElementsByTagName('td')[x];
+ s = s + ' ' + nohtml(td[x].innerHTML).toUpperCase();
+ }
+ if ( s.includes(filter)) {
+ tr[i].style.display = '';
+ } else {
+ tr[i].style.display = 'none'
+ }
+ } // end for
+} // end function
+
+function searchTsvTable() {
+ var input, filter, table, tr, i, x, s, y, cols;
+ var td = [];
+ table = document.getElementById('talkgroups');
+ cols = table.rows[1].cells.length;
+ input = document.getElementById('searchInput');
+ filter = input.value.toUpperCase();
+ tr = table.getElementsByTagName('tr');
+ for (i = 1; i < tr.length; i++) {
+ var s = undefined;
+ for (x = 1; x < cols; x++) { // don't search the first column [0]
+ td[x] = tr[i].getElementsByTagName('td')[x];
+ s += ' ' + td[x].firstChild.value.toUpperCase();
+ }
+ if ( s.includes(filter)) {
+ tr[i].style.display = '';
+ } else {
+ tr[i].style.display = 'none'
+ }
+ } // end for
+} // end function
+
+function hex(dec) {
+ if (!dec) return;
+ return dec.toString(16);
+}
+
+function dec(hex) {
+ if (!hex) return;
+ return parseInt(hex, 16);
+}
+
+function nohtml(str) {
+ if (typeof str != 'string') return str;
+ var x = str.replace(/(<([^>]+)>)/gi, "");
+ return x;
+}
+
+function freqDisplay(f) {
+ var freq;
+ if (!f) return;
+ if (cbState('trailing_zeros')) {
+ freq = f.toFixed(5);
+ } else {
+ if (Number.isInteger(f)) {
+ freq = f + ".0";
+ } else {
+ freq = f;
+ }
+ }
+ return freq;
+}
+
+function displayMode() { // just returns the display mode
+ var x,y;
+ x = document.documentElement.getAttribute('data-theme');
+ y = (x == "dark") ? "dark" : "light";
+ return y;
+}
+
+function sdmode() {
+ $('#selDispMode').val(displayMode());
+}
+
+function sdmodeChange() {
+ var y = document.getElementById('selDispMode');
+ document.documentElement.setAttribute('data-theme', y.value);
+}
+
+function is_digit(s) {
+ return ((s >= '0' && s <= '9'));
+}
+
+function getTime(x) {
+ //expects Unix timestamp, returns 24 hour time, hrs:min:sec
+ date = new Date(parseInt(x));
+ var time = zeroPad(date.getHours(), 2) + ':' + zeroPad(date.getMinutes(), 2) + ':' + zeroPad(date.getSeconds(), 2);
+ return time;
+}
+
+function cbState(x) {
+ // returns the state (true / false) of whatever checkbox you ask it to
+ return $('#' + x).is(':checked');
+}
+
+function csvTable(table_id, separator = ',') { // Quick and simple export target #table_id into a csv
+ // Select rows from table_id
+ var rows = document.querySelectorAll('table#' + table_id + ' tr');
+ // Construct csv
+ var csv = [];
+ for (var i = 0; i < rows.length; i++) {
+ var row = [],
+ cols = rows[i].querySelectorAll('td, th');
+ for (var j = 0; j < cols.length; j++) {
+ // Clean innertext to remove multiple spaces and jumpline (break csv)
+ var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ');
+ // Escape double-quote with double-double-quote
+ data = data.replace(/"/g, '""');
+ // Push escaped string
+ row.push('"' + data + '"');
+ }
+ csv.push(row.join(separator));
+ }
+ var csv_string = csv.join('\n');
+ // Download it
+ var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
+ var link = document.createElement('a');
+ link.style.display = 'none';
+ link.setAttribute('target', '_blank');
+ link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
+ link.setAttribute('download', filename);
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+}
+
+function exportToCsv(filename, rows) { // another csv export tool, but this one accepts an array.
+ var processRow = function (row) {
+ var finalVal = '';
+ for (var j = 0; j < row.length; j++) {
+ var innerValue = row[j] === null ? '' : row[j].toString();
+ if (row[j] instanceof Date) {
+ innerValue = row[j].toLocaleString();
+ };
+ var result = innerValue.replace(/"/g, '""');
+ if (result.search(/("|,|\n)/g) >= 0)
+ result = '"' + result + '"';
+ if (j > 0)
+ finalVal += ',';
+ finalVal += result;
+ }
+ return finalVal + '\n';
+ };
+
+ var csvFile = '';
+ for (var i = 0; i < rows.length; i++) {
+ csvFile += processRow(rows[i]);
+ }
+
+ var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
+ if (navigator.msSaveBlob) { // IE 10+
+ navigator.msSaveBlob(blob, filename);
+ } else {
+ var link = document.createElement("a");
+ if (link.download !== undefined) { // feature detection
+ // Browsers that support HTML5 download attribute
+ var url = URL.createObjectURL(blob);
+ link.setAttribute("href", url);
+ link.setAttribute("download", filename);
+ link.style.visibility = 'hidden';
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ }
+ }
+}
+
+function sortTable(t, c) { // table id, column index
+ if (!cbState('show_adj'))
+ return;
+ if (!t) return;
+ var table, rows, switching, i, x, y, shouldSwitch;
+ table = document.getElementById(t);
+ switching = true;
+ while (switching) {
+ switching = false;
+ rows = table.rows;
+ // (skip the first row (0), which contains table headers)
+ for (i = 1; i < (rows.length - 1); i++) {
+ shouldSwitch = false;
+ x = rows[i].getElementsByTagName("TD")[c];
+ y = rows[i + 1].getElementsByTagName("TD")[c];
+ if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
+ shouldSwitch = true;
+ break;
+ }
+ }
+ if (shouldSwitch) {
+ rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
+ switching = true;
+ }
+ }
+} // end sort table
+
+function sources(d) { // d json type = trunk_update
+
+ // stores source IDs and tags and colors in a global object
+
+ // USAGE:
+
+ // window['tgidc' + tgid] = tgid color
+ // window['tgidt' + tgid] = tgid tag "talkgroup"
+
+ // window['srct' + srcaddr] = srcaddr tag
+ // window['srcc' + srcaddr] = srcaddr color
+
+ if (Object.keys(d).length < 1)
+ return;
+ var f, nac, srcaddr, srcaddr_tag;
+ var ft = 'frequency_tracking';
+ var calls = 'calls';
+ for (nac in d) {
+ if (Number.isInteger(parseInt(nac))) {
+ for (f in d[nac][ft]) {
+
+ srcaddr_tag = d[nac][ft][f]['calls'][0]['srcaddr']['tag'] ? d[nac][ft][f]['calls'][0]['srcaddr'] : null;
+ srcaddr = d[nac][ft][f]['calls'][0]['srcaddr']['unit_id'] ? d[nac][ft][f]['calls'][0]['srcaddr'] : null;
+
+ if (srcaddr && srcaddr_tag) {
+ window['tgidc' + d[nac][ft][f]['calls'][0]['tgid']['tg_id']] = d[nac][ft][f]['calls'][0]['tgid']['color'];
+ window['tgidt' + d[nac][ft][f]['calls'][0]['tgid']['tg_id']] = d[nac][ft][f]['calls'][0]['tgid']['tag'];
+
+ window['srct' + d[nac][ft][f]['calls'][0]['srcaddr']['unit_id']] = d[nac][ft][f]['calls'][0]['srcaddr']['tag'];
+ window['srcc' + d[nac][ft][f]['calls'][0]['srcaddr']['unit_id']] = d[nac][ft][f]['calls'][0]['srcaddr']['color'];
+ }
+
+ if (d[nac][ft][f]['tdma'] == true ) {
+ window[nac + 'flavor'] = "2"; // set it as p2 and leave it that way for the duration
+ }
+ } // end for f
+ } // end if number
+ } // end for x
+} // end function
+
+function getReason(r) {
+ // denial reason lookup
+ if (g_reason[r]) {
+ result = '0x' + r + ' - ' + g_reason[r];
+ } else {
+ result = '0x' + r;
+ }
+ return result;
+}
+
+function saveDisplaySettings() {
+ var settings = {};
+ $('#saveSettings').html('Saved');
+ setTimeout(() => { $('#saveSettings').html('Save Display Settings');}, 2000);
+
+ var s = [
+ "valSystemFont",
+ "valTagFont",
+ "valTruncate",
+ "valFontStyle",
+ "sc1",
+ "sc2",
+ "sc3",
+ "sc4",
+ "log_len",
+ "color_main_tag",
+ "color_main_sys",
+ "smartcolors",
+ "log_cc",
+ "log_cf",
+ "log_tu",
+ "log_rx",
+ "show_adj",
+ "je_joins",
+ "je_calls",
+ "je_deny",
+ "je_log",
+ "hide_enc",
+ "trailing_zeros",
+ "selDispMode",
+ "acc1",
+ "acc2",
+ "sysColor",
+ "valColor",
+ "sysColor",
+ "btnColor",
+ "unk_default",
+ "ani_speed",
+ "showBandPlan",
+ "showSlot",
+ "oplogip",
+ "oplogport",
+ "showLast",
+ "colSlot2",
+ "showEnc",
+ "showSourceId",
+ "je_extfunc",
+ "usePresets",
+ "preset-tg1",
+ "preset-tg2",
+ "preset-tg3",
+ "preset-tg4",
+ "preset-tg5",
+ "preset-tg6",
+ "preset-tg7",
+ "preset-tag1",
+ "preset-tag2",
+ "preset-tag3",
+ "preset-tag4",
+ "preset-tag5",
+ "preset-tag6",
+ "preset-tag7",
+ "psc1",
+ "psc2",
+ "psc3",
+ "psc4",
+ "psc5",
+ "psc6",
+ "psc7" ];
+
+ for (r in s) {
+ if ($('#' + s[r]).attr('type') == "checkbox") {
+ settings[s[r]] = $('#' + s[r]).is(':checked') ? true : false;
+ } else {
+ settings[s[r]] = $('#' + s[r]).val();
+ }
+ } // end for
+
+ var settingsJSON = JSON.stringify(settings, null, 2);
+ send_command('config-savesettings', settingsJSON);
+
+}
+
+
+function loadHelp(){ // this is also called from editor.js
+ f = 'help.html';
+ $.ajax({
+ url : f,
+ type : 'GET',
+ success : popHelp,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('Settings File Acces Error: \n\nFile:' + f + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+function popHelp(h){
+ $('#div_help').html(h)
+}
+
+
+function beginJsonSettings(){ // this is also called from editor.js
+ f = 'ui-settings.json';
+ $.ajax({
+ url : f,
+ type : 'GET',
+ success : loadJsonDisplaySettings,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {alert('Settings File Acces Error: \n\nFile:' + f + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+function loadJsonDisplaySettings(settings) {
+ $('#loadSettings').html('Loaded');
+ setTimeout(() => { $('#loadSettings').html('Load Settings'); }, 2000);
+
+ var ele, m;
+ for (item in settings) {
+
+ ele = document.getElementById(item);
+ if (ele) {
+ if (ele.type == "checkbox") {
+ ele.checked = settings[item] == true ? true : false;
+ continue;
+ }
+
+ if (ele.type == "select") {
+ ele.value = settings[item];
+ continue;
+ }
+
+ ele.value = settings[item];
+// console.log(ele.value + ' --- ' + item);
+ }
+
+ if (item == "selDispMode") {
+ m = settings[item];
+ document.documentElement.setAttribute('data-theme', m);
+ sdmode();
+ }
+
+ // populate url into oplog url field
+ var x = window.location.origin.split( ':' );
+// var y = x[0] + ':' + x[1] + ':5000';
+// $('#oplogUrl').val(y);
+ $('#oplogip').val(x[1].substring(2));
+ $('#oplogport').val('5000');
+
+
+ if (item == "oplogip") {
+ $('#oplogip').val(settings[item]);
+ }
+
+ if (item == "oplogport") {
+ $('#oplogport').val(settings[item]);
+ }
+
+ $('#oplogUrl').val('http://' + $('#oplogip').val() + ':' + $('#oplogport').val());
+
+ } // end for item
+
+ uiColorRefresh();
+
+ (cbState('usePresets')) ? $('#configPresets').show() : $('#configPresets').hide();
+
+}
+
+function uiColorRefresh() { // this is also called from editor.js
+ $('#acc1').trigger('change');
+ $('#valColor').trigger('change');
+ $('#sysColor').trigger('change');
+ $('#btnColor').trigger('change');
+ $('#ani_speed').trigger('change');
+}
+
+function changeCss(className, classValue) {
+
+ // we need invisible container to store additional css definitions
+ var cssMainContainer = $('#css-modifier-container');
+ if (cssMainContainer.length == 0) {
+ cssMainContainer = $('<div id="css-modifier-container"></div>');
+ cssMainContainer.hide();
+ cssMainContainer.appendTo($('body'));
+ }
+
+ // and we need one div for each class
+ var classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
+ if (classContainer.length == 0) {
+ classContainer = $('<div data-class="' + className + '"></div>');
+ classContainer.appendTo(cssMainContainer);
+ }
+
+ // append additional style
+ classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
+}
+
+function getSiteAlias() {
+
+ if (localStorage.AliasTableUpdated == false)
+ return;
+ if (event_source == null || event_source.readyState != 1) // the server has gone out to lunch
+ return;
+ $.ajax({
+ url : 'site-alias.json',
+ type : 'GET',
+ success : loadSiteAlias,
+ error : function(XMLHttpRequest, textStatus, errorThrown) {console.log('site-alias.json file not found. \n\nFile:' + url + '\n\n' + errorThrown + '\n\n');}
+ });
+}
+
+function loadSiteAlias(json) {
+ window.siteAlias = json;
+ localStorage.AliasTableUpdated == false;
+}
+
+function accColorSel() { // this is also called from editor.js
+
+ $('.accColor').on('change', function() {
+ this.blur();
+ var c1 = $('#acc1').val();
+ var c2 = $('#acc2').val();
+ var z = 'linear-gradient(' + c1 + ', ' + c2 +')';
+ $('.controlsDisplay').css('background', z);
+ });
+
+ $('#valColor').on('change', function() {
+ this.blur();
+ var c1 = $('#valColor').val();
+ changeCss('.value', 'color: ' + c1 + ';');
+ changeCss('.nac', 'color: ' + c1 + ';');
+ });
+
+ $('#sysColor').on('change', function() {
+ this.blur();
+ var c1 = $('#sysColor').val();
+ changeCss('.systgid', 'color: ' + c1 + ';');
+ });
+
+ $('#btnColor').on('change', function() {
+ this.blur();
+ var c1 = $('#btnColor').val();
+ changeCss('button', 'color: ' + c1 + ';');
+ changeCss('.nav-button-active', 'color: ' + c1 + ';');
+ changeCss('.nav-button:hover', 'color: ' + c1 + ';');
+ changeCss('.nav-button-active:hover', 'color: ' + c1 + ';');
+ changeCss('.btn', 'color: ' + c1 + ';');
+ changeCss('.control-button', 'color: ' + c1 + ';');
+ changeCss('.control-button:hover', 'color: ' + c1 + ';');
+ });
+
+ $('#ani_speed').on('change', function() {
+ this.blur();
+ window.animateSpeed = parseInt(this.value);
+ });
+
+}
+
+// color, animation, backgroundColor - used for main talkgroup/system display
+// returns the property value of the selector supplied. sheet is document.styleSheets[index].title
+function getProperty(selector, property, sheet) {
+ for (y in document.styleSheets) {
+ if (document.styleSheets[y].title == sheet) // this title is set in the json color map builder func
+ break;
+ }
+ rules = document.styleSheets[y].cssRules;
+ for(i in rules) {
+ if(rules[i].selectorText == selector)
+ return rules[i]['style'][property];
+ }
+ return false;
+}
+
+function getStyle(className) { //test, not used
+ var cssText = "";
+ var classes = document.styleSheets[1].rules || document.styleSheets[0].cssRules;
+ for (var x = 0; x < classes.length; x++) {
+ if (classes[x].selectorText == className) {
+ cssText += classes[x].cssText || classes[x].style.cssText;
+ }
+ }
+ return cssText;
+}
+
+var g_opcode = { // global opcodes
+ '0': 'Call', // Group Voice Grant grp_v_ch_grant dec=0
+ '1': 'Reserved', // REserved 0x01
+ '2': 'Update 0x02',
+ '3': 'Update 0x03',
+ '4': 'UnitVoiceGrant',
+ '5': 'UU_ANS_RSP', // unit to unit answer response
+ '6': 'UnitVoiceUpdate',
+ '8': 'PhoneGrant',
+ '9': 'TELE_INT_PSTN_AEQ',
+ '0a': 'Phone Alert', // tele interconnect
+ '0b': 'Reserved',
+ '10': 'UnitDataGrant',
+ '11': 'GroupDataGrant',
+ '12': 'GroupDataUpdate',
+ '13': 'GroupDataUpdateExplicit',
+ '18': 'UnitStatusUpdate',
+ '1a': 'UnitStatusQuery',
+ '1c': 'UnitShortMessage',
+ '1d': 'UnitMonitor',
+ '1f': 'UnitCallAlert', // Call Alert
+ '20': 'Ack Response', // AckResponse - ACK_RESP_U - This is the generic response supplied by a unit to acknowledge an action when there is no other expected response. Response from radio to system poll ("are you still there?")
+ '21': 'QueuedResponse',
+ '24': 'ExtFunctionCommand',
+ '27': 'Denied', // DenyResponse
+ '28': 'Joins', // GroupAffiliationResponse - GRP_AFF_RSP - This is the response to the request for group affiliation by a unit. This will present the necessary information to the requesting unit to allow it to perform group operations for the indicated group identity.
+ '29': 'Ack Response FNE', // This is the generic response supplied to a unit to acknowledge an action when there is no other expected response. This response is sent to a subscriber unit in response to an earlier action or service request.
+ '2a': 'Group Aff Q', // GRP_AFF_Q - This transaction is to be used to determine what a targeted subscriber unit maintains as the group affiliation data for the unit. The Query will usually originate in the system, but the standard enables other originators.
+ '2b': 'Joins', // LocRegResponse - This transaction is to be used to respond to a Location Registration Request. The response indicates that the subscriber is registered in the new location area.
+ '2c': 'Login', // UnitRegResponse
+ '2d': 'Force SU Reg', // UnitRegCommand - U_REG_CMD - This transaction is to be used to force an SU to initiate Unit Registration
+ '2e': 'UnitAuthCommand',
+ '2f': 'Logout', // UnitDeregAck
+ '31': 'Auth Demand',
+ '36': 'RoamingAddrCommand',
+ '37': 'RoamingAddrUpdate',
+ '38': 'SystemServiceBroadcast', // This broadcast will inform the subscriber units of the current system services supported and currently offered on the Primary control channel of this site.
+ '39': 'AltControlChannel',
+ '3a': 'RfssStatusBroadcast',
+ '3b': 'NetworkStatusBroadcast',
+ '3c': 'AdjacentSite', // Adjacent Site Broadcast
+ '3d': 'ChannelParamsUpdate', // IDEN_UP
+ '3e': 'ProtectionParamBroadcast',
+ '3f': 'ProtectionParamUpdate'
+};
+
+var g_reason = { // TIA-10.AABC-B Annex B Deny Response Reason Codes
+ '10': 'Unit not valid',
+ '11': 'Unit not authoirized',
+ '20': 'Target unit not valid',
+ '21': 'Target unit not authorized',
+ '2f': 'Target unit refused',
+ '30': 'Target group invalid',
+ '31': 'Target group not authoirzed',
+ '40': 'Invalid dialing',
+ '41': 'Telephone number not authroized',
+ '42': 'PSTN address invalid',
+ '50': 'Call time-out',
+ '51': 'Call terminated by landline',
+ '52': 'Call terminated by subscriber',
+ '5f': 'Call pre-empted',
+ '60': 'Site access denial',
+ '61': 'User/system def', // 0x61 - 0xEF per standard
+ '67': 'User/sys def',
+ '77': 'User/sys def',
+ 'c0': 'User/sys def', // seen on MOT system
+ 'f0': 'Call options invalid',
+ 'f1': 'Protection service option invalid',
+ 'f2': 'Duples service option invalid',
+ 'f3': 'circuit/packet mode service option invalid',
+ 'ff': 'Service not supported by system'
+};
+
+var g_moto_opcode = { // opcodes when mfrid is MOT (0x90, 144)
+ '0': 'MOT Add Patch Group',
+ '1': 'MOT Del Patch Group',
+ '3': 'MOT Patch Voice Channel Grant Update',
+ '4': 'MOT Unknown',
+ '5': 'MOT Traffic Chan Stn ID',
+ '6': 'MOT Unknown',
+ '7': 'MOT Unknown',
+ '8': 'MOT Unknown',
+ '9': 'MOT System Load',
+ '0a': 'MOT Unknown',
+ '0b': 'MOT Control Chan Base Stn ID',
+ '0c': 'MOT Unknown',
+ '0d': 'MOT Unknown',
+ '0e': 'MOT Planned Control Channel Shutdown',
+ // 0f through 3f = unknown
+};
+
+var g_serviceOption = {
+ // TODO - populate this, not used currently.
+ // bits 0-2 priority
+ '0': 'reserved',
+ '1': 'Lowest',
+ '2': 'User/system def',
+ '3': 'User/system def',
+ '4': 'Default',
+ '5': 'User/system def',
+ '6': 'User/system def',
+ '7': 'Highest',
+
+ // bit 3 - reserved
+ // bit 4 - mode
+
+};
+
+
+// const value_string MFIDS[] = {
+// { 0x00, "Standard MFID (pre-2001)" },
+// { 0x01, "Standard MFID (post-2001)" },
+// { 0x09, "Aselsan Inc." },
+// { 0x10, "Relm / BK Radio" },
+// { 0x18, "EADS Public Safety Inc." },
+// { 0x20, "Cycomm" },
+// { 0x28, "Efratom Time and Frequency Products, Inc" },
+// { 0x30, "Com-Net Ericsson" },
+// { 0x34, "Etherstack" },
+// { 0x38, "Datron" },
+// { 0x40, "Icom" },
+// { 0x48, "Garmin" },
+// { 0x50, "GTE" },
+// { 0x55, "IFR Systems" },
+// { 0x5A, "INIT Innovations in Transportation, Inc" },
+// { 0x60, "GEC-Marconi" },
+// { 0x64, "Harris Corp." },
+// { 0x68, "Kenwood Communications" },
+// { 0x70, "Glenayre Electronics" },
+// { 0x74, "Japan Radio Co." },
+// { 0x78, "Kokusai" },
+// { 0x7C, "Maxon" },
+// { 0x80, "Midland" },
+// { 0x86, "Daniels Electronics Ltd." },
+// { 0x90, "Motorola" },
+// { 0xA0, "Thales" },
+// { 0xA4, "M/A-COM" },
+// { 0xB0, "Raytheon" },
+// { 0xC0, "SEA" },
+// { 0xC8, "Securicor" },
+// { 0xD0, "ADI" },
+// { 0xD8, "Tait Electronics" },
+// { 0xE0, "Teletec" },
+// { 0xF0, "Transcrypt International" },
+// { 0xF8, "Vertex Standard" },
+// { 0xFC, "Zetron, Inc" },
+// };
+
+
+// const value_string ALGIDS[] = {
+// /* Type I */
+// { 0x00, "ACCORDION 1.3" },
+// { 0x01, "BATON (Auto Even)" },
+// { 0x02, "FIREFLY Type 1" },
+// { 0x03, "MAYFLY Type 1" },
+// { 0x04, "SAVILLE" },
+// { 0x05, "Motorola Assigned - PADSTONE" },
+// { 0x41, "BATON (Auto Odd)" },
+// /* Type III */
+// { 0x80, "Unencrypted" },
+// { 0x81, "DES-OFB, 56 bit key" },
+// { 0x83, "3 key Triple DES, 168 bit key" },
+// { 0x84, "AES-256-OFB" },
+// { 0x85, "AES-128-ECB"},
+// { 0x88, "AES-CBC"},
+// { 0x89, "AES-128-OFB"},
+// /* Motorola proprietary - some of these have been observed over the air,
+// some have been taken from firmware dumps on various devices, others
+// have come from the TIA's FTP website while it was still public,
+// from document "ALGID Guide 2015-04-15.pdf", and others have been
+// have been worked out with a little bit of "guesswork" ;) */
+// { 0x9F, "Motorola DES-XL 56-bit key" },
+// { 0xA0, "Motorola DVI-XL" },
+// { 0xA1, "Motorola DVP-XL" },
+// { 0xA2, "Motorola DVI-SPFL"},
+// { 0xA3, "Motorola HAYSTACK" },
+// { 0xA4, "Motorola Assigned - Unknown" },
+// { 0xA5, "Motorola Assigned - Unknown" },
+// { 0xA6, "Motorola Assigned - Unknown" },
+// { 0xA7, "Motorola Assigned - Unknown" },
+// { 0xA8, "Motorola Assigned - Unknown" },
+// { 0xA9, "Motorola Assigned - Unknown" },
+// { 0xAA, "Motorola ADP (40 bit RC4)" },
+// { 0xAB, "Motorola CFX-256" },
+// { 0xAC, "Motorola Assigned - Unknown" },
+// { 0xAD, "Motorola Assigned - Unknown" },
+// { 0xAE, "Motorola Assigned - Unknown" },
+// { 0xAF, "Motorola AES-256-GCM (possibly)" },
+// { 0xB0, "Motorola DVP"},
+// };
+
+
+
+
+
+
diff --git a/op25/gr-op25_repeater/www/www-static/spectrum.css b/op25/gr-op25_repeater/www/www-static/spectrum.css
new file mode 100644
index 0000000..e68f492
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/spectrum.css
@@ -0,0 +1,507 @@
+/***
+Spectrum Colorpicker v1.8.1
+https://github.com/bgrins/spectrum
+Author: Brian Grinstead
+License: MIT
+***/
+
+.sp-container {
+ position:absolute;
+ top:0;
+ left:0;
+ display:inline-block;
+ *display: inline;
+ *zoom: 1;
+ /* https://github.com/bgrins/spectrum/issues/40 */
+ z-index: 9999994;
+ overflow: hidden;
+}
+.sp-container.sp-flat {
+ position: relative;
+}
+
+/* Fix for * { box-sizing: border-box; } */
+.sp-container,
+.sp-container * {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+
+/* http://ansciath.tumblr.com/post/7347495869/css-aspect-ratio */
+.sp-top {
+ position:relative;
+ width: 100%;
+ display:inline-block;
+}
+.sp-top-inner {
+ position:absolute;
+ top:0;
+ left:0;
+ bottom:0;
+ right:0;
+}
+.sp-color {
+ position: absolute;
+ top:0;
+ left:0;
+ bottom:0;
+ right:20%;
+}
+.sp-hue {
+ position: absolute;
+ top:0;
+ right:0;
+ bottom:0;
+ left:84%;
+ height: 100%;
+}
+
+.sp-clear-enabled .sp-hue {
+ top:33px;
+ height: 77.5%;
+}
+
+.sp-fill {
+ padding-top: 80%;
+}
+.sp-sat, .sp-val {
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+}
+
+.sp-alpha-enabled .sp-top {
+ margin-bottom: 18px;
+}
+.sp-alpha-enabled .sp-alpha {
+ display: block;
+}
+.sp-alpha-handle {
+ position:absolute;
+ top:-4px;
+ bottom: -4px;
+ width: 6px;
+ left: 50%;
+ cursor: pointer;
+ border: 1px solid black;
+ background: white;
+ opacity: .8;
+}
+.sp-alpha {
+ display: none;
+ position: absolute;
+ bottom: -14px;
+ right: 0;
+ left: 0;
+ height: 8px;
+}
+.sp-alpha-inner {
+ border: solid 1px #333;
+}
+
+.sp-clear {
+ display: none;
+}
+
+.sp-clear.sp-clear-display {
+ background-position: center;
+}
+
+.sp-clear-enabled .sp-clear {
+ display: block;
+ position:absolute;
+ top:0px;
+ right:0;
+ bottom:0;
+ left:84%;
+ height: 28px;
+}
+
+/* Don't allow text selection */
+.sp-container, .sp-replacer, .sp-preview, .sp-dragger, .sp-slider, .sp-alpha, .sp-clear, .sp-alpha-handle, .sp-container.sp-dragging .sp-input, .sp-container button {
+ -webkit-user-select:none;
+ -moz-user-select: -moz-none;
+ -o-user-select:none;
+ user-select: none;
+}
+
+.sp-container.sp-input-disabled .sp-input-container {
+ display: none;
+}
+.sp-container.sp-buttons-disabled .sp-button-container {
+ display: none;
+}
+.sp-container.sp-palette-buttons-disabled .sp-palette-button-container {
+ display: none;
+}
+.sp-palette-only .sp-picker-container {
+ display: none;
+}
+.sp-palette-disabled .sp-palette-container {
+ display: none;
+}
+
+.sp-initial-disabled .sp-initial {
+ display: none;
+}
+
+
+/* Gradients for hue, saturation and value instead of images. Not pretty... but it works */
+.sp-sat {
+ background-image: -webkit-gradient(linear, 0 0, 100% 0, from(#FFF), to(rgba(204, 154, 129, 0)));
+ background-image: -webkit-linear-gradient(left, #FFF, rgba(204, 154, 129, 0));
+ background-image: -moz-linear-gradient(left, #fff, rgba(204, 154, 129, 0));
+ background-image: -o-linear-gradient(left, #fff, rgba(204, 154, 129, 0));
+ background-image: -ms-linear-gradient(left, #fff, rgba(204, 154, 129, 0));
+ background-image: linear-gradient(to right, #fff, rgba(204, 154, 129, 0));
+ -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr=#FFFFFFFF, endColorstr=#00CC9A81)";
+ filter : progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr='#FFFFFFFF', endColorstr='#00CC9A81');
+}
+.sp-val {
+ background-image: -webkit-gradient(linear, 0 100%, 0 0, from(#000000), to(rgba(204, 154, 129, 0)));
+ background-image: -webkit-linear-gradient(bottom, #000000, rgba(204, 154, 129, 0));
+ background-image: -moz-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));
+ background-image: -o-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));
+ background-image: -ms-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));
+ background-image: linear-gradient(to top, #000, rgba(204, 154, 129, 0));
+ -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00CC9A81, endColorstr=#FF000000)";
+ filter : progid:DXImageTransform.Microsoft.gradient(startColorstr='#00CC9A81', endColorstr='#FF000000');
+}
+
+.sp-hue {
+ background: -moz-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
+ background: -ms-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
+ background: -o-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
+ background: -webkit-gradient(linear, left top, left bottom, from(#ff0000), color-stop(0.17, #ffff00), color-stop(0.33, #00ff00), color-stop(0.5, #00ffff), color-stop(0.67, #0000ff), color-stop(0.83, #ff00ff), to(#ff0000));
+ background: -webkit-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
+ background: linear-gradient(to bottom, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
+}
+
+/* IE filters do not support multiple color stops.
+ Generate 6 divs, line them up, and do two color gradients for each.
+ Yes, really.
+ */
+.sp-1 {
+ height:17%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0000', endColorstr='#ffff00');
+}
+.sp-2 {
+ height:16%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff00', endColorstr='#00ff00');
+}
+.sp-3 {
+ height:17%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ff00', endColorstr='#00ffff');
+}
+.sp-4 {
+ height:17%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ffff', endColorstr='#0000ff');
+}
+.sp-5 {
+ height:16%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0000ff', endColorstr='#ff00ff');
+}
+.sp-6 {
+ height:17%;
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff00ff', endColorstr='#ff0000');
+}
+
+.sp-hidden {
+ display: none !important;
+}
+
+/* Clearfix hack */
+.sp-cf:before, .sp-cf:after { content: ""; display: table; }
+.sp-cf:after { clear: both; }
+.sp-cf { *zoom: 1; }
+
+/* Mobile devices, make hue slider bigger so it is easier to slide */
+@media (max-device-width: 480px) {
+ .sp-color { right: 40%; }
+ .sp-hue { left: 63%; }
+ .sp-fill { padding-top: 60%; }
+}
+.sp-dragger {
+ border-radius: 5px;
+ height: 5px;
+ width: 5px;
+ border: 1px solid #fff;
+ background: #000;
+ cursor: pointer;
+ position:absolute;
+ top:0;
+ left: 0;
+}
+.sp-slider {
+ position: absolute;
+ top:0;
+ cursor:pointer;
+ height: 3px;
+ left: -1px;
+ right: -1px;
+ border: 1px solid #000;
+ background: white;
+ opacity: .8;
+}
+
+/*
+Theme authors:
+Here are the basic themeable display options (colors, fonts, global widths).
+See http://bgrins.github.io/spectrum/themes/ for instructions.
+*/
+
+.sp-container {
+ border-radius: 0;
+ background-color: #ECECEC;
+ border: solid 1px #f0c49B;
+ padding: 0;
+}
+.sp-container, .sp-container button, .sp-container input, .sp-color, .sp-hue, .sp-clear {
+ font: normal 12px "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -ms-box-sizing: border-box;
+ box-sizing: border-box;
+}
+.sp-top {
+ margin-bottom: 3px;
+}
+.sp-color, .sp-hue, .sp-clear {
+ border: solid 1px #666;
+}
+
+/* Input */
+.sp-input-container {
+ float:right;
+ width: 100px;
+ margin-bottom: 4px;
+}
+.sp-initial-disabled .sp-input-container {
+ width: 100%;
+}
+.sp-input {
+ font-size: 12px !important;
+ border: 1px inset;
+ padding: 4px 5px;
+ margin: 0;
+ width: 100%;
+ background:transparent;
+ border-radius: 3px;
+ color: #222;
+}
+.sp-input:focus {
+ border: 1px solid orange;
+}
+.sp-input.sp-validation-error {
+ border: 1px solid red;
+ background: #fdd;
+}
+.sp-picker-container , .sp-palette-container {
+ float:left;
+ position: relative;
+ padding: 10px;
+ padding-bottom: 300px;
+ margin-bottom: -290px;
+}
+.sp-picker-container {
+ width: 172px;
+ border-left: solid 1px #fff;
+}
+
+/* Palettes */
+.sp-palette-container {
+ border-right: solid 1px #ccc;
+}
+
+.sp-palette-only .sp-palette-container {
+ border: 0;
+}
+
+.sp-palette .sp-thumb-el {
+ display: block;
+ position:relative;
+ float:left;
+ width: 24px;
+ height: 15px;
+ margin: 3px;
+ cursor: pointer;
+ border:solid 2px transparent;
+}
+.sp-palette .sp-thumb-el:hover, .sp-palette .sp-thumb-el.sp-thumb-active {
+ border-color: orange;
+}
+.sp-thumb-el {
+ position:relative;
+}
+
+/* Initial */
+.sp-initial {
+ float: left;
+ border: solid 1px #333;
+}
+.sp-initial span {
+ width: 30px;
+ height: 25px;
+ border:none;
+ display:block;
+ float:left;
+ margin:0;
+}
+
+.sp-initial .sp-clear-display {
+ background-position: center;
+}
+
+/* Buttons */
+.sp-palette-button-container,
+.sp-button-container {
+ float: right;
+}
+
+/* Replacer (the little preview div that shows up instead of the <input>) */
+.sp-replacer {
+ margin:0;
+ overflow:hidden;
+ cursor:pointer;
+ padding: 4px;
+ display:inline-block;
+ *zoom: 1;
+ *display: inline;
+ border: solid 1px #91765d;
+ background: #eee;
+ color: #333;
+ vertical-align: middle;
+}
+.sp-replacer:hover, .sp-replacer.sp-active {
+ border-color: #F0C49B;
+ color: #111;
+}
+.sp-replacer.sp-disabled {
+ cursor:default;
+ border-color: silver;
+ color: silver;
+}
+.sp-dd {
+ padding: 2px 0;
+ height: 16px;
+ line-height: 16px;
+ float:left;
+ font-size:10px;
+}
+.sp-preview {
+ position:relative;
+ width:25px;
+ height: 20px;
+ border: solid 1px #222;
+ margin-right: 5px;
+ float:left;
+ z-index: 0;
+}
+
+.sp-palette {
+ *width: 220px;
+ max-width: 220px;
+}
+.sp-palette .sp-thumb-el {
+ width:16px;
+ height: 16px;
+ margin:2px 1px;
+ border: solid 1px #d0d0d0;
+}
+
+.sp-container {
+ padding-bottom:0;
+}
+
+
+/* Buttons: http://hellohappy.org/css3-buttons/ */
+.sp-container button {
+ background-color: #eeeeee;
+ background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
+ background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
+ background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
+ background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
+ background-image: linear-gradient(to bottom, #eeeeee, #cccccc);
+ border: 1px solid #ccc;
+ border-bottom: 1px solid #bbb;
+ border-radius: 3px;
+ color: #333;
+ font-size: 14px;
+ line-height: 1;
+ padding: 5px 4px;
+ text-align: center;
+ text-shadow: 0 1px 0 #eee;
+ vertical-align: middle;
+}
+.sp-container button:hover {
+ background-color: #dddddd;
+ background-image: -webkit-linear-gradient(top, #dddddd, #bbbbbb);
+ background-image: -moz-linear-gradient(top, #dddddd, #bbbbbb);
+ background-image: -ms-linear-gradient(top, #dddddd, #bbbbbb);
+ background-image: -o-linear-gradient(top, #dddddd, #bbbbbb);
+ background-image: linear-gradient(to bottom, #dddddd, #bbbbbb);
+ border: 1px solid #bbb;
+ border-bottom: 1px solid #999;
+ cursor: pointer;
+ text-shadow: 0 1px 0 #ddd;
+}
+.sp-container button:active {
+ border: 1px solid #aaa;
+ border-bottom: 1px solid #888;
+ -webkit-box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
+ -moz-box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
+ -ms-box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
+ -o-box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
+ box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
+}
+.sp-cancel {
+ font-size: 11px;
+ color: #d93f3f !important;
+ margin:0;
+ padding:2px;
+ margin-right: 5px;
+ vertical-align: middle;
+ text-decoration:none;
+
+}
+.sp-cancel:hover {
+ color: #d93f3f !important;
+ text-decoration: underline;
+}
+
+
+.sp-palette span:hover, .sp-palette span.sp-thumb-active {
+ border-color: #000;
+}
+
+.sp-preview, .sp-alpha, .sp-thumb-el {
+ position:relative;
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);
+}
+.sp-preview-inner, .sp-alpha-inner, .sp-thumb-inner {
+ display:block;
+ position:absolute;
+ top:0;left:0;bottom:0;right:0;
+}
+
+.sp-palette .sp-thumb-inner {
+ background-position: 50% 50%;
+ background-repeat: no-repeat;
+}
+
+.sp-palette .sp-thumb-light.sp-thumb-active .sp-thumb-inner {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAIVJREFUeNpiYBhsgJFMffxAXABlN5JruT4Q3wfi/0DsT64h8UD8HmpIPCWG/KemIfOJCUB+Aoacx6EGBZyHBqI+WsDCwuQ9mhxeg2A210Ntfo8klk9sOMijaURm7yc1UP2RNCMbKE9ODK1HM6iegYLkfx8pligC9lCD7KmRof0ZhjQACDAAceovrtpVBRkAAAAASUVORK5CYII=);
+}
+
+.sp-palette .sp-thumb-dark.sp-thumb-active .sp-thumb-inner {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAMdJREFUOE+tkgsNwzAMRMugEAahEAahEAZhEAqlEAZhEAohEAYh81X2dIm8fKpEspLGvudPOsUYpxE2BIJCroJmEW9qJ+MKaBFhEMNabSy9oIcIPwrB+afvAUFoK4H0tMaQ3XtlrggDhOVVMuT4E5MMG0FBbCEYzjYT7OxLEvIHQLY2zWwQ3D+9luyOQTfKDiFD3iUIfPk8VqrKjgAiSfGFPecrg6HN6m/iBcwiDAo7WiBeawa+Kwh7tZoSCGLMqwlSAzVDhoK+6vH4G0P5wdkAAAAASUVORK5CYII=);
+}
+
+.sp-clear-display {
+ background-repeat:no-repeat;
+ background-position: center;
+ background-image: url(data:image/gif;base64,R0lGODlhFAAUAPcAAAAAAJmZmZ2dnZ6enqKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq/Hx8fLy8vT09PX19ff39/j4+Pn5+fr6+vv7+wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAAUABQAAAihAP9FoPCvoMGDBy08+EdhQAIJCCMybCDAAYUEARBAlFiQQoMABQhKUJBxY0SPICEYHBnggEmDKAuoPMjS5cGYMxHW3IiT478JJA8M/CjTZ0GgLRekNGpwAsYABHIypcAgQMsITDtWJYBR6NSqMico9cqR6tKfY7GeBCuVwlipDNmefAtTrkSzB1RaIAoXodsABiZAEFB06gIBWC1mLVgBa0AAOw==);
+}
diff --git a/op25/gr-op25_repeater/www/www-static/spectrum.js b/op25/gr-op25_repeater/www/www-static/spectrum.js
new file mode 100644
index 0000000..e2e0687
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/spectrum.js
@@ -0,0 +1,2341 @@
+// Spectrum Colorpicker v1.8.1
+// https://github.com/bgrins/spectrum
+// Author: Brian Grinstead
+// License: MIT
+
+(function (factory) {
+ "use strict";
+
+ if (typeof define === 'function' && define.amd) { // AMD
+ define(['jquery'], factory);
+ }
+ else if (typeof exports == "object" && typeof module == "object") { // CommonJS
+ module.exports = factory(require('jquery'));
+ }
+ else { // Browser
+ factory(jQuery);
+ }
+})(function($, undefined) {
+ "use strict";
+
+ var defaultOpts = {
+
+ // Callbacks
+ beforeShow: noop,
+ move: noop,
+ change: noop,
+ show: noop,
+ hide: noop,
+
+ // Options
+ color: false,
+ flat: false,
+ showInput: false,
+ allowEmpty: false,
+ showButtons: true,
+ clickoutFiresChange: true,
+ showInitial: false,
+ showPalette: false,
+ showPaletteOnly: false,
+ hideAfterPaletteSelect: false,
+ togglePaletteOnly: false,
+ showSelectionPalette: true,
+ localStorageKey: false,
+ appendTo: "body",
+ maxSelectionSize: 7,
+ cancelText: "cancel",
+ chooseText: "choose",
+ togglePaletteMoreText: "more",
+ togglePaletteLessText: "less",
+ clearText: "Clear Color Selection",
+ noColorSelectedText: "No Color Selected",
+ preferredFormat: false,
+ className: "", // Deprecated - use containerClassName and replacerClassName instead.
+ containerClassName: "",
+ replacerClassName: "",
+ showAlpha: false,
+ theme: "sp-light",
+ palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]],
+ selectionPalette: [],
+ disabled: false,
+ offset: null
+ },
+ spectrums = [],
+ IE = !!/msie/i.exec( window.navigator.userAgent ),
+ rgbaSupport = (function() {
+ function contains( str, substr ) {
+ return !!~('' + str).indexOf(substr);
+ }
+
+ var elem = document.createElement('div');
+ var style = elem.style;
+ style.cssText = 'background-color:rgba(0,0,0,.5)';
+ return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
+ })(),
+ replaceInput = [
+ "<div class='sp-replacer'>",
+ "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
+ "<div class='sp-dd'>&#9660;</div>",
+ "</div>"
+ ].join(''),
+ markup = (function () {
+
+ // IE does not support gradients with multiple stops, so we need to simulate
+ // that for the rainbow slider with 8 divs that each have a single gradient
+ var gradientFix = "";
+ if (IE) {
+ for (var i = 1; i <= 6; i++) {
+ gradientFix += "<div class='sp-" + i + "'></div>";
+ }
+ }
+
+ return [
+ "<div class='sp-container sp-hidden'>",
+ "<div class='sp-palette-container'>",
+ "<div class='sp-palette sp-thumb sp-cf'></div>",
+ "<div class='sp-palette-button-container sp-cf'>",
+ "<button type='button' class='sp-palette-toggle'></button>",
+ "</div>",
+ "</div>",
+ "<div class='sp-picker-container'>",
+ "<div class='sp-top sp-cf'>",
+ "<div class='sp-fill'></div>",
+ "<div class='sp-top-inner'>",
+ "<div class='sp-color'>",
+ "<div class='sp-sat'>",
+ "<div class='sp-val'>",
+ "<div class='sp-dragger'></div>",
+ "</div>",
+ "</div>",
+ "</div>",
+ "<div class='sp-clear sp-clear-display'>",
+ "</div>",
+ "<div class='sp-hue'>",
+ "<div class='sp-slider'></div>",
+ gradientFix,
+ "</div>",
+ "</div>",
+ "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
+ "</div>",
+ "<div class='sp-input-container sp-cf'>",
+ "<input class='sp-input' type='text' spellcheck='false' />",
+ "</div>",
+ "<div class='sp-initial sp-thumb sp-cf'></div>",
+ "<div class='sp-button-container sp-cf'>",
+ "<a class='sp-cancel' href='#'></a>",
+ "<button type='button' class='sp-choose'></button>",
+ "</div>",
+ "</div>",
+ "</div>"
+ ].join("");
+ })();
+
+ function paletteTemplate (p, color, className, opts) {
+ var html = [];
+ for (var i = 0; i < p.length; i++) {
+ var current = p[i];
+ if(current) {
+ var tiny = tinycolor(current);
+ var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
+ c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
+ var formattedString = tiny.toString(opts.preferredFormat || "rgb");
+ var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
+ html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';"></span></span>');
+ } else {
+ var cls = 'sp-clear-display';
+ html.push($('<div />')
+ .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>')
+ .attr('title', opts.noColorSelectedText)
+ )
+ .html()
+ );
+ }
+ }
+ return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
+ }
+
+ function hideAll() {
+ for (var i = 0; i < spectrums.length; i++) {
+ if (spectrums[i]) {
+ spectrums[i].hide();
+ }
+ }
+ }
+
+ function instanceOptions(o, callbackContext) {
+ var opts = $.extend({}, defaultOpts, o);
+ opts.callbacks = {
+ 'move': bind(opts.move, callbackContext),
+ 'change': bind(opts.change, callbackContext),
+ 'show': bind(opts.show, callbackContext),
+ 'hide': bind(opts.hide, callbackContext),
+ 'beforeShow': bind(opts.beforeShow, callbackContext)
+ };
+
+ return opts;
+ }
+
+ function spectrum(element, o) {
+
+ var opts = instanceOptions(o, element),
+ flat = opts.flat,
+ showSelectionPalette = opts.showSelectionPalette,
+ localStorageKey = opts.localStorageKey,
+ theme = opts.theme,
+ callbacks = opts.callbacks,
+ resize = throttle(reflow, 10),
+ visible = false,
+ isDragging = false,
+ dragWidth = 0,
+ dragHeight = 0,
+ dragHelperHeight = 0,
+ slideHeight = 0,
+ slideWidth = 0,
+ alphaWidth = 0,
+ alphaSlideHelperWidth = 0,
+ slideHelperHeight = 0,
+ currentHue = 0,
+ currentSaturation = 0,
+ currentValue = 0,
+ currentAlpha = 1,
+ palette = [],
+ paletteArray = [],
+ paletteLookup = {},
+ selectionPalette = opts.selectionPalette.slice(0),
+ maxSelectionSize = opts.maxSelectionSize,
+ draggingClass = "sp-dragging",
+ shiftMovementDirection = null;
+
+ var doc = element.ownerDocument,
+ body = doc.body,
+ boundElement = $(element),
+ disabled = false,
+ container = $(markup, doc).addClass(theme),
+ pickerContainer = container.find(".sp-picker-container"),
+ dragger = container.find(".sp-color"),
+ dragHelper = container.find(".sp-dragger"),
+ slider = container.find(".sp-hue"),
+ slideHelper = container.find(".sp-slider"),
+ alphaSliderInner = container.find(".sp-alpha-inner"),
+ alphaSlider = container.find(".sp-alpha"),
+ alphaSlideHelper = container.find(".sp-alpha-handle"),
+ textInput = container.find(".sp-input"),
+ paletteContainer = container.find(".sp-palette"),
+ initialColorContainer = container.find(".sp-initial"),
+ cancelButton = container.find(".sp-cancel"),
+ clearButton = container.find(".sp-clear"),
+ chooseButton = container.find(".sp-choose"),
+ toggleButton = container.find(".sp-palette-toggle"),
+ isInput = boundElement.is("input"),
+ isInputTypeColor = isInput && boundElement.attr("type") === "color" && inputTypeColorSupport(),
+ shouldReplace = isInput && !flat,
+ replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]),
+ offsetElement = (shouldReplace) ? replacer : boundElement,
+ previewElement = replacer.find(".sp-preview-inner"),
+ initialColor = opts.color || (isInput && boundElement.val()),
+ colorOnShow = false,
+ currentPreferredFormat = opts.preferredFormat,
+ clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
+ isEmpty = !initialColor,
+ allowEmpty = opts.allowEmpty && !isInputTypeColor;
+
+ function applyOptions() {
+
+ if (opts.showPaletteOnly) {
+ opts.showPalette = true;
+ }
+
+ toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
+
+ if (opts.palette) {
+ palette = opts.palette.slice(0);
+ paletteArray = $.isArray(palette[0]) ? palette : [palette];
+ paletteLookup = {};
+ for (var i = 0; i < paletteArray.length; i++) {
+ for (var j = 0; j < paletteArray[i].length; j++) {
+ var rgb = tinycolor(paletteArray[i][j]).toRgbString();
+ paletteLookup[rgb] = true;
+ }
+ }
+ }
+
+ container.toggleClass("sp-flat", flat);
+ container.toggleClass("sp-input-disabled", !opts.showInput);
+ container.toggleClass("sp-alpha-enabled", opts.showAlpha);
+ container.toggleClass("sp-clear-enabled", allowEmpty);
+ container.toggleClass("sp-buttons-disabled", !opts.showButtons);
+ container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly);
+ container.toggleClass("sp-palette-disabled", !opts.showPalette);
+ container.toggleClass("sp-palette-only", opts.showPaletteOnly);
+ container.toggleClass("sp-initial-disabled", !opts.showInitial);
+ container.addClass(opts.className).addClass(opts.containerClassName);
+
+ reflow();
+ }
+
+ function initialize() {
+
+ if (IE) {
+ container.find("*:not(input)").attr("unselectable", "on");
+ }
+
+ applyOptions();
+
+ if (shouldReplace) {
+ boundElement.after(replacer).hide();
+ }
+
+ if (!allowEmpty) {
+ clearButton.hide();
+ }
+
+ if (flat) {
+ boundElement.after(container).hide();
+ }
+ else {
+
+ var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
+ if (appendTo.length !== 1) {
+ appendTo = $("body");
+ }
+
+ appendTo.append(container);
+ }
+
+ updateSelectionPaletteFromStorage();
+
+ offsetElement.on("click.spectrum touchstart.spectrum", function (e) {
+ if (!disabled) {
+ toggle();
+ }
+
+ e.stopPropagation();
+
+ if (!$(e.target).is("input")) {
+ e.preventDefault();
+ }
+ });
+
+ if(boundElement.is(":disabled") || (opts.disabled === true)) {
+ disable();
+ }
+
+ // Prevent clicks from bubbling up to document. This would cause it to be hidden.
+ container.click(stopPropagation);
+
+ // Handle user typed input
+ textInput.change(setFromTextInput);
+ textInput.on("paste", function () {
+ setTimeout(setFromTextInput, 1);
+ });
+ textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });
+
+ cancelButton.text(opts.cancelText);
+ cancelButton.on("click.spectrum", function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+ revert();
+ hide();
+ });
+
+ clearButton.attr("title", opts.clearText);
+ clearButton.on("click.spectrum", function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+ isEmpty = true;
+ move();
+
+ if(flat) {
+ //for the flat style, this is a change event
+ updateOriginalInput(true);
+ }
+ });
+
+ chooseButton.text(opts.chooseText);
+ chooseButton.on("click.spectrum", function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+
+ if (IE && textInput.is(":focus")) {
+ textInput.trigger('change');
+ }
+
+ if (isValid()) {
+ updateOriginalInput(true);
+ hide();
+ }
+ });
+
+ toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
+ toggleButton.on("click.spectrum", function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+
+ opts.showPaletteOnly = !opts.showPaletteOnly;
+
+ // To make sure the Picker area is drawn on the right, next to the
+ // Palette area (and not below the palette), first move the Palette
+ // to the left to make space for the picker, plus 5px extra.
+ // The 'applyOptions' function puts the whole container back into place
+ // and takes care of the button-text and the sp-palette-only CSS class.
+ if (!opts.showPaletteOnly && !flat) {
+ container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
+ }
+ applyOptions();
+ });
+
+ draggable(alphaSlider, function (dragX, dragY, e) {
+ currentAlpha = (dragX / alphaWidth);
+ isEmpty = false;
+ if (e.shiftKey) {
+ currentAlpha = Math.round(currentAlpha * 10) / 10;
+ }
+
+ move();
+ }, dragStart, dragStop);
+
+ draggable(slider, function (dragX, dragY) {
+ currentHue = parseFloat(dragY / slideHeight);
+ isEmpty = false;
+ if (!opts.showAlpha) {
+ currentAlpha = 1;
+ }
+ move();
+ }, dragStart, dragStop);
+
+ draggable(dragger, function (dragX, dragY, e) {
+
+ // shift+drag should snap the movement to either the x or y axis.
+ if (!e.shiftKey) {
+ shiftMovementDirection = null;
+ }
+ else if (!shiftMovementDirection) {
+ var oldDragX = currentSaturation * dragWidth;
+ var oldDragY = dragHeight - (currentValue * dragHeight);
+ var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
+
+ shiftMovementDirection = furtherFromX ? "x" : "y";
+ }
+
+ var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
+ var setValue = !shiftMovementDirection || shiftMovementDirection === "y";
+
+ if (setSaturation) {
+ currentSaturation = parseFloat(dragX / dragWidth);
+ }
+ if (setValue) {
+ currentValue = parseFloat((dragHeight - dragY) / dragHeight);
+ }
+
+ isEmpty = false;
+ if (!opts.showAlpha) {
+ currentAlpha = 1;
+ }
+
+ move();
+
+ }, dragStart, dragStop);
+
+ if (!!initialColor) {
+ set(initialColor);
+
+ // In case color was black - update the preview UI and set the format
+ // since the set function will not run (default color is black).
+ updateUI();
+ currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).format;
+
+ addColorToSelectionPalette(initialColor);
+ }
+ else {
+ updateUI();
+ }
+
+ if (flat) {
+ show();
+ }
+
+ function paletteElementClick(e) {
+ if (e.data && e.data.ignore) {
+ set($(e.target).closest(".sp-thumb-el").data("color"));
+ move();
+ }
+ else {
+ set($(e.target).closest(".sp-thumb-el").data("color"));
+ move();
+
+ // If the picker is going to close immediately, a palette selection
+ // is a change. Otherwise, it's a move only.
+ if (opts.hideAfterPaletteSelect) {
+ updateOriginalInput(true);
+ hide();
+ } else {
+ updateOriginalInput();
+ }
+ }
+
+ return false;
+ }
+
+ var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
+ paletteContainer.on(paletteEvent, ".sp-thumb-el", paletteElementClick);
+ initialColorContainer.on(paletteEvent, ".sp-thumb-el:nth-child(1)", { ignore: true }, paletteElementClick);
+ }
+
+ function updateSelectionPaletteFromStorage() {
+
+ if (localStorageKey && window.localStorage) {
+
+ // Migrate old palettes over to new format. May want to remove this eventually.
+ try {
+ var oldPalette = window.localStorage[localStorageKey].split(",#");
+ if (oldPalette.length > 1) {
+ delete window.localStorage[localStorageKey];
+ $.each(oldPalette, function(i, c) {
+ addColorToSelectionPalette(c);
+ });
+ }
+ }
+ catch(e) { }
+
+ try {
+ selectionPalette = window.localStorage[localStorageKey].split(";");
+ }
+ catch (e) { }
+ }
+ }
+
+ function addColorToSelectionPalette(color) {
+ if (showSelectionPalette) {
+ var rgb = tinycolor(color).toRgbString();
+ if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
+ selectionPalette.push(rgb);
+ while(selectionPalette.length > maxSelectionSize) {
+ selectionPalette.shift();
+ }
+ }
+
+ if (localStorageKey && window.localStorage) {
+ try {
+ window.localStorage[localStorageKey] = selectionPalette.join(";");
+ }
+ catch(e) { }
+ }
+ }
+ }
+
+ function getUniqueSelectionPalette() {
+ var unique = [];
+ if (opts.showPalette) {
+ for (var i = 0; i < selectionPalette.length; i++) {
+ var rgb = tinycolor(selectionPalette[i]).toRgbString();
+
+ if (!paletteLookup[rgb]) {
+ unique.push(selectionPalette[i]);
+ }
+ }
+ }
+
+ return unique.reverse().slice(0, opts.maxSelectionSize);
+ }
+
+ function drawPalette() {
+
+ var currentColor = get();
+
+ var html = $.map(paletteArray, function (palette, i) {
+ return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts);
+ });
+
+ updateSelectionPaletteFromStorage();
+
+ if (selectionPalette) {
+ html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts));
+ }
+
+ paletteContainer.html(html.join(""));
+ }
+
+ function drawInitial() {
+ if (opts.showInitial) {
+ var initial = colorOnShow;
+ var current = get();
+ initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts));
+ }
+ }
+
+ function dragStart() {
+ if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
+ reflow();
+ }
+ isDragging = true;
+ container.addClass(draggingClass);
+ shiftMovementDirection = null;
+ boundElement.trigger('dragstart.spectrum', [ get() ]);
+ }
+
+ function dragStop() {
+ isDragging = false;
+ container.removeClass(draggingClass);
+ boundElement.trigger('dragstop.spectrum', [ get() ]);
+ }
+
+ function setFromTextInput() {
+
+ var value = textInput.val();
+
+ if ((value === null || value === "") && allowEmpty) {
+ set(null);
+ move();
+ updateOriginalInput();
+ }
+ else {
+ var tiny = tinycolor(value);
+ if (tiny.isValid()) {
+ set(tiny);
+ move();
+ updateOriginalInput();
+ }
+ else {
+ textInput.addClass("sp-validation-error");
+ }
+ }
+ }
+
+ function toggle() {
+ if (visible) {
+ hide();
+ }
+ else {
+ show();
+ }
+ }
+
+ function show() {
+ var event = $.Event('beforeShow.spectrum');
+
+ if (visible) {
+ reflow();
+ return;
+ }
+
+ boundElement.trigger(event, [ get() ]);
+
+ if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
+ return;
+ }
+
+ hideAll();
+ visible = true;
+
+ $(doc).on("keydown.spectrum", onkeydown);
+ $(doc).on("click.spectrum", clickout);
+ $(window).on("resize.spectrum", resize);
+ replacer.addClass("sp-active");
+ container.removeClass("sp-hidden");
+
+ reflow();
+ updateUI();
+
+ colorOnShow = get();
+
+ drawInitial();
+ callbacks.show(colorOnShow);
+ boundElement.trigger('show.spectrum', [ colorOnShow ]);
+ }
+
+ function onkeydown(e) {
+ // Close on ESC
+ if (e.keyCode === 27) {
+ hide();
+ }
+ }
+
+ function clickout(e) {
+ // Return on right click.
+ if (e.button == 2) { return; }
+
+ // If a drag event was happening during the mouseup, don't hide
+ // on click.
+ if (isDragging) { return; }
+
+ if (clickoutFiresChange) {
+ updateOriginalInput(true);
+ }
+ else {
+ revert();
+ }
+ hide();
+ }
+
+ function hide() {
+ // Return if hiding is unnecessary
+ if (!visible || flat) { return; }
+ visible = false;
+
+ $(doc).off("keydown.spectrum", onkeydown);
+ $(doc).off("click.spectrum", clickout);
+ $(window).off("resize.spectrum", resize);
+
+ replacer.removeClass("sp-active");
+ container.addClass("sp-hidden");
+
+ callbacks.hide(get());
+ boundElement.trigger('hide.spectrum', [ get() ]);
+ }
+
+ function revert() {
+ set(colorOnShow, true);
+ updateOriginalInput(true);
+ }
+
+ function set(color, ignoreFormatChange) {
+ if (tinycolor.equals(color, get())) {
+ // Update UI just in case a validation error needs
+ // to be cleared.
+ updateUI();
+ return;
+ }
+
+ var newColor, newHsv;
+ if (!color && allowEmpty) {
+ isEmpty = true;
+ } else {
+ isEmpty = false;
+ newColor = tinycolor(color);
+ newHsv = newColor.toHsv();
+
+ currentHue = (newHsv.h % 360) / 360;
+ currentSaturation = newHsv.s;
+ currentValue = newHsv.v;
+ currentAlpha = newHsv.a;
+ }
+ updateUI();
+
+ if (newColor && newColor.isValid() && !ignoreFormatChange) {
+ currentPreferredFormat = opts.preferredFormat || newColor.getFormat();
+ }
+ }
+
+ function get(opts) {
+ opts = opts || { };
+
+ if (allowEmpty && isEmpty) {
+ return null;
+ }
+
+ return tinycolor.fromRatio({
+ h: currentHue,
+ s: currentSaturation,
+ v: currentValue,
+ a: Math.round(currentAlpha * 1000) / 1000
+ }, { format: opts.format || currentPreferredFormat });
+ }
+
+ function isValid() {
+ return !textInput.hasClass("sp-validation-error");
+ }
+
+ function move() {
+ updateUI();
+
+ callbacks.move(get());
+ boundElement.trigger('move.spectrum', [ get() ]);
+ }
+
+ function updateUI() {
+
+ textInput.removeClass("sp-validation-error");
+
+ updateHelperLocations();
+
+ // Update dragger background color (gradients take care of saturation and value).
+ var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
+ dragger.css("background-color", flatColor.toHexString());
+
+ // Get a format that alpha will be included in (hex and names ignore alpha)
+ var format = currentPreferredFormat;
+ if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
+ if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
+ format = "rgb";
+ }
+ }
+
+ var realColor = get({ format: format }),
+ displayColor = '';
+
+ //reset background info for preview element
+ previewElement.removeClass("sp-clear-display");
+ previewElement.css('background-color', 'transparent');
+
+ if (!realColor && allowEmpty) {
+ // Update the replaced elements background with icon indicating no color selection
+ previewElement.addClass("sp-clear-display");
+ }
+ else {
+ var realHex = realColor.toHexString(),
+ realRgb = realColor.toRgbString();
+
+ // Update the replaced elements background color (with actual selected color)
+ if (rgbaSupport || realColor.alpha === 1) {
+ previewElement.css("background-color", realRgb);
+ }
+ else {
+ previewElement.css("background-color", "transparent");
+ previewElement.css("filter", realColor.toFilter());
+ }
+
+ if (opts.showAlpha) {
+ var rgb = realColor.toRgb();
+ rgb.a = 0;
+ var realAlpha = tinycolor(rgb).toRgbString();
+ var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";
+
+ if (IE) {
+ alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
+ }
+ else {
+ alphaSliderInner.css("background", "-webkit-" + gradient);
+ alphaSliderInner.css("background", "-moz-" + gradient);
+ alphaSliderInner.css("background", "-ms-" + gradient);
+ // Use current syntax gradient on unprefixed property.
+ alphaSliderInner.css("background",
+ "linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
+ }
+ }
+
+ displayColor = realColor.toString(format);
+ }
+
+ // Update the text entry input as it changes happen
+ if (opts.showInput) {
+ textInput.val(displayColor);
+ }
+
+ if (opts.showPalette) {
+ drawPalette();
+ }
+
+ drawInitial();
+ }
+
+ function updateHelperLocations() {
+ var s = currentSaturation;
+ var v = currentValue;
+
+ if(allowEmpty && isEmpty) {
+ //if selected color is empty, hide the helpers
+ alphaSlideHelper.hide();
+ slideHelper.hide();
+ dragHelper.hide();
+ }
+ else {
+ //make sure helpers are visible
+ alphaSlideHelper.show();
+ slideHelper.show();
+ dragHelper.show();
+
+ // Where to show the little circle in that displays your current selected color
+ var dragX = s * dragWidth;
+ var dragY = dragHeight - (v * dragHeight);
+ dragX = Math.max(
+ -dragHelperHeight,
+ Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
+ );
+ dragY = Math.max(
+ -dragHelperHeight,
+ Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
+ );
+ dragHelper.css({
+ "top": dragY + "px",
+ "left": dragX + "px"
+ });
+
+ var alphaX = currentAlpha * alphaWidth;
+ alphaSlideHelper.css({
+ "left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
+ });
+
+ // Where to show the bar that displays your current selected hue
+ var slideY = (currentHue) * slideHeight;
+ slideHelper.css({
+ "top": (slideY - slideHelperHeight) + "px"
+ });
+ }
+ }
+
+ function updateOriginalInput(fireCallback) {
+ var color = get(),
+ displayColor = '',
+ hasChanged = !tinycolor.equals(color, colorOnShow);
+
+ if (color) {
+ displayColor = color.toString(currentPreferredFormat);
+ // Update the selection palette with the current color
+ addColorToSelectionPalette(color);
+ }
+
+ if (isInput) {
+ boundElement.val(displayColor);
+ }
+
+ if (fireCallback && hasChanged) {
+ callbacks.change(color);
+ boundElement.trigger('change', [ color ]);
+ }
+ }
+
+ function reflow() {
+ if (!visible) {
+ return; // Calculations would be useless and wouldn't be reliable anyways
+ }
+ dragWidth = dragger.width();
+ dragHeight = dragger.height();
+ dragHelperHeight = dragHelper.height();
+ slideWidth = slider.width();
+ slideHeight = slider.height();
+ slideHelperHeight = slideHelper.height();
+ alphaWidth = alphaSlider.width();
+ alphaSlideHelperWidth = alphaSlideHelper.width();
+
+ if (!flat) {
+ container.css("position", "absolute");
+ if (opts.offset) {
+ container.offset(opts.offset);
+ } else {
+ container.offset(getOffset(container, offsetElement));
+ }
+ }
+
+ updateHelperLocations();
+
+ if (opts.showPalette) {
+ drawPalette();
+ }
+
+ boundElement.trigger('reflow.spectrum');
+ }
+
+ function destroy() {
+ boundElement.show();
+ offsetElement.off("click.spectrum touchstart.spectrum");
+ container.remove();
+ replacer.remove();
+ spectrums[spect.id] = null;
+ }
+
+ function option(optionName, optionValue) {
+ if (optionName === undefined) {
+ return $.extend({}, opts);
+ }
+ if (optionValue === undefined) {
+ return opts[optionName];
+ }
+
+ opts[optionName] = optionValue;
+
+ if (optionName === "preferredFormat") {
+ currentPreferredFormat = opts.preferredFormat;
+ }
+ applyOptions();
+ }
+
+ function enable() {
+ disabled = false;
+ boundElement.attr("disabled", false);
+ offsetElement.removeClass("sp-disabled");
+ }
+
+ function disable() {
+ hide();
+ disabled = true;
+ boundElement.attr("disabled", true);
+ offsetElement.addClass("sp-disabled");
+ }
+
+ function setOffset(coord) {
+ opts.offset = coord;
+ reflow();
+ }
+
+ initialize();
+
+ var spect = {
+ show: show,
+ hide: hide,
+ toggle: toggle,
+ reflow: reflow,
+ option: option,
+ enable: enable,
+ disable: disable,
+ offset: setOffset,
+ set: function (c) {
+ set(c);
+ updateOriginalInput();
+ },
+ get: get,
+ destroy: destroy,
+ container: container
+ };
+
+ spect.id = spectrums.push(spect) - 1;
+
+ return spect;
+ }
+
+ /**
+ * checkOffset - get the offset below/above and left/right element depending on screen position
+ * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
+ */
+ function getOffset(picker, input) {
+ var extraY = 0;
+ var dpWidth = picker.outerWidth();
+ var dpHeight = picker.outerHeight();
+ var inputHeight = input.outerHeight();
+ var doc = picker[0].ownerDocument;
+ var docElem = doc.documentElement;
+ var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
+ var viewHeight = docElem.clientHeight + $(doc).scrollTop();
+ var offset = input.offset();
+ var offsetLeft = offset.left;
+ var offsetTop = offset.top;
+
+ offsetTop += inputHeight;
+
+ offsetLeft -=
+ Math.min(offsetLeft, (offsetLeft + dpWidth > viewWidth && viewWidth > dpWidth) ?
+ Math.abs(offsetLeft + dpWidth - viewWidth) : 0);
+
+ offsetTop -=
+ Math.min(offsetTop, ((offsetTop + dpHeight > viewHeight && viewHeight > dpHeight) ?
+ Math.abs(dpHeight + inputHeight - extraY) : extraY));
+
+ return {
+ top: offsetTop,
+ bottom: offset.bottom,
+ left: offsetLeft,
+ right: offset.right,
+ width: offset.width,
+ height: offset.height
+ };
+ }
+
+ /**
+ * noop - do nothing
+ */
+ function noop() {
+
+ }
+
+ /**
+ * stopPropagation - makes the code only doing this a little easier to read in line
+ */
+ function stopPropagation(e) {
+ e.stopPropagation();
+ }
+
+ /**
+ * Create a function bound to a given object
+ * Thanks to underscore.js
+ */
+ function bind(func, obj) {
+ var slice = Array.prototype.slice;
+ var args = slice.call(arguments, 2);
+ return function () {
+ return func.apply(obj, args.concat(slice.call(arguments)));
+ };
+ }
+
+ /**
+ * Lightweight drag helper. Handles containment within the element, so that
+ * when dragging, the x is within [0,element.width] and y is within [0,element.height]
+ */
+ function draggable(element, onmove, onstart, onstop) {
+ onmove = onmove || function () { };
+ onstart = onstart || function () { };
+ onstop = onstop || function () { };
+ var doc = document;
+ var dragging = false;
+ var offset = {};
+ var maxHeight = 0;
+ var maxWidth = 0;
+ var hasTouch = ('ontouchstart' in window);
+
+ var duringDragEvents = {};
+ duringDragEvents["selectstart"] = prevent;
+ duringDragEvents["dragstart"] = prevent;
+ duringDragEvents["touchmove mousemove"] = move;
+ duringDragEvents["touchend mouseup"] = stop;
+
+ function prevent(e) {
+ if (e.stopPropagation) {
+ e.stopPropagation();
+ }
+ if (e.preventDefault) {
+ e.preventDefault();
+ }
+ e.returnValue = false;
+ }
+
+ function move(e) {
+ if (dragging) {
+ // Mouseup happened outside of window
+ if (IE && doc.documentMode < 9 && !e.button) {
+ return stop();
+ }
+
+ var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0];
+ var pageX = t0 && t0.pageX || e.pageX;
+ var pageY = t0 && t0.pageY || e.pageY;
+
+ var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
+ var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));
+
+ if (hasTouch) {
+ // Stop scrolling in iOS
+ prevent(e);
+ }
+
+ onmove.apply(element, [dragX, dragY, e]);
+ }
+ }
+
+ function start(e) {
+ var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);
+
+ if (!rightclick && !dragging) {
+ if (onstart.apply(element, arguments) !== false) {
+ dragging = true;
+ maxHeight = $(element).height();
+ maxWidth = $(element).width();
+ offset = $(element).offset();
+
+ $(doc).on(duringDragEvents);
+ $(doc.body).addClass("sp-dragging");
+
+ move(e);
+
+ prevent(e);
+ }
+ }
+ }
+
+ function stop() {
+ if (dragging) {
+ $(doc).off(duringDragEvents);
+ $(doc.body).removeClass("sp-dragging");
+
+ // Wait a tick before notifying observers to allow the click event
+ // to fire in Chrome.
+ setTimeout(function() {
+ onstop.apply(element, arguments);
+ }, 0);
+ }
+ dragging = false;
+ }
+
+ $(element).on("touchstart mousedown", start);
+ }
+
+ function throttle(func, wait, debounce) {
+ var timeout;
+ return function () {
+ var context = this, args = arguments;
+ var throttler = function () {
+ timeout = null;
+ func.apply(context, args);
+ };
+ if (debounce) clearTimeout(timeout);
+ if (debounce || !timeout) timeout = setTimeout(throttler, wait);
+ };
+ }
+
+ function inputTypeColorSupport() {
+ return $.fn.spectrum.inputTypeColorSupport();
+ }
+
+ /**
+ * Define a jQuery plugin
+ */
+ var dataID = "spectrum.id";
+ $.fn.spectrum = function (opts, extra) {
+
+ if (typeof opts == "string") {
+
+ var returnValue = this;
+ var args = Array.prototype.slice.call( arguments, 1 );
+
+ this.each(function () {
+ var spect = spectrums[$(this).data(dataID)];
+ if (spect) {
+ var method = spect[opts];
+ if (!method) {
+ throw new Error( "Spectrum: no such method: '" + opts + "'" );
+ }
+
+ if (opts == "get") {
+ returnValue = spect.get();
+ }
+ else if (opts == "container") {
+ returnValue = spect.container;
+ }
+ else if (opts == "option") {
+ returnValue = spect.option.apply(spect, args);
+ }
+ else if (opts == "destroy") {
+ spect.destroy();
+ $(this).removeData(dataID);
+ }
+ else {
+ method.apply(spect, args);
+ }
+ }
+ });
+
+ return returnValue;
+ }
+
+ // Initializing a new instance of spectrum
+ return this.spectrum("destroy").each(function () {
+ var options = $.extend({}, $(this).data(), opts);
+ var spect = spectrum(this, options);
+ $(this).data(dataID, spect.id);
+ });
+ };
+
+ $.fn.spectrum.load = true;
+ $.fn.spectrum.loadOpts = {};
+ $.fn.spectrum.draggable = draggable;
+ $.fn.spectrum.defaults = defaultOpts;
+ $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
+ if (typeof inputTypeColorSupport._cachedResult === "undefined") {
+ var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null
+ inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== "";
+ }
+ return inputTypeColorSupport._cachedResult;
+ };
+
+ $.spectrum = { };
+ $.spectrum.localization = { };
+ $.spectrum.palettes = { };
+
+ $.fn.spectrum.processNativeColorInputs = function () {
+ var colorInputs = $("input[type=color]");
+ if (colorInputs.length && !inputTypeColorSupport()) {
+ colorInputs.spectrum({
+ preferredFormat: "hex6"
+ });
+ }
+ };
+
+ // TinyColor v1.1.2
+ // https://github.com/bgrins/TinyColor
+ // Brian Grinstead, MIT License
+
+ (function() {
+
+ var trimLeft = /^[\s,#]+/,
+ trimRight = /\s+$/,
+ tinyCounter = 0,
+ math = Math,
+ mathRound = math.round,
+ mathMin = math.min,
+ mathMax = math.max,
+ mathRandom = math.random;
+
+ var tinycolor = function(color, opts) {
+
+ color = (color) ? color : '';
+ opts = opts || { };
+
+ // If input is already a tinycolor, return itself
+ if (color instanceof tinycolor) {
+ return color;
+ }
+ // If we are called as a function, call using new instead
+ if (!(this instanceof tinycolor)) {
+ return new tinycolor(color, opts);
+ }
+
+ var rgb = inputToRGB(color);
+ this._originalInput = color;
+ this._r = rgb.r;
+ this._g = rgb.g;
+ this._b = rgb.b;
+ this._a = rgb.a;
+ this._roundA = mathRound(1000 * this._a) / 1000;
+ this._format = opts.format || rgb.format;
+ this._gradientType = opts.gradientType;
+
+ // Don't let the range of [0,255] come back in [0,1].
+ // Potentially lose a little bit of precision here, but will fix issues where
+ // .5 gets interpreted as half of the total, instead of half of 1
+ // If it was supposed to be 128, this was already taken care of by `inputToRgb`
+ if (this._r < 1) { this._r = mathRound(this._r); }
+ if (this._g < 1) { this._g = mathRound(this._g); }
+ if (this._b < 1) { this._b = mathRound(this._b); }
+
+ this._ok = rgb.ok;
+ this._tc_id = tinyCounter++;
+ };
+
+ tinycolor.prototype = {
+ isDark: function() {
+ return this.getBrightness() < 128;
+ },
+ isLight: function() {
+ return !this.isDark();
+ },
+ isValid: function() {
+ return this._ok;
+ },
+ getOriginalInput: function() {
+ return this._originalInput;
+ },
+ getFormat: function() {
+ return this._format;
+ },
+ getAlpha: function() {
+ return this._a;
+ },
+ getBrightness: function() {
+ var rgb = this.toRgb();
+ return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
+ },
+ setAlpha: function(value) {
+ this._a = boundAlpha(value);
+ this._roundA = mathRound(1000 * this._a) / 1000;
+ return this;
+ },
+ toHsv: function() {
+ var hsv = rgbToHsv(this._r, this._g, this._b);
+ return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
+ },
+ toHsvString: function() {
+ var hsv = rgbToHsv(this._r, this._g, this._b);
+ var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
+ return (this._a == 1) ?
+ "hsv(" + h + ", " + s + "%, " + v + "%)" :
+ "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
+ },
+ toHsl: function() {
+ var hsl = rgbToHsl(this._r, this._g, this._b);
+ return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
+ },
+ toHslString: function() {
+ var hsl = rgbToHsl(this._r, this._g, this._b);
+ var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
+ return (this._a == 1) ?
+ "hsl(" + h + ", " + s + "%, " + l + "%)" :
+ "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
+ },
+ toHex: function(allow3Char) {
+ return rgbToHex(this._r, this._g, this._b, allow3Char);
+ },
+ toHexString: function(allow3Char) {
+ return '#' + this.toHex(allow3Char);
+ },
+ toHex8: function() {
+ return rgbaToHex(this._r, this._g, this._b, this._a);
+ },
+ toHex8String: function() {
+ return '#' + this.toHex8();
+ },
+ toRgb: function() {
+ return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
+ },
+ toRgbString: function() {
+ return (this._a == 1) ?
+ "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
+ "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
+ },
+ toPercentageRgb: function() {
+ return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
+ },
+ toPercentageRgbString: function() {
+ return (this._a == 1) ?
+ "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
+ "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
+ },
+ toName: function() {
+ if (this._a === 0) {
+ return "transparent";
+ }
+
+ if (this._a < 1) {
+ return false;
+ }
+
+ return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
+ },
+ toFilter: function(secondColor) {
+ var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
+ var secondHex8String = hex8String;
+ var gradientType = this._gradientType ? "GradientType = 1, " : "";
+
+ if (secondColor) {
+ var s = tinycolor(secondColor);
+ secondHex8String = s.toHex8String();
+ }
+
+ return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
+ },
+ toString: function(format) {
+ var formatSet = !!format;
+ format = format || this._format;
+
+ var formattedString = false;
+ var hasAlpha = this._a < 1 && this._a >= 0;
+ var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
+
+ if (needsAlphaFormat) {
+ // Special case for "transparent", all other non-alpha formats
+ // will return rgba when there is transparency.
+ if (format === "name" && this._a === 0) {
+ return this.toName();
+ }
+ return this.toRgbString();
+ }
+ if (format === "rgb") {
+ formattedString = this.toRgbString();
+ }
+ if (format === "prgb") {
+ formattedString = this.toPercentageRgbString();
+ }
+ if (format === "hex" || format === "hex6") {
+ formattedString = this.toHexString();
+ }
+ if (format === "hex3") {
+ formattedString = this.toHexString(true);
+ }
+ if (format === "hex8") {
+ formattedString = this.toHex8String();
+ }
+ if (format === "name") {
+ formattedString = this.toName();
+ }
+ if (format === "hsl") {
+ formattedString = this.toHslString();
+ }
+ if (format === "hsv") {
+ formattedString = this.toHsvString();
+ }
+
+ return formattedString || this.toHexString();
+ },
+
+ _applyModification: function(fn, args) {
+ var color = fn.apply(null, [this].concat([].slice.call(args)));
+ this._r = color._r;
+ this._g = color._g;
+ this._b = color._b;
+ this.setAlpha(color._a);
+ return this;
+ },
+ lighten: function() {
+ return this._applyModification(lighten, arguments);
+ },
+ brighten: function() {
+ return this._applyModification(brighten, arguments);
+ },
+ darken: function() {
+ return this._applyModification(darken, arguments);
+ },
+ desaturate: function() {
+ return this._applyModification(desaturate, arguments);
+ },
+ saturate: function() {
+ return this._applyModification(saturate, arguments);
+ },
+ greyscale: function() {
+ return this._applyModification(greyscale, arguments);
+ },
+ spin: function() {
+ return this._applyModification(spin, arguments);
+ },
+
+ _applyCombination: function(fn, args) {
+ return fn.apply(null, [this].concat([].slice.call(args)));
+ },
+ analogous: function() {
+ return this._applyCombination(analogous, arguments);
+ },
+ complement: function() {
+ return this._applyCombination(complement, arguments);
+ },
+ monochromatic: function() {
+ return this._applyCombination(monochromatic, arguments);
+ },
+ splitcomplement: function() {
+ return this._applyCombination(splitcomplement, arguments);
+ },
+ triad: function() {
+ return this._applyCombination(triad, arguments);
+ },
+ tetrad: function() {
+ return this._applyCombination(tetrad, arguments);
+ }
+ };
+
+ // If input is an object, force 1 into "1.0" to handle ratios properly
+ // String input requires "1.0" as input, so 1 will be treated as 1
+ tinycolor.fromRatio = function(color, opts) {
+ if (typeof color == "object") {
+ var newColor = {};
+ for (var i in color) {
+ if (color.hasOwnProperty(i)) {
+ if (i === "a") {
+ newColor[i] = color[i];
+ }
+ else {
+ newColor[i] = convertToPercentage(color[i]);
+ }
+ }
+ }
+ color = newColor;
+ }
+
+ return tinycolor(color, opts);
+ };
+
+ // Given a string or object, convert that input to RGB
+ // Possible string inputs:
+ //
+ // "red"
+ // "#f00" or "f00"
+ // "#ff0000" or "ff0000"
+ // "#ff000000" or "ff000000"
+ // "rgb 255 0 0" or "rgb (255, 0, 0)"
+ // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
+ // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
+ // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
+ // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
+ // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
+ // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
+ //
+ function inputToRGB(color) {
+
+ var rgb = { r: 0, g: 0, b: 0 };
+ var a = 1;
+ var ok = false;
+ var format = false;
+
+ if (typeof color == "string") {
+ color = stringInputToObject(color);
+ }
+
+ if (typeof color == "object") {
+ if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
+ rgb = rgbToRgb(color.r, color.g, color.b);
+ ok = true;
+ format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
+ }
+ else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
+ color.s = convertToPercentage(color.s);
+ color.v = convertToPercentage(color.v);
+ rgb = hsvToRgb(color.h, color.s, color.v);
+ ok = true;
+ format = "hsv";
+ }
+ else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
+ color.s = convertToPercentage(color.s);
+ color.l = convertToPercentage(color.l);
+ rgb = hslToRgb(color.h, color.s, color.l);
+ ok = true;
+ format = "hsl";
+ }
+
+ if (color.hasOwnProperty("a")) {
+ a = color.a;
+ }
+ }
+
+ a = boundAlpha(a);
+
+ return {
+ ok: ok,
+ format: color.format || format,
+ r: mathMin(255, mathMax(rgb.r, 0)),
+ g: mathMin(255, mathMax(rgb.g, 0)),
+ b: mathMin(255, mathMax(rgb.b, 0)),
+ a: a
+ };
+ }
+
+
+ // Conversion Functions
+ // --------------------
+
+ // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
+ // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
+
+ // `rgbToRgb`
+ // Handle bounds / percentage checking to conform to CSS color spec
+ // <http://www.w3.org/TR/css3-color/>
+ // *Assumes:* r, g, b in [0, 255] or [0, 1]
+ // *Returns:* { r, g, b } in [0, 255]
+ function rgbToRgb(r, g, b){
+ return {
+ r: bound01(r, 255) * 255,
+ g: bound01(g, 255) * 255,
+ b: bound01(b, 255) * 255
+ };
+ }
+
+ // `rgbToHsl`
+ // Converts an RGB color value to HSL.
+ // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
+ // *Returns:* { h, s, l } in [0,1]
+ function rgbToHsl(r, g, b) {
+
+ r = bound01(r, 255);
+ g = bound01(g, 255);
+ b = bound01(b, 255);
+
+ var max = mathMax(r, g, b), min = mathMin(r, g, b);
+ var h, s, l = (max + min) / 2;
+
+ if(max == min) {
+ h = s = 0; // achromatic
+ }
+ else {
+ var d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch(max) {
+ case r: h = (g - b) / d + (g < b ? 6 : 0); break;
+ case g: h = (b - r) / d + 2; break;
+ case b: h = (r - g) / d + 4; break;
+ }
+
+ h /= 6;
+ }
+
+ return { h: h, s: s, l: l };
+ }
+
+ // `hslToRgb`
+ // Converts an HSL color value to RGB.
+ // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
+ // *Returns:* { r, g, b } in the set [0, 255]
+ function hslToRgb(h, s, l) {
+ var r, g, b;
+
+ h = bound01(h, 360);
+ s = bound01(s, 100);
+ l = bound01(l, 100);
+
+ function hue2rgb(p, q, t) {
+ if(t < 0) t += 1;
+ if(t > 1) t -= 1;
+ if(t < 1/6) return p + (q - p) * 6 * t;
+ if(t < 1/2) return q;
+ if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
+ return p;
+ }
+
+ if(s === 0) {
+ r = g = b = l; // achromatic
+ }
+ else {
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+ r = hue2rgb(p, q, h + 1/3);
+ g = hue2rgb(p, q, h);
+ b = hue2rgb(p, q, h - 1/3);
+ }
+
+ return { r: r * 255, g: g * 255, b: b * 255 };
+ }
+
+ // `rgbToHsv`
+ // Converts an RGB color value to HSV
+ // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
+ // *Returns:* { h, s, v } in [0,1]
+ function rgbToHsv(r, g, b) {
+
+ r = bound01(r, 255);
+ g = bound01(g, 255);
+ b = bound01(b, 255);
+
+ var max = mathMax(r, g, b), min = mathMin(r, g, b);
+ var h, s, v = max;
+
+ var d = max - min;
+ s = max === 0 ? 0 : d / max;
+
+ if(max == min) {
+ h = 0; // achromatic
+ }
+ else {
+ switch(max) {
+ case r: h = (g - b) / d + (g < b ? 6 : 0); break;
+ case g: h = (b - r) / d + 2; break;
+ case b: h = (r - g) / d + 4; break;
+ }
+ h /= 6;
+ }
+ return { h: h, s: s, v: v };
+ }
+
+ // `hsvToRgb`
+ // Converts an HSV color value to RGB.
+ // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
+ // *Returns:* { r, g, b } in the set [0, 255]
+ function hsvToRgb(h, s, v) {
+
+ h = bound01(h, 360) * 6;
+ s = bound01(s, 100);
+ v = bound01(v, 100);
+
+ var i = math.floor(h),
+ f = h - i,
+ p = v * (1 - s),
+ q = v * (1 - f * s),
+ t = v * (1 - (1 - f) * s),
+ mod = i % 6,
+ r = [v, q, p, p, t, v][mod],
+ g = [t, v, v, q, p, p][mod],
+ b = [p, p, t, v, v, q][mod];
+
+ return { r: r * 255, g: g * 255, b: b * 255 };
+ }
+
+ // `rgbToHex`
+ // Converts an RGB color to hex
+ // Assumes r, g, and b are contained in the set [0, 255]
+ // Returns a 3 or 6 character hex
+ function rgbToHex(r, g, b, allow3Char) {
+
+ var hex = [
+ pad2(mathRound(r).toString(16)),
+ pad2(mathRound(g).toString(16)),
+ pad2(mathRound(b).toString(16))
+ ];
+
+ // Return a 3 character hex if possible
+ if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
+ return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
+ }
+
+ return hex.join("");
+ }
+ // `rgbaToHex`
+ // Converts an RGBA color plus alpha transparency to hex
+ // Assumes r, g, b and a are contained in the set [0, 255]
+ // Returns an 8 character hex
+ function rgbaToHex(r, g, b, a) {
+
+ var hex = [
+ pad2(convertDecimalToHex(a)),
+ pad2(mathRound(r).toString(16)),
+ pad2(mathRound(g).toString(16)),
+ pad2(mathRound(b).toString(16))
+ ];
+
+ return hex.join("");
+ }
+
+ // `equals`
+ // Can be called with any tinycolor input
+ tinycolor.equals = function (color1, color2) {
+ if (!color1 || !color2) { return false; }
+ return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
+ };
+ tinycolor.random = function() {
+ return tinycolor.fromRatio({
+ r: mathRandom(),
+ g: mathRandom(),
+ b: mathRandom()
+ });
+ };
+
+
+ // Modification Functions
+ // ----------------------
+ // Thanks to less.js for some of the basics here
+ // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
+
+ function desaturate(color, amount) {
+ amount = (amount === 0) ? 0 : (amount || 10);
+ var hsl = tinycolor(color).toHsl();
+ hsl.s -= amount / 100;
+ hsl.s = clamp01(hsl.s);
+ return tinycolor(hsl);
+ }
+
+ function saturate(color, amount) {
+ amount = (amount === 0) ? 0 : (amount || 10);
+ var hsl = tinycolor(color).toHsl();
+ hsl.s += amount / 100;
+ hsl.s = clamp01(hsl.s);
+ return tinycolor(hsl);
+ }
+
+ function greyscale(color) {
+ return tinycolor(color).desaturate(100);
+ }
+
+ function lighten (color, amount) {
+ amount = (amount === 0) ? 0 : (amount || 10);
+ var hsl = tinycolor(color).toHsl();
+ hsl.l += amount / 100;
+ hsl.l = clamp01(hsl.l);
+ return tinycolor(hsl);
+ }
+
+ function brighten(color, amount) {
+ amount = (amount === 0) ? 0 : (amount || 10);
+ var rgb = tinycolor(color).toRgb();
+ rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
+ rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
+ rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
+ return tinycolor(rgb);
+ }
+
+ function darken (color, amount) {
+ amount = (amount === 0) ? 0 : (amount || 10);
+ var hsl = tinycolor(color).toHsl();
+ hsl.l -= amount / 100;
+ hsl.l = clamp01(hsl.l);
+ return tinycolor(hsl);
+ }
+
+ // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
+ // Values outside of this range will be wrapped into this range.
+ function spin(color, amount) {
+ var hsl = tinycolor(color).toHsl();
+ var hue = (mathRound(hsl.h) + amount) % 360;
+ hsl.h = hue < 0 ? 360 + hue : hue;
+ return tinycolor(hsl);
+ }
+
+ // Combination Functions
+ // ---------------------
+ // Thanks to jQuery xColor for some of the ideas behind these
+ // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
+
+ function complement(color) {
+ var hsl = tinycolor(color).toHsl();
+ hsl.h = (hsl.h + 180) % 360;
+ return tinycolor(hsl);
+ }
+
+ function triad(color) {
+ var hsl = tinycolor(color).toHsl();
+ var h = hsl.h;
+ return [
+ tinycolor(color),
+ tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
+ tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
+ ];
+ }
+
+ function tetrad(color) {
+ var hsl = tinycolor(color).toHsl();
+ var h = hsl.h;
+ return [
+ tinycolor(color),
+ tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
+ tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
+ tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
+ ];
+ }
+
+ function splitcomplement(color) {
+ var hsl = tinycolor(color).toHsl();
+ var h = hsl.h;
+ return [
+ tinycolor(color),
+ tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
+ tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
+ ];
+ }
+
+ function analogous(color, results, slices) {
+ results = results || 6;
+ slices = slices || 30;
+
+ var hsl = tinycolor(color).toHsl();
+ var part = 360 / slices;
+ var ret = [tinycolor(color)];
+
+ for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
+ hsl.h = (hsl.h + part) % 360;
+ ret.push(tinycolor(hsl));
+ }
+ return ret;
+ }
+
+ function monochromatic(color, results) {
+ results = results || 6;
+ var hsv = tinycolor(color).toHsv();
+ var h = hsv.h, s = hsv.s, v = hsv.v;
+ var ret = [];
+ var modification = 1 / results;
+
+ while (results--) {
+ ret.push(tinycolor({ h: h, s: s, v: v}));
+ v = (v + modification) % 1;
+ }
+
+ return ret;
+ }
+
+ // Utility Functions
+ // ---------------------
+
+ tinycolor.mix = function(color1, color2, amount) {
+ amount = (amount === 0) ? 0 : (amount || 50);
+
+ var rgb1 = tinycolor(color1).toRgb();
+ var rgb2 = tinycolor(color2).toRgb();
+
+ var p = amount / 100;
+ var w = p * 2 - 1;
+ var a = rgb2.a - rgb1.a;
+
+ var w1;
+
+ if (w * a == -1) {
+ w1 = w;
+ } else {
+ w1 = (w + a) / (1 + w * a);
+ }
+
+ w1 = (w1 + 1) / 2;
+
+ var w2 = 1 - w1;
+
+ var rgba = {
+ r: rgb2.r * w1 + rgb1.r * w2,
+ g: rgb2.g * w1 + rgb1.g * w2,
+ b: rgb2.b * w1 + rgb1.b * w2,
+ a: rgb2.a * p + rgb1.a * (1 - p)
+ };
+
+ return tinycolor(rgba);
+ };
+
+
+ // Readability Functions
+ // ---------------------
+ // <http://www.w3.org/TR/AERT#color-contrast>
+
+ // `readability`
+ // Analyze the 2 colors and returns an object with the following properties:
+ // `brightness`: difference in brightness between the two colors
+ // `color`: difference in color/hue between the two colors
+ tinycolor.readability = function(color1, color2) {
+ var c1 = tinycolor(color1);
+ var c2 = tinycolor(color2);
+ var rgb1 = c1.toRgb();
+ var rgb2 = c2.toRgb();
+ var brightnessA = c1.getBrightness();
+ var brightnessB = c2.getBrightness();
+ var colorDiff = (
+ Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
+ Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
+ Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
+ );
+
+ return {
+ brightness: Math.abs(brightnessA - brightnessB),
+ color: colorDiff
+ };
+ };
+
+ // `readable`
+ // http://www.w3.org/TR/AERT#color-contrast
+ // Ensure that foreground and background color combinations provide sufficient contrast.
+ // *Example*
+ // tinycolor.isReadable("#000", "#111") => false
+ tinycolor.isReadable = function(color1, color2) {
+ var readability = tinycolor.readability(color1, color2);
+ return readability.brightness > 125 && readability.color > 500;
+ };
+
+ // `mostReadable`
+ // Given a base color and a list of possible foreground or background
+ // colors for that base, returns the most readable color.
+ // *Example*
+ // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
+ tinycolor.mostReadable = function(baseColor, colorList) {
+ var bestColor = null;
+ var bestScore = 0;
+ var bestIsReadable = false;
+ for (var i=0; i < colorList.length; i++) {
+
+ // We normalize both around the "acceptable" breaking point,
+ // but rank brightness constrast higher than hue.
+
+ var readability = tinycolor.readability(baseColor, colorList[i]);
+ var readable = readability.brightness > 125 && readability.color > 500;
+ var score = 3 * (readability.brightness / 125) + (readability.color / 500);
+
+ if ((readable && ! bestIsReadable) ||
+ (readable && bestIsReadable && score > bestScore) ||
+ ((! readable) && (! bestIsReadable) && score > bestScore)) {
+ bestIsReadable = readable;
+ bestScore = score;
+ bestColor = tinycolor(colorList[i]);
+ }
+ }
+ return bestColor;
+ };
+
+
+ // Big List of Colors
+ // ------------------
+ // <http://www.w3.org/TR/css3-color/#svg-color>
+ var names = tinycolor.names = {
+ aliceblue: "f0f8ff",
+ antiquewhite: "faebd7",
+ aqua: "0ff",
+ aquamarine: "7fffd4",
+ azure: "f0ffff",
+ beige: "f5f5dc",
+ bisque: "ffe4c4",
+ black: "000",
+ blanchedalmond: "ffebcd",
+ blue: "00f",
+ blueviolet: "8a2be2",
+ brown: "a52a2a",
+ burlywood: "deb887",
+ burntsienna: "ea7e5d",
+ cadetblue: "5f9ea0",
+ chartreuse: "7fff00",
+ chocolate: "d2691e",
+ coral: "ff7f50",
+ cornflowerblue: "6495ed",
+ cornsilk: "fff8dc",
+ crimson: "dc143c",
+ cyan: "0ff",
+ darkblue: "00008b",
+ darkcyan: "008b8b",
+ darkgoldenrod: "b8860b",
+ darkgray: "a9a9a9",
+ darkgreen: "006400",
+ darkgrey: "a9a9a9",
+ darkkhaki: "bdb76b",
+ darkmagenta: "8b008b",
+ darkolivegreen: "556b2f",
+ darkorange: "ff8c00",
+ darkorchid: "9932cc",
+ darkred: "8b0000",
+ darksalmon: "e9967a",
+ darkseagreen: "8fbc8f",
+ darkslateblue: "483d8b",
+ darkslategray: "2f4f4f",
+ darkslategrey: "2f4f4f",
+ darkturquoise: "00ced1",
+ darkviolet: "9400d3",
+ deeppink: "ff1493",
+ deepskyblue: "00bfff",
+ dimgray: "696969",
+ dimgrey: "696969",
+ dodgerblue: "1e90ff",
+ firebrick: "b22222",
+ floralwhite: "fffaf0",
+ forestgreen: "228b22",
+ fuchsia: "f0f",
+ gainsboro: "dcdcdc",
+ ghostwhite: "f8f8ff",
+ gold: "ffd700",
+ goldenrod: "daa520",
+ gray: "808080",
+ green: "008000",
+ greenyellow: "adff2f",
+ grey: "808080",
+ honeydew: "f0fff0",
+ hotpink: "ff69b4",
+ indianred: "cd5c5c",
+ indigo: "4b0082",
+ ivory: "fffff0",
+ khaki: "f0e68c",
+ lavender: "e6e6fa",
+ lavenderblush: "fff0f5",
+ lawngreen: "7cfc00",
+ lemonchiffon: "fffacd",
+ lightblue: "add8e6",
+ lightcoral: "f08080",
+ lightcyan: "e0ffff",
+ lightgoldenrodyellow: "fafad2",
+ lightgray: "d3d3d3",
+ lightgreen: "90ee90",
+ lightgrey: "d3d3d3",
+ lightpink: "ffb6c1",
+ lightsalmon: "ffa07a",
+ lightseagreen: "20b2aa",
+ lightskyblue: "87cefa",
+ lightslategray: "789",
+ lightslategrey: "789",
+ lightsteelblue: "b0c4de",
+ lightyellow: "ffffe0",
+ lime: "0f0",
+ limegreen: "32cd32",
+ linen: "faf0e6",
+ magenta: "f0f",
+ maroon: "800000",
+ mediumaquamarine: "66cdaa",
+ mediumblue: "0000cd",
+ mediumorchid: "ba55d3",
+ mediumpurple: "9370db",
+ mediumseagreen: "3cb371",
+ mediumslateblue: "7b68ee",
+ mediumspringgreen: "00fa9a",
+ mediumturquoise: "48d1cc",
+ mediumvioletred: "c71585",
+ midnightblue: "191970",
+ mintcream: "f5fffa",
+ mistyrose: "ffe4e1",
+ moccasin: "ffe4b5",
+ navajowhite: "ffdead",
+ navy: "000080",
+ oldlace: "fdf5e6",
+ olive: "808000",
+ olivedrab: "6b8e23",
+ orange: "ffa500",
+ orangered: "ff4500",
+ orchid: "da70d6",
+ palegoldenrod: "eee8aa",
+ palegreen: "98fb98",
+ paleturquoise: "afeeee",
+ palevioletred: "db7093",
+ papayawhip: "ffefd5",
+ peachpuff: "ffdab9",
+ peru: "cd853f",
+ pink: "ffc0cb",
+ plum: "dda0dd",
+ powderblue: "b0e0e6",
+ purple: "800080",
+ rebeccapurple: "663399",
+ red: "f00",
+ rosybrown: "bc8f8f",
+ royalblue: "4169e1",
+ saddlebrown: "8b4513",
+ salmon: "fa8072",
+ sandybrown: "f4a460",
+ seagreen: "2e8b57",
+ seashell: "fff5ee",
+ sienna: "a0522d",
+ silver: "c0c0c0",
+ skyblue: "87ceeb",
+ slateblue: "6a5acd",
+ slategray: "708090",
+ slategrey: "708090",
+ snow: "fffafa",
+ springgreen: "00ff7f",
+ steelblue: "4682b4",
+ tan: "d2b48c",
+ teal: "008080",
+ thistle: "d8bfd8",
+ tomato: "ff6347",
+ turquoise: "40e0d0",
+ violet: "ee82ee",
+ wheat: "f5deb3",
+ white: "fff",
+ whitesmoke: "f5f5f5",
+ yellow: "ff0",
+ yellowgreen: "9acd32"
+ };
+
+ // Make it easy to access colors via `hexNames[hex]`
+ var hexNames = tinycolor.hexNames = flip(names);
+
+
+ // Utilities
+ // ---------
+
+ // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
+ function flip(o) {
+ var flipped = { };
+ for (var i in o) {
+ if (o.hasOwnProperty(i)) {
+ flipped[o[i]] = i;
+ }
+ }
+ return flipped;
+ }
+
+ // Return a valid alpha value [0,1] with all invalid values being set to 1
+ function boundAlpha(a) {
+ a = parseFloat(a);
+
+ if (isNaN(a) || a < 0 || a > 1) {
+ a = 1;
+ }
+
+ return a;
+ }
+
+ // Take input from [0, n] and return it as [0, 1]
+ function bound01(n, max) {
+ if (isOnePointZero(n)) { n = "100%"; }
+
+ var processPercent = isPercentage(n);
+ n = mathMin(max, mathMax(0, parseFloat(n)));
+
+ // Automatically convert percentage into number
+ if (processPercent) {
+ n = parseInt(n * max, 10) / 100;
+ }
+
+ // Handle floating point rounding errors
+ if ((math.abs(n - max) < 0.000001)) {
+ return 1;
+ }
+
+ // Convert into [0, 1] range if it isn't already
+ return (n % max) / parseFloat(max);
+ }
+
+ // Force a number between 0 and 1
+ function clamp01(val) {
+ return mathMin(1, mathMax(0, val));
+ }
+
+ // Parse a base-16 hex value into a base-10 integer
+ function parseIntFromHex(val) {
+ return parseInt(val, 16);
+ }
+
+ // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
+ // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
+ function isOnePointZero(n) {
+ return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
+ }
+
+ // Check to see if string passed in is a percentage
+ function isPercentage(n) {
+ return typeof n === "string" && n.indexOf('%') != -1;
+ }
+
+ // Force a hex value to have 2 characters
+ function pad2(c) {
+ return c.length == 1 ? '0' + c : '' + c;
+ }
+
+ // Replace a decimal with it's percentage value
+ function convertToPercentage(n) {
+ if (n <= 1) {
+ n = (n * 100) + "%";
+ }
+
+ return n;
+ }
+
+ // Converts a decimal to a hex value
+ function convertDecimalToHex(d) {
+ return Math.round(parseFloat(d) * 255).toString(16);
+ }
+ // Converts a hex value to a decimal
+ function convertHexToDecimal(h) {
+ return (parseIntFromHex(h) / 255);
+ }
+
+ var matchers = (function() {
+
+ // <http://www.w3.org/TR/css3-values/#integers>
+ var CSS_INTEGER = "[-\\+]?\\d+%?";
+
+ // <http://www.w3.org/TR/css3-values/#number-value>
+ var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
+
+ // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
+ var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
+
+ // Actual matching.
+ // Parentheses and commas are optional, but not required.
+ // Whitespace can take the place of commas or opening paren
+ var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+ var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+
+ return {
+ rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
+ rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
+ hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
+ hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
+ hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
+ hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
+ hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
+ hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
+ hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
+ };
+ })();
+
+ // `stringInputToObject`
+ // Permissive string parsing. Take in a number of formats, and output an object
+ // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
+ function stringInputToObject(color) {
+
+ color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
+ var named = false;
+ if (names[color]) {
+ color = names[color];
+ named = true;
+ }
+ else if (color == 'transparent') {
+ return { r: 0, g: 0, b: 0, a: 0, format: "name" };
+ }
+
+ // Try to match string input using regular expressions.
+ // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
+ // Just return an object and let the conversion functions handle that.
+ // This way the result will be the same whether the tinycolor is initialized with string or object.
+ var match;
+ if ((match = matchers.rgb.exec(color))) {
+ return { r: match[1], g: match[2], b: match[3] };
+ }
+ if ((match = matchers.rgba.exec(color))) {
+ return { r: match[1], g: match[2], b: match[3], a: match[4] };
+ }
+ if ((match = matchers.hsl.exec(color))) {
+ return { h: match[1], s: match[2], l: match[3] };
+ }
+ if ((match = matchers.hsla.exec(color))) {
+ return { h: match[1], s: match[2], l: match[3], a: match[4] };
+ }
+ if ((match = matchers.hsv.exec(color))) {
+ return { h: match[1], s: match[2], v: match[3] };
+ }
+ if ((match = matchers.hsva.exec(color))) {
+ return { h: match[1], s: match[2], v: match[3], a: match[4] };
+ }
+ if ((match = matchers.hex8.exec(color))) {
+ return {
+ a: convertHexToDecimal(match[1]),
+ r: parseIntFromHex(match[2]),
+ g: parseIntFromHex(match[3]),
+ b: parseIntFromHex(match[4]),
+ format: named ? "name" : "hex8"
+ };
+ }
+ if ((match = matchers.hex6.exec(color))) {
+ return {
+ r: parseIntFromHex(match[1]),
+ g: parseIntFromHex(match[2]),
+ b: parseIntFromHex(match[3]),
+ format: named ? "name" : "hex"
+ };
+ }
+ if ((match = matchers.hex3.exec(color))) {
+ return {
+ r: parseIntFromHex(match[1] + '' + match[1]),
+ g: parseIntFromHex(match[2] + '' + match[2]),
+ b: parseIntFromHex(match[3] + '' + match[3]),
+ format: named ? "name" : "hex"
+ };
+ }
+
+ return false;
+ }
+
+ window.tinycolor = tinycolor;
+ })();
+
+ $(function () {
+ if ($.fn.spectrum.load) {
+ $.fn.spectrum.processNativeColorInputs();
+ }
+ });
+
+});
diff --git a/op25/gr-op25_repeater/www/www-static/tsv-edit.html b/op25/gr-op25_repeater/www/www-static/tsv-edit.html
new file mode 100644
index 0000000..ae6df55
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/tsv-edit.html
@@ -0,0 +1,112 @@
+<!--
+ Copyright 2017, 2018 Max H. Parke KA1RBI
+ Copyright 2021 Michael Rose
+
+ This file is part of OP25
+
+ OP25 is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3, or (at your option)
+ any later version.
+
+ OP25 is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with OP25; see the file COPYING. If not, write to the Free
+ Software Foundation, Inc., 51 Franklin Street, Boston, MA
+ 02110-1301, USA.
+
+ -->
+<!DOCTYPE html>
+
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>OP25 - Edit TSV</title>
+ <script src="jquery.js"></script>
+ <script src="editor.js"></script>
+ <script src="main.js"></script>
+ <script src="config.js"></script>
+ <script src='spectrum.js'></script>
+ <link rel='stylesheet' href='spectrum.css' />
+ <link rel="stylesheet" type="text/css" id="style" href="main.css">
+ <script src="jquery.alerts.js"></script>
+
+ </head>
+ <body onload="javascript:tsv_onload();">
+ <a href="#" name="top"></a>
+ <div class="tsv-controls">
+ <!-- <table style="width: 705px; border-collapse: collapse; border: 0px solid var(~~bg-color);"> -->
+ <table class="tsv">
+ <tr colspan="2">
+ <td>
+ <div id="title" class="nac" style="font-weight: normal;">TSV Editing - OP25</div>
+ </td>
+ <td>
+ <p align="right"><a href="#" onclick="window.close();" style="text-decoration: none;" title="Close">&#x274C;</a></p>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <button onclick="this.blur(); begin();" id="btnLoad" title="Load from Server" class="btn">Load Talkgroups</button>&nbsp;&nbsp;
+ <button onclick="this.blur(); saveTable();"id="btnSave1" class="saveButton btn" title="Save to Server">Save Talkgroups</button>&nbsp;&nbsp;
+ <button onclick="this.blur(); dispImport();" class="importExport btn" title="Import TSV or CSV">Import</button>&nbsp;&nbsp;
+ <button onclick="tsv_csv();" class="importExport btn" title="Export as CSV">Export</button>
+ </td>
+ <td align='right'>
+ <span class="label">Status: </span>
+ <span id="message" class="value">Ready</span>
+ <img src="loading.gif" style="height: 15px;" id="loading">
+ </td>
+ </tr>
+ </table>
+ <br>
+ <input type="text" id="searchInput" style="width: 643px;" onkeyup="searchTsvTable()" placeholder="Filter" title="Search">
+ <div id="csv-upload" style="display: none;">
+ <table class=editor><th colspan="2">Import Data</th>
+ <tr><td>
+ <span class="label"> Select a CSV or TSV file to import. <br><br>
+ <input type="file" id="csvfile" name="filename">&nbsp;&nbsp;
+ <button id="importnow" onclick="this.blur(); importNow();">Import Now</button>
+ </td>
+ <td style="width: 100px; text-align: center;">
+ <button onclick="document.getElementById('csvfile').value='';" style="width: 80px;"> Reset </button><br>
+ <button onclick="this.blur(); hideImport();" style="width: 80px;"> Cancel </button>
+ </td>
+ </tr>
+ </table>
+ <br><br>
+ </div>
+ </div>
+ <div id="save-div">
+ <br>&nbsp;&nbsp;
+ <!-- <button onclick="saveTable();"id="btnSave" class="saveButton">Save Talkgroups</button>&nbsp;&nbsp;<br>&nbsp;&nbsp; -->
+ <!-- <button onclick="window.location.href='#top;'"id="btnSave" class="saveButton">Top</button>&nbsp;&nbsp;<br>&nbsp; -->
+ </div>
+ <div id="main"></div>
+ <!-- Main Content Area -->
+ <div class="footer">
+ &nbsp;<br><button onclick="saveTable();"id="btnSave2" class="saveButton">Save Talkgroups</button>
+ &nbsp;
+ &nbsp;
+ <button class="btn" onclick="up();">Go to Top</button>&nbsp;&nbsp;&nbsp;
+ <button class="importExport btn" onclick="tsv_csv();">Export as CSV</button>&nbsp;&nbsp;&nbsp;
+ <a href="tsv-edit.html?mode=color&css=dark" target="_blank"><button id="btnColorEditor" class="btn" onclick="this.blur();">Colors Editor</button></a> &nbsp;&nbsp;&nbsp;
+ <button onclick="this.blur(); help();" class="btnHelp btn">Help</button>&nbsp;&nbsp;
+ <button class="btn" onclick="window.close();">Close</button>
+ <br>
+ </div>
+
+ <div style="display: none;"> <!-- placeholder for the color values -->
+ <span id="loadSettings"></span>
+ <input type="color" class="accColor" id="acc1"></input>
+ <input type="color" class="accColor" id="acc2"></input>
+ <input type="color" class="valColor" id="valColor">
+ <input type="color" class="sysColor" id="sysColor"></input>
+ <input type="color" class="btnColor" id="btnColor"></input>
+ </div>
+ </body>
+</html>
diff --git a/op25/gr-op25_repeater/www/www-static/tsv-help.html b/op25/gr-op25_repeater/www/www-static/tsv-help.html
new file mode 100644
index 0000000..93b36e4
--- /dev/null
+++ b/op25/gr-op25_repeater/www/www-static/tsv-help.html
@@ -0,0 +1,66 @@
+<div id="editor-help">
+ <table class="tsv">
+ <tr colspan="2">
+ <td>
+ <div id="title" class="nac" style="font-weight: normal;">TSV Editor Help</div>
+ </td>
+ <td>
+ <p align="right"><a href="#" onclick="closeHelp();" style="text-decoration: none;" title="Close Help">&#x274C;</a>&nbsp;&nbsp;</p>
+ </td>
+ </tr>
+ </table>
+
+ Hint: Navigate to the TSV entry by double-clicking on the entry in the Call History table or the Active Frequency table. The script cannot (currently) navigate to range values.
+
+ <h3>Saving Data</h3>
+
+ After editing, click Save Talkgroups or Save Source IDs. The TSV file will be written to the server, and the Reload TSV command will be sent automatically to OP25.<br><br>
+
+ Force TSV Reload: <button onclick="this.blur(); command_reload_tsv(nac);" id="btnReload" title="Send Relaod TSV Command to Server">OP25 Reload IDs</button>
+
+ <br><br><span class="red_value">Important: </span>After creating a new entry, click Save. After deleting an entry or multiple enteries, click Save. If not, the changes will be abandoned.
+ <br>
+
+ <h3>Creating and Deleting Enteries</h3>
+
+ <h3>Talkgroup IDs</h3>
+
+ <b>Talkgroup ID Field</b> <br> Can be one of either 1) specific value 2) range of values 3) wildcard values:<br><br>
+
+ <b>Specific Value: 123456</b> <br> Matches ID 123456 <br><br>
+
+ <b>Range of Value: 123* </b> <br> Match any ID starting with 123 <br><br>
+
+ <b>Range of Value: 123... </b> <br> Match 123456 but not 1234567 (length is checked) (dot dot dot ) <br>
+
+ <b>Range of Value: 1234-1250 </b><br> Matches the range (inclusive of first and last)<br><br>
+
+ <h3>Priority / Color Field - Talkgroups</h3>
+
+ A three value 0 through 999 where the first digit represents priority and the last 2 digits represent the CSS color code. (See Config tab, Show Colors button in the OP25 ui.)<br>
+
+ <br>Example: 502: Priority 5, color 02 - 914:Priority 9, Color 12
+
+ Higher priority value (9) = greatest priority.<br><br>
+
+ <button onclick="this.blur(); displayColors();">Show Colors</button> &nbsp;&nbsp; Display color codes for use in TSV files.
+
+ <h3>Source IDs</h3>
+
+ <b>Source ID Field</b> <br> Can be one of either 1) specific value 2) range of values 3) wildcard values:<br><br>
+
+ <b>Specific Value: 123456</b> <br> Matches ID 123456 <br>
+
+ <b>Range of Value: 123* </b> <br> Match any ID starting with 123 <br>
+
+ <b>Range of Value: 123... </b> <br> Match 123456 but not 1234567 (length is checked) (dot dot dot ) <br>
+
+ <b>Range of Value: 1234-1250 </b> <br> Matches the range (inclusive of first and last)<br>
+
+ <h3>Priority / Color Field - Sources</h3>
+
+ A single value 0 through 99 corresponding to the CSS colors. (See Config tab, Show Colors button in the OP25 ui.)
+
+
+</div>
+<br><br><br><br><br><br><br> \ No newline at end of file
diff --git a/scripts/blacklist-rtl.conf b/scripts/blacklist-rtl.conf
new file mode 100644
index 0000000..f723da3
--- /dev/null
+++ b/scripts/blacklist-rtl.conf
@@ -0,0 +1,4 @@
+blacklist dvb_usb_rtl28xxu
+blacklist rtl2832
+blacklist rtl2830
+blacklist rtl2838
diff --git a/scripts/do_sed.sh b/scripts/do_sed.sh
new file mode 100755
index 0000000..eb84eb9
--- /dev/null
+++ b/scripts/do_sed.sh
@@ -0,0 +1,12 @@
+#! /bin/bash
+
+srcs=`find lib include -name '*.c' -o -name '*.h' -o -name '*.cc'`
+files=`grep -l 'boost.*shared_ptr' $srcs`
+
+dir=`pwd`
+
+for f in $files; do
+ echo editing file $f in $dir
+ sed -i 's%boost/shared_ptr.hpp%memory%' $f
+ sed -i 's%boost::shared_ptr%std::shared_ptr%' $f
+done
diff --git a/scripts/do_sedb.sh b/scripts/do_sedb.sh
new file mode 100755
index 0000000..080ca41
--- /dev/null
+++ b/scripts/do_sedb.sh
@@ -0,0 +1,32 @@
+#! /bin/bash
+
+me=$0
+f=$1
+
+echo "$me processing $f"
+
+sed -i -f - $f << EOF
+/^# Make sure our local CMake Modules path comes first/i\
+########################################################################\n\
+# Find boost\n\
+########################################################################\n\
+if(UNIX AND EXISTS "/usr/lib64")\n\
+ list(APPEND BOOST_LIBRARYDIR "/usr/lib64") #fedora 64-bit fix\n\
+endif(UNIX AND EXISTS "/usr/lib64")\n\
+set(Boost_ADDITIONAL_VERSIONS\n\
+ "1.35.0" "1.35" "1.36.0" "1.36" "1.37.0" "1.37" "1.38.0" "1.38" "1.39.0" "1.39"\n\
+ "1.40.0" "1.40" "1.41.0" "1.41" "1.42.0" "1.42" "1.43.0" "1.43" "1.44.0" "1.44"\n\
+ "1.45.0" "1.45" "1.46.0" "1.46" "1.47.0" "1.47" "1.48.0" "1.48" "1.49.0" "1.49"\n\
+ "1.50.0" "1.50" "1.51.0" "1.51" "1.52.0" "1.52" "1.53.0" "1.53" "1.54.0" "1.54"\n\
+ "1.55.0" "1.55" "1.56.0" "1.56" "1.57.0" "1.57" "1.58.0" "1.58" "1.59.0" "1.59"\n\
+ "1.60.0" "1.60" "1.61.0" "1.61" "1.62.0" "1.62" "1.63.0" "1.63" "1.64.0" "1.64"\n\
+ "1.65.0" "1.65" "1.66.0" "1.66" "1.67.0" "1.67" "1.68.0" "1.68" "1.69.0" "1.69"\n\
+ "1.74.0" "1.74"\n\
+)\n\
+find_package(Boost "1.35" COMPONENTS filesystem system)\n\
+\n\
+if(NOT Boost_FOUND)\n\
+ message(FATAL_ERROR "Boost required to compile op25")\n\
+endif()\n\
+
+EOF
diff --git a/scripts/do_sedc.sh b/scripts/do_sedc.sh
new file mode 100755
index 0000000..687ab8e
--- /dev/null
+++ b/scripts/do_sedc.sh
@@ -0,0 +1,6 @@
+#! /bin/bash
+
+me=$0
+f=$1
+echo "$me editing file $f"
+sed -i '/^find_package(Gnuradio .*REQUIRED)/s/)/ COMPONENTS blocks fft filter)/' $f
diff --git a/scripts/do_sedm.sh b/scripts/do_sedm.sh
new file mode 100755
index 0000000..170f2df
--- /dev/null
+++ b/scripts/do_sedm.sh
@@ -0,0 +1,19 @@
+#! /bin/bash
+
+me=$0
+srcs=`find lib include -name '*.c' -o -name '*.h' -o -name '*.cc'`
+dir=`pwd`
+
+files=`grep -l -e 'gr::message' -e 'gr::msg_queue' $srcs`
+for f in $files; do
+ echo $me editing file $f in $dir
+ sed -i 's%gr::msg_queue%gr::op25::msg_queue%g' $f
+ sed -i 's%gr::message%gr::op25::message%g' $f
+done
+
+files=`grep -l -e 'include.*gnuradio/message' -e 'include.*gnuradio/msg_queue' $srcs`
+for f in $files; do
+ echo $me editing file $f in $dir
+ sed -i 's%gnuradio/msg_queue%op25/msg_queue%g' $f
+ sed -i 's%gnuradio/message%op25/message%g' $f
+done
diff --git a/scripts/do_sedp.sh b/scripts/do_sedp.sh
new file mode 100755
index 0000000..f2e66b6
--- /dev/null
+++ b/scripts/do_sedp.sh
@@ -0,0 +1,27 @@
+#! /bin/bash
+
+me=$0
+f=$1
+
+echo "$me processing $f"
+
+sed -i -f - $f << EOF
+/Set the version information here/i\
+###############################################################\n\
+# Determine where to install python libs\n\
+###############################################################\n\
+execute_process(COMMAND python3 -c "\n\
+import os\n\
+import sys\n\
+pfx = '/usr/local'\n\
+path=os.path.join(pfx, 'lib', 'python%d.%d' % sys.version_info[:2], 'dist-packages')\n\
+if os.path.isdir(path) and path in sys.path:\n\
+ print(path)\n\
+ sys.exit(0)\n\
+p=[path for path in sys.path if path.startswith(pfx)][0]\n\
+print(p)\n\
+" OUTPUT_VARIABLE OP25_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE\n\
+)\n\
+MESSAGE(STATUS "OP25_PYTHON_DIR has been set to \\\"\${OP25_PYTHON_DIR}\\\".")\n\
+
+EOF
diff --git a/scripts/do_sedp2.sh b/scripts/do_sedp2.sh
new file mode 100755
index 0000000..c1c4111
--- /dev/null
+++ b/scripts/do_sedp2.sh
@@ -0,0 +1,13 @@
+#! /bin/bash
+
+me=$0
+dir=$1
+files=`grep -lr GR_PYTHON_DIR ${dir}`
+
+echo "$me processing directory $dir, files $files"
+
+for f in $files; do
+ echo editing $f
+ sed -i '/GR_PYTHON_DIR/s%GR_PYTHON_DIR}/gnuradio%OP25_PYTHON_DIR}%' $f
+done
+
diff --git a/scripts/do_sedpy.sh b/scripts/do_sedpy.sh
new file mode 100755
index 0000000..b03cfcd
--- /dev/null
+++ b/scripts/do_sedpy.sh
@@ -0,0 +1,23 @@
+#! /bin/sh
+
+me=$0
+
+py=`find . -type f -name '*.py' | grep -v doxy`
+
+files=`grep -l 'filter\.firdes\.WIN_' $py`
+for f in $files; do
+ echo $me editing $f
+ sed -i 's/filter\.firdes\.WIN_/fft.window.WIN_/' $f
+done
+
+files=`grep -l 'gr\.msg_queue' $py`
+for f in $files; do
+ echo $me editing $f
+ sed -i 's/gr\.msg_queue/op25.msg_queue/' $f
+done
+
+files=`grep -l 'gr\.message' $py`
+for f in $files; do
+ echo $me editing $f
+ sed -i 's/gr\.message/op25.message/' $f
+done
diff --git a/scripts/udev_rules.sh b/scripts/udev_rules.sh
new file mode 100755
index 0000000..88eb3fa
--- /dev/null
+++ b/scripts/udev_rules.sh
@@ -0,0 +1,20 @@
+#! /bin/sh
+
+if [ ! -f $PWD/blacklist-rtl.conf ]; then
+ echo "error, you must change to the op25/scripts directory prior to running this script"
+ exit 1
+fi
+
+# blacklist rtl dtv drivers
+if [ ! -f /etc/modprobe.d/blacklist-rtl.conf ]; then
+ echo ====== installing blacklist-rtl.conf
+ echo ====== please reboot before running op25
+ sudo install -m 0644 ./blacklist-rtl.conf /etc/modprobe.d/
+fi
+
+# fix borked airspy udev rule to allow used of airspy device when running headless
+if [ -f /lib/udev/rules.d/60-libairspy0.rules ]; then
+ echo ====== fixing libairspy0 udev rule
+ echo ====== please reboot before running op25
+ sudo sed -i 's^TAG+="uaccess"^MODE="660", GROUP="plugdev"^g' /lib/udev/rules.d/60-libairspy0.rules
+fi