Is this Tic-Tac-Toe board valid? Challenge

Given a tic-tac-toe board in any format, determine if it is valid or not. If a board can be the result of a tic-tac-toe game, then it is valid. For example, this board is valid:X O X
O X O
X O XOn the contrary, this board is invalid:

X X X
X X O
O O O

Input


A full (9/9) tic tac toe board (the outcome, not the game).


Rules


The input format must be able to depict all 512 possible input boards. It must be specified, along with the instructions to create it if it is obscure/unclear. You must state the marks of the board individually though.
There must be two possible outputs, one for validity and one for invalidity.
You can assume the board does not have empty spots.


Test cases

Valid:

X O X
O X O
X O X

X O X
X O X
O X O

X O O
O O X
O X X

O X O
X O X
O X O

Invalid:

X X X
X X X
X X X

O O O
O O O
O O O

X X X
O O O
X X X

O O O
O O X
X X X

X X O
O X O
O O X

A little help?

A board is considered valid (for this challenge) if and only if the following two conditions hold:


There are 5 X and 4 O, or 4 X and 5 O. For example,
X X X
O X O
X X Xis considered invalid, because there are 7 Xs and 2 Os.
Only the player with 5 marks has won, or none of them have won. For example,
X X X
O O O
O O Xis considered invalid, since either the row of Os or the row of Xs will be formed first. The two players can't have their turn simultaneously.


The current winner is...

...ais523's Jelly answer, at an astounding 26 bytes!
JavaScript (ES6), 88 87 bytes

s=&gt;(a=[...s]).sort()[5]-a[3]&amp;[7,56,73,84,146,273,292,448].every(j=&gt;j&amp;i,i=`0b`+s^~-a[4])


Takes input as a string of 9 0 and 1 characters and returns 1 for valid, 0 for invalid. We sort the characters into order. If the middle three characters are now the same then the board is invalid as there are too many of one piece. Otherwise, we convert the original board into binary, flipping the bits if there are more 0s than 1s. At this point the board is valid if 0 does not have a line of three, so we simply test all eight lines via an array of bitmasks. Edit: Saved 1 byte thanks to @ETHproductions.